blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
sequencelengths
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
sequencelengths
1
1
author
stringlengths
0
119
820cae76ba7cb514f0a8833285427988ecce6119
5ef0b4d230dc5243225d149efb44cdcdd2ffea9d
/trunk/cpp-tests/2420-content/examples/int swap 1.cpp
deb1ca0fc7fdbe4d09e209c7cc6207e5db8695f3
[]
no_license
kai-zhu/the-teaching-machine-and-webwriter
3d3b3dfdecd61e0fb2146b44c42d6467489fd94f
67adf8f41bb475108c285eb0894906cb0878849c
refs/heads/master
2021-01-16T20:47:55.620437
2016-05-23T12:38:03
2016-05-23T12:38:12
61,149,759
1
0
null
2016-06-14T19:22:57
2016-06-14T19:22:57
null
UTF-8
C++
false
false
546
cpp
#include <iostream> // info from standard library using namespace std; // cout is in the std namespace /******* Pass-by-Value Demo ******** We look at a FAULTY swap function to see how C passes by value *******************************************/ void swap(int a1, int a2); void main(){ int a = 1; int b = 2; cout << "a: " << a << " & b: " << b <<'\n'; swap(a,b); cout << "a: " << a << " & b: " << b <<'\n'; } void swap(int a1, int a2){ int temp = a1; a1 = a2; a2 = temp; }
2602b5ccd2a9d1eb990e3c923f825398e2fef03f
228e00812cc2428c1421565e5be3e04bf3660759
/ifc/fahrer.h
12ee117d19463378e30c5dbe07ec2c2380404969
[ "LicenseRef-scancode-warranty-disclaimer", "Artistic-1.0", "MIT" ]
permissive
4ssfscker/node-sim
dbfbec5d41988a5f4e1562babea89ccc86c04a2f
2bd3422fd645f415024907c9cf92697057cbc222
refs/heads/master
2021-01-24T10:38:14.973367
2007-06-09T15:12:10
2018-03-04T05:47:05
123,057,027
0
0
null
null
null
null
ISO-8859-1
C++
false
false
1,001
h
/* fahrer.h * * Interface für Verbindung von Fahrzeugen mit der Route * * 15.01.00, Hj. Malthaner */ #ifndef fahrer_h #define fahrer_h class grund_t; /** * Interface für Verbindung von Fahrzeugen mit der Route. * * @author Hj. Malthaner, 15.01.00 * @version $Revision: 1.8 $ */ class fahrer_t { public: virtual ~fahrer_t() {} virtual bool ist_befahrbar(const grund_t* ) const = 0; /** * Ermittelt die für das Fahrzeug geltenden Richtungsbits, * abhängig vom Untergrund. * * @author Hj. Malthaner, 03.01.01 */ virtual ribi_t::ribi gib_ribi(const grund_t* ) const = 0; virtual waytype_t gib_waytype() const = 0; // how expensive to go here (for way search) with the maximum convoi speed as second parameter virtual int gib_kosten(const grund_t *,const uint32) const = 0; // returns true for the way search to an unknown target. // first is current ground, second is starting ground virtual bool ist_ziel(const grund_t *,const grund_t *) const = 0; }; #endif
729d61f20cadf26c8254c7a0baa365456b13e909
430c6c11d9c6e4d9fda07454dfc84c26f7feccf7
/MQ5.ino
5be858430351b0bddba925f8237765af53013dd2
[]
no_license
GDBhatti/Vyadh
95a5b5f1234d0065fe8081182639eede8034e788
1acd776859975c75e124c7cef6841698f162b74d
refs/heads/master
2020-04-24T18:17:54.703517
2019-02-23T11:08:09
2019-02-23T11:08:09
172,175,494
0
0
null
null
null
null
UTF-8
C++
false
false
187
ino
float sensor=A0; float gas_value; void setup() { pinMode(sensor,INPUT); Serial.begin(9600); } void loop() { gas_value=analogRead(sensor); Serial.println(gas_value); }
4174b74bb014cc9a1c12e66c746aae73474f1dee
3e5aa39c132608716635aa7cbc905c2399fa84dd
/IGC/WrapperLLVM/include/llvmWrapper/Support/Alignment.h
5fe1bc9511cae6953c300b8fe2da9922b9029c74
[ "MIT" ]
permissive
krupenik/intel-graphics-compiler
04e3da63e1c9e10f3dfbb6455666751f726e23b0
8dc771cc827f29ade02b0721e227990162084dbf
refs/heads/master
2022-10-23T03:39:22.675288
2020-06-18T20:31:31
2020-06-19T17:01:15
273,596,762
0
0
MIT
2020-06-19T22:22:32
2020-06-19T22:22:32
null
UTF-8
C++
false
false
1,915
h
/*===================== begin_copyright_notice ================================== Copyright (c) 2017 Intel Corporation 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. ======================= end_copyright_notice ==================================*/ #ifndef IGCLLVM_SUPPORT_ALIGNMENT_H #define IGCLLVM_SUPPORT_ALIGNMENT_H #if LLVM_VERSION_MAJOR >= 10 #include <llvm/Support/Alignment.h> using namespace llvm; #endif #if LLVM_VERSION_MAJOR < 10 #include <cstdint> #define MaybeAlign(n) (n) #endif namespace IGCLLVM { #if LLVM_VERSION_MAJOR < 10 inline uint64_t getAlignmentValue(uint64_t Val) { return Val; } inline uint64_t getAlign(uint64_t Val) { return Val; } #else inline uint64_t getAlignmentValue(llvm::Align A) { return A.value(); } inline uint64_t getAlignmentValue(uint64_t Val) { return Val; } inline llvm::Align getAlign(uint64_t Val) { return llvm::Align{Val}; } #endif } // namespace IGCLLVM #endif
52dc218c2def62a1be4f58e296bfcddb95cffa70
e217eaf05d0dab8dd339032b6c58636841aa8815
/Ifc2x3/src/OpenInfraPlatform/Ifc2x3/entity/IfcLogicalOperatorEnum.cpp
854cf0aebceb0a15126919ae2d107dc447602e61
[]
no_license
bigdoods/OpenInfraPlatform
f7785ebe4cb46e24d7f636e1b4110679d78a4303
0266e86a9f25f2ea9ec837d8d340d31a58a83c8e
refs/heads/master
2021-01-21T03:41:20.124443
2016-01-26T23:20:21
2016-01-26T23:20:21
57,377,206
0
1
null
2016-04-29T10:38:19
2016-04-29T10:38:19
null
UTF-8
C++
false
false
1,703
cpp
/*! \verbatim * \copyright Copyright (c) 2014 Julian Amann. All rights reserved. * \date 2014-04-26 17:30 * \author Julian Amann <[email protected]> (https://www.cms.bgu.tum.de/en/team/amann) * \brief This file is part of the BlueFramework. * \endverbatim */ #include <sstream> #include <limits> #include <map> #include "reader/ReaderUtil.h" #include "writer/WriterUtil.h" #include "../model/shared_ptr.h" #include "../model/Ifc2x3Exception.h" #include "include/IfcLogicalOperatorEnum.h" namespace OpenInfraPlatform { namespace Ifc2x3 { // TYPE IfcLogicalOperatorEnum IfcLogicalOperatorEnum::IfcLogicalOperatorEnum() {} IfcLogicalOperatorEnum::~IfcLogicalOperatorEnum() {} void IfcLogicalOperatorEnum::getStepParameter( std::stringstream& stream, bool is_select_type ) const { if( is_select_type ) { stream << "IFCLOGICALOPERATORENUM("; } if( m_enum == ENUM_LOGICALAND ) { stream << ".LOGICALAND."; } else if( m_enum == ENUM_LOGICALOR ) { stream << ".LOGICALOR."; } if( is_select_type ) { stream << ")"; } } shared_ptr<IfcLogicalOperatorEnum> IfcLogicalOperatorEnum::readStepData( std::string& arg ) { // read TYPE if( arg.compare( "$" ) == 0 ) { return shared_ptr<IfcLogicalOperatorEnum>(); } shared_ptr<IfcLogicalOperatorEnum> type_object( new IfcLogicalOperatorEnum() ); if( _stricmp( arg.c_str(), ".LOGICALAND." ) == 0 ) { type_object->m_enum = IfcLogicalOperatorEnum::ENUM_LOGICALAND; } else if( _stricmp( arg.c_str(), ".LOGICALOR." ) == 0 ) { type_object->m_enum = IfcLogicalOperatorEnum::ENUM_LOGICALOR; } return type_object; } } // end namespace Ifc2x3 } // end namespace OpenInfraPlatform
dccbd514e796373dbd90255608139076a37aec09
04b1803adb6653ecb7cb827c4f4aa616afacf629
/chrome/browser/chromeos/login/screens/terms_of_service_screen.cc
39b3524d359960af90bd43b45a48c0491c703dfa
[ "BSD-3-Clause" ]
permissive
Samsung/Castanets
240d9338e097b75b3f669604315b06f7cf129d64
4896f732fc747dfdcfcbac3d442f2d2d42df264a
refs/heads/castanets_76_dev
2023-08-31T09:01:04.744346
2021-07-30T04:56:25
2021-08-11T05:45:21
125,484,161
58
49
BSD-3-Clause
2022-10-16T19:31:26
2018-03-16T08:07:37
null
UTF-8
C++
false
false
5,992
cc
// Copyright (c) 2013 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 "chrome/browser/chromeos/login/screens/terms_of_service_screen.h" #include <string> #include <utility> #include "base/bind.h" #include "base/location.h" #include "base/logging.h" #include "base/time/time.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chromeos/login/wizard_controller.h" #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h" #include "chrome/browser/net/system_network_context_manager.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ui/webui/chromeos/login/terms_of_service_screen_handler.h" #include "chrome/common/pref_names.h" #include "components/prefs/pref_service.h" #include "content/public/browser/storage_partition.h" #include "net/http/http_response_headers.h" #include "services/network/public/cpp/resource_request.h" #include "services/network/public/cpp/simple_url_loader.h" #include "services/network/public/mojom/url_loader_factory.mojom.h" #include "url/gurl.h" namespace chromeos { TermsOfServiceScreen::TermsOfServiceScreen( TermsOfServiceScreenView* view, const ScreenExitCallback& exit_callback) : BaseScreen(TermsOfServiceScreenView::kScreenId), view_(view), exit_callback_(exit_callback) { DCHECK(view_); if (view_) view_->SetDelegate(this); } TermsOfServiceScreen::~TermsOfServiceScreen() { if (view_) view_->SetDelegate(NULL); } void TermsOfServiceScreen::OnDecline() { exit_callback_.Run(Result::DECLINED); } void TermsOfServiceScreen::OnAccept() { exit_callback_.Run(Result::ACCEPTED); } void TermsOfServiceScreen::OnViewDestroyed(TermsOfServiceScreenView* view) { if (view_ == view) view_ = NULL; } void TermsOfServiceScreen::Show() { if (!view_) return; // Set the domain name whose Terms of Service are being shown. policy::BrowserPolicyConnectorChromeOS* connector = g_browser_process->platform_part()->browser_policy_connector_chromeos(); view_->SetDomain(connector->GetEnterpriseDisplayDomain()); // Show the screen. view_->Show(); // Start downloading the Terms of Service. StartDownload(); } void TermsOfServiceScreen::Hide() { if (view_) view_->Hide(); } void TermsOfServiceScreen::StartDownload() { const PrefService* prefs = ProfileManager::GetActiveUserProfile()->GetPrefs(); // If an URL from which the Terms of Service can be downloaded has not been // set, show an error message to the user. std::string terms_of_service_url = prefs->GetString(prefs::kTermsOfServiceURL); if (terms_of_service_url.empty()) { if (view_) view_->OnLoadError(); return; } net::NetworkTrafficAnnotationTag traffic_annotation = net::DefineNetworkTrafficAnnotation("terms_of_service_fetch", R"( semantics { sender: "Chrome OS Terms of Service" description: "Chrome OS downloads the latest terms of service document " "from Google servers." trigger: "When a public session starts on managed devices and an admin " "has uploaded a terms of service document for the domain." data: "URL of the terms of service document. " "No user information is sent." destination: WEBSITE } policy { cookies_allowed: YES cookies_store: "user" setting: "Unconditionally enabled on Chrome OS." policy_exception_justification: "Not implemented, considered not useful." })"); // Start downloading the Terms of Service. auto resource_request = std::make_unique<network::ResourceRequest>(); resource_request->url = GURL(terms_of_service_url); // Request a text/plain MIME type as only plain-text Terms of Service are // accepted. resource_request->headers.SetHeader("Accept", "text/plain"); terms_of_service_loader_ = network::SimpleURLLoader::Create( std::move(resource_request), traffic_annotation); // Retry up to three times if network changes are detected during the // download. terms_of_service_loader_->SetRetryOptions( 3, network::SimpleURLLoader::RETRY_ON_NETWORK_CHANGE); network::mojom::URLLoaderFactory* loader_factory = g_browser_process->system_network_context_manager() ->GetURLLoaderFactory(); terms_of_service_loader_->DownloadToStringOfUnboundedSizeUntilCrashAndDie( loader_factory, base::BindOnce(&TermsOfServiceScreen::OnDownloaded, base::Unretained(this))); // Abort the download attempt if it takes longer than one minute. download_timer_.Start(FROM_HERE, base::TimeDelta::FromMinutes(1), this, &TermsOfServiceScreen::OnDownloadTimeout); } void TermsOfServiceScreen::OnDownloadTimeout() { // Destroy the fetcher, which will abort the download attempt. terms_of_service_loader_.reset(); // Show an error message to the user. if (view_) view_->OnLoadError(); } void TermsOfServiceScreen::OnDownloaded( std::unique_ptr<std::string> response_body) { download_timer_.Stop(); // Destroy the fetcher when this method returns. std::unique_ptr<network::SimpleURLLoader> loader( std::move(terms_of_service_loader_)); if (!view_) return; // If the Terms of Service could not be downloaded, do not have a MIME type of // text/plain or are empty, show an error message to the user. if (!response_body || *response_body == "" || !loader->ResponseInfo() || loader->ResponseInfo()->mime_type != "text/plain") { view_->OnLoadError(); } else { // If the Terms of Service were downloaded successfully, show them to the // user. view_->OnLoadSuccess(*response_body); } } } // namespace chromeos
fdd3be4e39899ed0cc0ab0293721bec329efcfb9
2b8b8034e0e902341a2191f8d14ad1173ad9b0ae
/lib/widgets/KFileTreeDirUp.cpp
aba655fcc8bcf7711a83dd758c44765d990cd97f
[]
no_license
Frizlab/kodisein
3a4e48d4448ba6290a95394c33adcdf0c3013f04
1aece4de5946930936745330ba68d1d7339715bc
refs/heads/master
2022-06-03T19:52:37.473697
2021-03-25T19:43:54
2021-03-25T19:43:54
92,667,843
0
0
null
null
null
null
UTF-8
C++
false
false
1,647
cpp
/* * KFileTreeDirUp.cpp * kodisein */ #include "KFileTreeDirUp.h" #include "KFileTreeDir.h" #include "KEventHandler.h" #include "KTools.h" KDL_CLASS_INTROSPECTION_1 (KFileTreeDirUp, KFileTreeNode) // -------------------------------------------------------------------------------------------------------- KFileTreeDirUp::KFileTreeDirUp () : KFileTreeNode ( ".." ) { node_color.setValues (0.0, 0.0, 1.0, KDL_FILETREENODE_DEFAULT_ALPHA); type = KDL_FILE_TYPE_DIR; current_dir_node = NULL; parent = NULL; } // -------------------------------------------------------------------------------------------------------- void KFileTreeDirUp::setCurrentDir ( KFileTreeDir * currentDir ) { current_dir_node = currentDir; relayout(); } // -------------------------------------------------------------------------------------------------------- void KFileTreeDirUp::relayout () { current_dir_node->setPosition(matrix[TX], matrix[TY], matrix[TZ]); current_dir_node->relayout(); } // -------------------------------------------------------------------------------------------------------- void KFileTreeDirUp::render () { int divisions = KEventHandler::flags[KDL_DISPLAY_MODE_FAST] ? 5 : 8; glDisable(GL_LIGHTING); glBegin(GL_LINES); glVertex3f( 0.5, -1.0, 0.0); glVertex3f(-0.5, -1.0, 0.0); glVertex3f( 0.0, 0.0, 0.0); glVertex3f( 0.0, -1.0, 0.0); glEnd(); glEnable(GL_LIGHTING); glPushMatrix(); glTranslated(0.5, -1.0, 0.0); kDisplaySolidSphere(0.4f, divisions); glTranslated(-1.0, 0.0, 0.0); kDisplaySolidSphere(0.4f, divisions); glPopMatrix(); }
8a0f482456290ef465df6421f5df9a4c46307ac5
b8d309c77ad95a29ebb856e98c6047fd63bc6cfb
/BattleTanks/Source/BattleTanks/Public/TankTrack.h
da39aaca7cc588462b2e080becd5967e2891cc23
[]
no_license
FendingTheEnding/BattleTank
022b6d6233eff97e3e820c4f8f6cd791f3020d75
87ada2bcf5e65baa4e29b17b4726a7d87292b255
refs/heads/master
2022-07-28T16:54:31.196166
2022-07-17T23:38:32
2022-07-17T23:38:32
251,735,786
0
0
null
null
null
null
UTF-8
C++
false
false
1,165
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "Components/StaticMeshComponent.h" #include "TankTrack.generated.h" /** * TankTrack is used to set maximum driving force, and to apply forces to the tank */ UCLASS(meta = (BlueprintSpawnableComponent)) class BATTLETANKS_API UTankTrack : public UStaticMeshComponent { GENERATED_BODY() public: // Sets throttle to value between -1/+1 UFUNCTION(BlueprintCallable, Category = Input) void SetThrottle(float Throttle); // Max force per track in Newtons UPROPERTY(EditDefaultsOnly) float TrackMaxDrivingForce = 80000000.f; // Assume 40 ton tank and 1g acceleration private: UTankTrack(); virtual void BeginPlay() override; //virtual void TickComponent(float DeltaTime, enum ELevelTick TickType, FActorComponentTickFunction *ThisTickFunction) override; void ApplySidwaysForce(); void ApplyUpDownForce(); void DriveTrack(); float CurrentThrottle = 0.f; UFUNCTION() void OnHit(UPrimitiveComponent* HitComponent, AActor* OtherActor, UPrimitiveComponent* OtherComponent, FVector NormalImpulse, const FHitResult& Hit); };
2cb915fa74e62b317a8fe1b00788d8a6117a8942
5828f68cd5ab4ff48d7420ccdc3e1c4964d8196f
/fem/fe/fe_nd.cpp
603d1e81fc0778a39f24a21b431a677a5ec577c9
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "MIT", "Zlib" ]
permissive
adrienbernede/mfem
5bb7a7a143b6812a0781af6713bdfd9bf3e3fd63
f66ddbc394051a335c4a99da0169962fea69cc0e
refs/heads/master
2021-11-19T05:17:06.805519
2021-09-28T20:49:04
2021-09-28T20:49:04
263,454,847
0
0
BSD-3-Clause
2021-05-24T05:14:51
2020-05-12T21:20:47
C++
UTF-8
C++
false
false
34,597
cpp
// Copyright (c) 2010-2021, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-806117. // // This file is part of the MFEM library. For more information and source code // availability visit https://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. // Nedelec Finite Element classes #include "fe_nd.hpp" #include "../coefficient.hpp" namespace mfem { using namespace std; const double ND_HexahedronElement::tk[18] = { 1.,0.,0., 0.,1.,0., 0.,0.,1., -1.,0.,0., 0.,-1.,0., 0.,0.,-1. }; ND_HexahedronElement::ND_HexahedronElement(const int p, const int cb_type, const int ob_type) : VectorTensorFiniteElement(3, 3*p*(p + 1)*(p + 1), p, cb_type, ob_type, H_CURL, DofMapType::L2_DOF_MAP), dof2tk(dof), cp(poly1d.ClosedPoints(p, cb_type)) { if (obasis1d.IsIntegratedType()) { is_nodal = false; } dof_map.SetSize(dof); const double *op = poly1d.OpenPoints(p - 1, ob_type); const int dof3 = dof/3; #ifndef MFEM_THREAD_SAFE shape_cx.SetSize(p + 1); shape_ox.SetSize(p); shape_cy.SetSize(p + 1); shape_oy.SetSize(p); shape_cz.SetSize(p + 1); shape_oz.SetSize(p); dshape_cx.SetSize(p + 1); dshape_cy.SetSize(p + 1); dshape_cz.SetSize(p + 1); #endif // edges int o = 0; for (int i = 0; i < p; i++) // (0,1) { dof_map[0*dof3 + i + (0 + 0*(p + 1))*p] = o++; } for (int i = 0; i < p; i++) // (1,2) { dof_map[1*dof3 + p + (i + 0*p)*(p + 1)] = o++; } for (int i = 0; i < p; i++) // (3,2) { dof_map[0*dof3 + i + (p + 0*(p + 1))*p] = o++; } for (int i = 0; i < p; i++) // (0,3) { dof_map[1*dof3 + 0 + (i + 0*p)*(p + 1)] = o++; } for (int i = 0; i < p; i++) // (4,5) { dof_map[0*dof3 + i + (0 + p*(p + 1))*p] = o++; } for (int i = 0; i < p; i++) // (5,6) { dof_map[1*dof3 + p + (i + p*p)*(p + 1)] = o++; } for (int i = 0; i < p; i++) // (7,6) { dof_map[0*dof3 + i + (p + p*(p + 1))*p] = o++; } for (int i = 0; i < p; i++) // (4,7) { dof_map[1*dof3 + 0 + (i + p*p)*(p + 1)] = o++; } for (int i = 0; i < p; i++) // (0,4) { dof_map[2*dof3 + 0 + (0 + i*(p + 1))*(p + 1)] = o++; } for (int i = 0; i < p; i++) // (1,5) { dof_map[2*dof3 + p + (0 + i*(p + 1))*(p + 1)] = o++; } for (int i = 0; i < p; i++) // (2,6) { dof_map[2*dof3 + p + (p + i*(p + 1))*(p + 1)] = o++; } for (int i = 0; i < p; i++) // (3,7) { dof_map[2*dof3 + 0 + (p + i*(p + 1))*(p + 1)] = o++; } // faces // (3,2,1,0) -- bottom for (int j = 1; j < p; j++) // x - components for (int i = 0; i < p; i++) { dof_map[0*dof3 + i + ((p - j) + 0*(p + 1))*p] = o++; } for (int j = 0; j < p; j++) // y - components for (int i = 1; i < p; i++) { dof_map[1*dof3 + i + ((p - 1 - j) + 0*p)*(p + 1)] = -1 - (o++); } // (0,1,5,4) -- front for (int k = 1; k < p; k++) // x - components for (int i = 0; i < p; i++) { dof_map[0*dof3 + i + (0 + k*(p + 1))*p] = o++; } for (int k = 0; k < p; k++) // z - components for (int i = 1; i < p; i++ ) { dof_map[2*dof3 + i + (0 + k*(p + 1))*(p + 1)] = o++; } // (1,2,6,5) -- right for (int k = 1; k < p; k++) // y - components for (int j = 0; j < p; j++) { dof_map[1*dof3 + p + (j + k*p)*(p + 1)] = o++; } for (int k = 0; k < p; k++) // z - components for (int j = 1; j < p; j++) { dof_map[2*dof3 + p + (j + k*(p + 1))*(p + 1)] = o++; } // (2,3,7,6) -- back for (int k = 1; k < p; k++) // x - components for (int i = 0; i < p; i++) { dof_map[0*dof3 + (p - 1 - i) + (p + k*(p + 1))*p] = -1 - (o++); } for (int k = 0; k < p; k++) // z - components for (int i = 1; i < p; i++) { dof_map[2*dof3 + (p - i) + (p + k*(p + 1))*(p + 1)] = o++; } // (3,0,4,7) -- left for (int k = 1; k < p; k++) // y - components for (int j = 0; j < p; j++) { dof_map[1*dof3 + 0 + ((p - 1 - j) + k*p)*(p + 1)] = -1 - (o++); } for (int k = 0; k < p; k++) // z - components for (int j = 1; j < p; j++) { dof_map[2*dof3 + 0 + ((p - j) + k*(p + 1))*(p + 1)] = o++; } // (4,5,6,7) -- top for (int j = 1; j < p; j++) // x - components for (int i = 0; i < p; i++) { dof_map[0*dof3 + i + (j + p*(p + 1))*p] = o++; } for (int j = 0; j < p; j++) // y - components for (int i = 1; i < p; i++) { dof_map[1*dof3 + i + (j + p*p)*(p + 1)] = o++; } // interior // x-components for (int k = 1; k < p; k++) for (int j = 1; j < p; j++) for (int i = 0; i < p; i++) { dof_map[0*dof3 + i + (j + k*(p + 1))*p] = o++; } // y-components for (int k = 1; k < p; k++) for (int j = 0; j < p; j++) for (int i = 1; i < p; i++) { dof_map[1*dof3 + i + (j + k*p)*(p + 1)] = o++; } // z-components for (int k = 0; k < p; k++) for (int j = 1; j < p; j++) for (int i = 1; i < p; i++) { dof_map[2*dof3 + i + (j + k*(p + 1))*(p + 1)] = o++; } // set dof2tk and Nodes o = 0; // x-components for (int k = 0; k <= p; k++) for (int j = 0; j <= p; j++) for (int i = 0; i < p; i++) { int idx; if ((idx = dof_map[o++]) < 0) { dof2tk[idx = -1 - idx] = 3; } else { dof2tk[idx] = 0; } Nodes.IntPoint(idx).Set3(op[i], cp[j], cp[k]); } // y-components for (int k = 0; k <= p; k++) for (int j = 0; j < p; j++) for (int i = 0; i <= p; i++) { int idx; if ((idx = dof_map[o++]) < 0) { dof2tk[idx = -1 - idx] = 4; } else { dof2tk[idx] = 1; } Nodes.IntPoint(idx).Set3(cp[i], op[j], cp[k]); } // z-components for (int k = 0; k < p; k++) for (int j = 0; j <= p; j++) for (int i = 0; i <= p; i++) { int idx; if ((idx = dof_map[o++]) < 0) { dof2tk[idx = -1 - idx] = 5; } else { dof2tk[idx] = 2; } Nodes.IntPoint(idx).Set3(cp[i], cp[j], op[k]); } } void ND_HexahedronElement::ProjectIntegrated(VectorCoefficient &vc, ElementTransformation &Trans, Vector &dofs) const { MFEM_ASSERT(obasis1d.IsIntegratedType(), "Not integrated type"); double vk[Geometry::MaxDim]; Vector xk(vk, vc.GetVDim()); const IntegrationRule &ir = IntRules.Get(Geometry::SEGMENT, order); const int nqpt = ir.GetNPoints(); IntegrationPoint ip3d; int o = 0; for (int c = 0; c < 3; ++c) // loop over x, y, z components { const int im = c == 0 ? order - 1 : order; const int jm = c == 1 ? order - 1 : order; const int km = c == 2 ? order - 1 : order; for (int k = 0; k <= km; k++) for (int j = 0; j <= jm; j++) for (int i = 0; i <= im; i++) { int idx; if ((idx = dof_map[o++]) < 0) { idx = -1 - idx; } const int id1 = c == 0 ? i : (c == 1 ? j : k); const double h = cp[id1+1] - cp[id1]; double val = 0.0; for (int q = 0; q < nqpt; q++) { const IntegrationPoint &ip1d = ir.IntPoint(q); if (c == 0) { ip3d.Set3(cp[i] + (h*ip1d.x), cp[j], cp[k]); } else if (c == 1) { ip3d.Set3(cp[i], cp[j] + (h*ip1d.x), cp[k]); } else { ip3d.Set3(cp[i], cp[j], cp[k] + (h*ip1d.x)); } Trans.SetIntPoint(&ip3d); vc.Eval(xk, Trans, ip3d); // xk^t J tk const double ipval = Trans.Jacobian().InnerProduct(tk + dof2tk[idx]*dim, vk); val += ip1d.weight * ipval; } dofs(idx) = val*h; } } } void ND_HexahedronElement::CalcVShape(const IntegrationPoint &ip, DenseMatrix &shape) const { const int p = order; #ifdef MFEM_THREAD_SAFE Vector shape_cx(p + 1), shape_ox(p), shape_cy(p + 1), shape_oy(p); Vector shape_cz(p + 1), shape_oz(p); Vector dshape_cx, dshape_cy, dshape_cz; #endif if (obasis1d.IsIntegratedType()) { cbasis1d.Eval(ip.x, shape_cx, dshape_cx); cbasis1d.Eval(ip.y, shape_cy, dshape_cy); cbasis1d.Eval(ip.z, shape_cz, dshape_cz); obasis1d.EvalIntegrated(dshape_cx, shape_ox); obasis1d.EvalIntegrated(dshape_cy, shape_oy); obasis1d.EvalIntegrated(dshape_cz, shape_oz); } else { cbasis1d.Eval(ip.x, shape_cx); cbasis1d.Eval(ip.y, shape_cy); cbasis1d.Eval(ip.z, shape_cz); obasis1d.Eval(ip.x, shape_ox); obasis1d.Eval(ip.y, shape_oy); obasis1d.Eval(ip.z, shape_oz); } int o = 0; // x-components for (int k = 0; k <= p; k++) for (int j = 0; j <= p; j++) for (int i = 0; i < p; i++) { int idx, s; if ((idx = dof_map[o++]) < 0) { idx = -1 - idx, s = -1; } else { s = +1; } shape(idx,0) = s*shape_ox(i)*shape_cy(j)*shape_cz(k); shape(idx,1) = 0.; shape(idx,2) = 0.; } // y-components for (int k = 0; k <= p; k++) for (int j = 0; j < p; j++) for (int i = 0; i <= p; i++) { int idx, s; if ((idx = dof_map[o++]) < 0) { idx = -1 - idx, s = -1; } else { s = +1; } shape(idx,0) = 0.; shape(idx,1) = s*shape_cx(i)*shape_oy(j)*shape_cz(k); shape(idx,2) = 0.; } // z-components for (int k = 0; k < p; k++) for (int j = 0; j <= p; j++) for (int i = 0; i <= p; i++) { int idx, s; if ((idx = dof_map[o++]) < 0) { idx = -1 - idx, s = -1; } else { s = +1; } shape(idx,0) = 0.; shape(idx,1) = 0.; shape(idx,2) = s*shape_cx(i)*shape_cy(j)*shape_oz(k); } } void ND_HexahedronElement::CalcCurlShape(const IntegrationPoint &ip, DenseMatrix &curl_shape) const { const int p = order; #ifdef MFEM_THREAD_SAFE Vector shape_cx(p + 1), shape_ox(p), shape_cy(p + 1), shape_oy(p); Vector shape_cz(p + 1), shape_oz(p); Vector dshape_cx(p + 1), dshape_cy(p + 1), dshape_cz(p + 1); #endif cbasis1d.Eval(ip.x, shape_cx, dshape_cx); cbasis1d.Eval(ip.y, shape_cy, dshape_cy); cbasis1d.Eval(ip.z, shape_cz, dshape_cz); if (obasis1d.IsIntegratedType()) { obasis1d.EvalIntegrated(dshape_cx, shape_ox); obasis1d.EvalIntegrated(dshape_cy, shape_oy); obasis1d.EvalIntegrated(dshape_cz, shape_oz); } else { obasis1d.Eval(ip.x, shape_ox); obasis1d.Eval(ip.y, shape_oy); obasis1d.Eval(ip.z, shape_oz); } int o = 0; // x-components for (int k = 0; k <= p; k++) for (int j = 0; j <= p; j++) for (int i = 0; i < p; i++) { int idx, s; if ((idx = dof_map[o++]) < 0) { idx = -1 - idx, s = -1; } else { s = +1; } curl_shape(idx,0) = 0.; curl_shape(idx,1) = s*shape_ox(i)* shape_cy(j)*dshape_cz(k); curl_shape(idx,2) = -s*shape_ox(i)*dshape_cy(j)* shape_cz(k); } // y-components for (int k = 0; k <= p; k++) for (int j = 0; j < p; j++) for (int i = 0; i <= p; i++) { int idx, s; if ((idx = dof_map[o++]) < 0) { idx = -1 - idx, s = -1; } else { s = +1; } curl_shape(idx,0) = -s* shape_cx(i)*shape_oy(j)*dshape_cz(k); curl_shape(idx,1) = 0.; curl_shape(idx,2) = s*dshape_cx(i)*shape_oy(j)* shape_cz(k); } // z-components for (int k = 0; k < p; k++) for (int j = 0; j <= p; j++) for (int i = 0; i <= p; i++) { int idx, s; if ((idx = dof_map[o++]) < 0) { idx = -1 - idx, s = -1; } else { s = +1; } curl_shape(idx,0) = s* shape_cx(i)*dshape_cy(j)*shape_oz(k); curl_shape(idx,1) = -s*dshape_cx(i)* shape_cy(j)*shape_oz(k); curl_shape(idx,2) = 0.; } } const double ND_QuadrilateralElement::tk[8] = { 1.,0., 0.,1., -1.,0., 0.,-1. }; ND_QuadrilateralElement::ND_QuadrilateralElement(const int p, const int cb_type, const int ob_type) : VectorTensorFiniteElement(2, 2*p*(p + 1), p, cb_type, ob_type, H_CURL, DofMapType::L2_DOF_MAP), dof2tk(dof), cp(poly1d.ClosedPoints(p, cb_type)) { if (obasis1d.IsIntegratedType()) { is_nodal = false; } dof_map.SetSize(dof); const double *op = poly1d.OpenPoints(p - 1, ob_type); const int dof2 = dof/2; #ifndef MFEM_THREAD_SAFE shape_cx.SetSize(p + 1); shape_ox.SetSize(p); shape_cy.SetSize(p + 1); shape_oy.SetSize(p); dshape_cx.SetSize(p + 1); dshape_cy.SetSize(p + 1); #endif // edges int o = 0; for (int i = 0; i < p; i++) // (0,1) { dof_map[0*dof2 + i + 0*p] = o++; } for (int j = 0; j < p; j++) // (1,2) { dof_map[1*dof2 + p + j*(p + 1)] = o++; } for (int i = 0; i < p; i++) // (2,3) { dof_map[0*dof2 + (p - 1 - i) + p*p] = -1 - (o++); } for (int j = 0; j < p; j++) // (3,0) { dof_map[1*dof2 + 0 + (p - 1 - j)*(p + 1)] = -1 - (o++); } // interior // x-components for (int j = 1; j < p; j++) for (int i = 0; i < p; i++) { dof_map[0*dof2 + i + j*p] = o++; } // y-components for (int j = 0; j < p; j++) for (int i = 1; i < p; i++) { dof_map[1*dof2 + i + j*(p + 1)] = o++; } // set dof2tk and Nodes o = 0; // x-components for (int j = 0; j <= p; j++) for (int i = 0; i < p; i++) { int idx; if ((idx = dof_map[o++]) < 0) { dof2tk[idx = -1 - idx] = 2; } else { dof2tk[idx] = 0; } Nodes.IntPoint(idx).Set2(op[i], cp[j]); } // y-components for (int j = 0; j < p; j++) for (int i = 0; i <= p; i++) { int idx; if ((idx = dof_map[o++]) < 0) { dof2tk[idx = -1 - idx] = 3; } else { dof2tk[idx] = 1; } Nodes.IntPoint(idx).Set2(cp[i], op[j]); } } void ND_QuadrilateralElement::ProjectIntegrated(VectorCoefficient &vc, ElementTransformation &Trans, Vector &dofs) const { MFEM_ASSERT(obasis1d.IsIntegratedType(), "Not integrated type"); double vk[Geometry::MaxDim]; Vector xk(vk, vc.GetVDim()); const IntegrationRule &ir = IntRules.Get(Geometry::SEGMENT, order); const int nqpt = ir.GetNPoints(); IntegrationPoint ip2d; int o = 0; // x-components for (int j = 0; j <= order; j++) for (int i = 0; i < order; i++) { int idx; if ((idx = dof_map[o++]) < 0) { idx = -1 - idx; } const double h = cp[i+1] - cp[i]; double val = 0.0; for (int k = 0; k < nqpt; k++) { const IntegrationPoint &ip1d = ir.IntPoint(k); ip2d.Set2(cp[i] + (h*ip1d.x), cp[j]); Trans.SetIntPoint(&ip2d); vc.Eval(xk, Trans, ip2d); // xk^t J tk const double ipval = Trans.Jacobian().InnerProduct(tk + dof2tk[idx]*dim, vk); val += ip1d.weight * ipval; } dofs(idx) = val*h; } // y-components for (int j = 0; j < order; j++) for (int i = 0; i <= order; i++) { int idx; if ((idx = dof_map[o++]) < 0) { idx = -1 - idx; } const double h = cp[j+1] - cp[j]; double val = 0.0; for (int k = 0; k < nqpt; k++) { const IntegrationPoint &ip1d = ir.IntPoint(k); ip2d.Set2(cp[i], cp[j] + (h*ip1d.x)); Trans.SetIntPoint(&ip2d); vc.Eval(xk, Trans, ip2d); // xk^t J tk const double ipval = Trans.Jacobian().InnerProduct(tk + dof2tk[idx]*dim, vk); val += ip1d.weight * ipval; } dofs(idx) = val*h; } } void ND_QuadrilateralElement::CalcVShape(const IntegrationPoint &ip, DenseMatrix &shape) const { const int p = order; #ifdef MFEM_THREAD_SAFE Vector shape_cx(p + 1), shape_ox(p), shape_cy(p + 1), shape_oy(p); Vector dshape_cx, dshape_cy; #endif if (obasis1d.IsIntegratedType()) { cbasis1d.Eval(ip.x, shape_cx, dshape_cx); cbasis1d.Eval(ip.y, shape_cy, dshape_cy); obasis1d.EvalIntegrated(dshape_cx, shape_ox); obasis1d.EvalIntegrated(dshape_cy, shape_oy); } else { cbasis1d.Eval(ip.x, shape_cx); cbasis1d.Eval(ip.y, shape_cy); obasis1d.Eval(ip.x, shape_ox); obasis1d.Eval(ip.y, shape_oy); } int o = 0; // x-components for (int j = 0; j <= p; j++) for (int i = 0; i < p; i++) { int idx, s; if ((idx = dof_map[o++]) < 0) { idx = -1 - idx, s = -1; } else { s = +1; } shape(idx,0) = s*shape_ox(i)*shape_cy(j); shape(idx,1) = 0.; } // y-components for (int j = 0; j < p; j++) for (int i = 0; i <= p; i++) { int idx, s; if ((idx = dof_map[o++]) < 0) { idx = -1 - idx, s = -1; } else { s = +1; } shape(idx,0) = 0.; shape(idx,1) = s*shape_cx(i)*shape_oy(j); } } void ND_QuadrilateralElement::CalcCurlShape(const IntegrationPoint &ip, DenseMatrix &curl_shape) const { const int p = order; #ifdef MFEM_THREAD_SAFE Vector shape_cx(p + 1), shape_ox(p), shape_cy(p + 1), shape_oy(p); Vector dshape_cx(p + 1), dshape_cy(p + 1); #endif cbasis1d.Eval(ip.x, shape_cx, dshape_cx); cbasis1d.Eval(ip.y, shape_cy, dshape_cy); if (obasis1d.IsIntegratedType()) { obasis1d.EvalIntegrated(dshape_cx, shape_ox); obasis1d.EvalIntegrated(dshape_cy, shape_oy); } else { obasis1d.Eval(ip.x, shape_ox); obasis1d.Eval(ip.y, shape_oy); } int o = 0; // x-components for (int j = 0; j <= p; j++) for (int i = 0; i < p; i++) { int idx, s; if ((idx = dof_map[o++]) < 0) { idx = -1 - idx, s = -1; } else { s = +1; } curl_shape(idx,0) = -s*shape_ox(i)*dshape_cy(j); } // y-components for (int j = 0; j < p; j++) for (int i = 0; i <= p; i++) { int idx, s; if ((idx = dof_map[o++]) < 0) { idx = -1 - idx, s = -1; } else { s = +1; } curl_shape(idx,0) = s*dshape_cx(i)*shape_oy(j); } } const double ND_TetrahedronElement::tk[18] = { 1.,0.,0., 0.,1.,0., 0.,0.,1., -1.,1.,0., -1.,0.,1., 0.,-1.,1. }; const double ND_TetrahedronElement::c = 1./4.; ND_TetrahedronElement::ND_TetrahedronElement(const int p) : VectorFiniteElement(3, Geometry::TETRAHEDRON, p*(p + 2)*(p + 3)/2, p, H_CURL, FunctionSpace::Pk), dof2tk(dof) { const double *eop = poly1d.OpenPoints(p - 1); const double *fop = (p > 1) ? poly1d.OpenPoints(p - 2) : NULL; const double *iop = (p > 2) ? poly1d.OpenPoints(p - 3) : NULL; const int pm1 = p - 1, pm2 = p - 2, pm3 = p - 3; #ifndef MFEM_THREAD_SAFE shape_x.SetSize(p); shape_y.SetSize(p); shape_z.SetSize(p); shape_l.SetSize(p); dshape_x.SetSize(p); dshape_y.SetSize(p); dshape_z.SetSize(p); dshape_l.SetSize(p); u.SetSize(dof, dim); #else Vector shape_x(p), shape_y(p), shape_z(p), shape_l(p); #endif int o = 0; // edges for (int i = 0; i < p; i++) // (0,1) { Nodes.IntPoint(o).Set3(eop[i], 0., 0.); dof2tk[o++] = 0; } for (int i = 0; i < p; i++) // (0,2) { Nodes.IntPoint(o).Set3(0., eop[i], 0.); dof2tk[o++] = 1; } for (int i = 0; i < p; i++) // (0,3) { Nodes.IntPoint(o).Set3(0., 0., eop[i]); dof2tk[o++] = 2; } for (int i = 0; i < p; i++) // (1,2) { Nodes.IntPoint(o).Set3(eop[pm1-i], eop[i], 0.); dof2tk[o++] = 3; } for (int i = 0; i < p; i++) // (1,3) { Nodes.IntPoint(o).Set3(eop[pm1-i], 0., eop[i]); dof2tk[o++] = 4; } for (int i = 0; i < p; i++) // (2,3) { Nodes.IntPoint(o).Set3(0., eop[pm1-i], eop[i]); dof2tk[o++] = 5; } // faces for (int j = 0; j <= pm2; j++) // (1,2,3) for (int i = 0; i + j <= pm2; i++) { double w = fop[i] + fop[j] + fop[pm2-i-j]; Nodes.IntPoint(o).Set3(fop[pm2-i-j]/w, fop[i]/w, fop[j]/w); dof2tk[o++] = 3; Nodes.IntPoint(o).Set3(fop[pm2-i-j]/w, fop[i]/w, fop[j]/w); dof2tk[o++] = 4; } for (int j = 0; j <= pm2; j++) // (0,3,2) for (int i = 0; i + j <= pm2; i++) { double w = fop[i] + fop[j] + fop[pm2-i-j]; Nodes.IntPoint(o).Set3(0., fop[j]/w, fop[i]/w); dof2tk[o++] = 2; Nodes.IntPoint(o).Set3(0., fop[j]/w, fop[i]/w); dof2tk[o++] = 1; } for (int j = 0; j <= pm2; j++) // (0,1,3) for (int i = 0; i + j <= pm2; i++) { double w = fop[i] + fop[j] + fop[pm2-i-j]; Nodes.IntPoint(o).Set3(fop[i]/w, 0., fop[j]/w); dof2tk[o++] = 0; Nodes.IntPoint(o).Set3(fop[i]/w, 0., fop[j]/w); dof2tk[o++] = 2; } for (int j = 0; j <= pm2; j++) // (0,2,1) for (int i = 0; i + j <= pm2; i++) { double w = fop[i] + fop[j] + fop[pm2-i-j]; Nodes.IntPoint(o).Set3(fop[j]/w, fop[i]/w, 0.); dof2tk[o++] = 1; Nodes.IntPoint(o).Set3(fop[j]/w, fop[i]/w, 0.); dof2tk[o++] = 0; } // interior for (int k = 0; k <= pm3; k++) for (int j = 0; j + k <= pm3; j++) for (int i = 0; i + j + k <= pm3; i++) { double w = iop[i] + iop[j] + iop[k] + iop[pm3-i-j-k]; Nodes.IntPoint(o).Set3(iop[i]/w, iop[j]/w, iop[k]/w); dof2tk[o++] = 0; Nodes.IntPoint(o).Set3(iop[i]/w, iop[j]/w, iop[k]/w); dof2tk[o++] = 1; Nodes.IntPoint(o).Set3(iop[i]/w, iop[j]/w, iop[k]/w); dof2tk[o++] = 2; } DenseMatrix T(dof); for (int m = 0; m < dof; m++) { const IntegrationPoint &ip = Nodes.IntPoint(m); const double *tm = tk + 3*dof2tk[m]; o = 0; poly1d.CalcBasis(pm1, ip.x, shape_x); poly1d.CalcBasis(pm1, ip.y, shape_y); poly1d.CalcBasis(pm1, ip.z, shape_z); poly1d.CalcBasis(pm1, 1. - ip.x - ip.y - ip.z, shape_l); for (int k = 0; k <= pm1; k++) for (int j = 0; j + k <= pm1; j++) for (int i = 0; i + j + k <= pm1; i++) { double s = shape_x(i)*shape_y(j)*shape_z(k)*shape_l(pm1-i-j-k); T(o++, m) = s * tm[0]; T(o++, m) = s * tm[1]; T(o++, m) = s * tm[2]; } for (int k = 0; k <= pm1; k++) for (int j = 0; j + k <= pm1; j++) { double s = shape_x(pm1-j-k)*shape_y(j)*shape_z(k); T(o++, m) = s*((ip.y - c)*tm[0] - (ip.x - c)*tm[1]); T(o++, m) = s*((ip.z - c)*tm[0] - (ip.x - c)*tm[2]); } for (int k = 0; k <= pm1; k++) { T(o++, m) = shape_y(pm1-k)*shape_z(k)*((ip.z - c)*tm[1] - (ip.y - c)*tm[2]); } } Ti.Factor(T); // mfem::out << "ND_TetrahedronElement(" << p << ") : "; Ti.TestInversion(); } void ND_TetrahedronElement::CalcVShape(const IntegrationPoint &ip, DenseMatrix &shape) const { const int pm1 = order - 1; #ifdef MFEM_THREAD_SAFE const int p = order; Vector shape_x(p), shape_y(p), shape_z(p), shape_l(p); DenseMatrix u(dof, dim); #endif poly1d.CalcBasis(pm1, ip.x, shape_x); poly1d.CalcBasis(pm1, ip.y, shape_y); poly1d.CalcBasis(pm1, ip.z, shape_z); poly1d.CalcBasis(pm1, 1. - ip.x - ip.y - ip.z, shape_l); int n = 0; for (int k = 0; k <= pm1; k++) for (int j = 0; j + k <= pm1; j++) for (int i = 0; i + j + k <= pm1; i++) { double s = shape_x(i)*shape_y(j)*shape_z(k)*shape_l(pm1-i-j-k); u(n,0) = s; u(n,1) = 0.; u(n,2) = 0.; n++; u(n,0) = 0.; u(n,1) = s; u(n,2) = 0.; n++; u(n,0) = 0.; u(n,1) = 0.; u(n,2) = s; n++; } for (int k = 0; k <= pm1; k++) for (int j = 0; j + k <= pm1; j++) { double s = shape_x(pm1-j-k)*shape_y(j)*shape_z(k); u(n,0) = s*(ip.y - c); u(n,1) = -s*(ip.x - c); u(n,2) = 0.; n++; u(n,0) = s*(ip.z - c); u(n,1) = 0.; u(n,2) = -s*(ip.x - c); n++; } for (int k = 0; k <= pm1; k++) { double s = shape_y(pm1-k)*shape_z(k); u(n,0) = 0.; u(n,1) = s*(ip.z - c); u(n,2) = -s*(ip.y - c); n++; } Ti.Mult(u, shape); } void ND_TetrahedronElement::CalcCurlShape(const IntegrationPoint &ip, DenseMatrix &curl_shape) const { const int pm1 = order - 1; #ifdef MFEM_THREAD_SAFE const int p = order; Vector shape_x(p), shape_y(p), shape_z(p), shape_l(p); Vector dshape_x(p), dshape_y(p), dshape_z(p), dshape_l(p); DenseMatrix u(dof, dim); #endif poly1d.CalcBasis(pm1, ip.x, shape_x, dshape_x); poly1d.CalcBasis(pm1, ip.y, shape_y, dshape_y); poly1d.CalcBasis(pm1, ip.z, shape_z, dshape_z); poly1d.CalcBasis(pm1, 1. - ip.x - ip.y - ip.z, shape_l, dshape_l); int n = 0; for (int k = 0; k <= pm1; k++) for (int j = 0; j + k <= pm1; j++) for (int i = 0; i + j + k <= pm1; i++) { int l = pm1-i-j-k; const double dx = (dshape_x(i)*shape_l(l) - shape_x(i)*dshape_l(l))*shape_y(j)*shape_z(k); const double dy = (dshape_y(j)*shape_l(l) - shape_y(j)*dshape_l(l))*shape_x(i)*shape_z(k); const double dz = (dshape_z(k)*shape_l(l) - shape_z(k)*dshape_l(l))*shape_x(i)*shape_y(j); u(n,0) = 0.; u(n,1) = dz; u(n,2) = -dy; n++; u(n,0) = -dz; u(n,1) = 0.; u(n,2) = dx; n++; u(n,0) = dy; u(n,1) = -dx; u(n,2) = 0.; n++; } for (int k = 0; k <= pm1; k++) for (int j = 0; j + k <= pm1; j++) { int i = pm1 - j - k; // s = shape_x(i)*shape_y(j)*shape_z(k); // curl of s*(ip.y - c, -(ip.x - c), 0): u(n,0) = shape_x(i)*(ip.x - c)*shape_y(j)*dshape_z(k); u(n,1) = shape_x(i)*shape_y(j)*(ip.y - c)*dshape_z(k); u(n,2) = -((dshape_x(i)*(ip.x - c) + shape_x(i))*shape_y(j)*shape_z(k) + (dshape_y(j)*(ip.y - c) + shape_y(j))*shape_x(i)*shape_z(k)); n++; // curl of s*(ip.z - c, 0, -(ip.x - c)): u(n,0) = -shape_x(i)*(ip.x - c)*dshape_y(j)*shape_z(k); u(n,1) = (shape_x(i)*shape_y(j)*(dshape_z(k)*(ip.z - c) + shape_z(k)) + (dshape_x(i)*(ip.x - c) + shape_x(i))*shape_y(j)*shape_z(k)); u(n,2) = -shape_x(i)*dshape_y(j)*shape_z(k)*(ip.z - c); n++; } for (int k = 0; k <= pm1; k++) { int j = pm1 - k; // curl of shape_y(j)*shape_z(k)*(0, ip.z - c, -(ip.y - c)): u(n,0) = -((dshape_y(j)*(ip.y - c) + shape_y(j))*shape_z(k) + shape_y(j)*(dshape_z(k)*(ip.z - c) + shape_z(k))); u(n,1) = 0.; u(n,2) = 0.; n++; } Ti.Mult(u, curl_shape); } const double ND_TriangleElement::tk[8] = { 1.,0., -1.,1., 0.,-1., 0.,1. }; const double ND_TriangleElement::c = 1./3.; ND_TriangleElement::ND_TriangleElement(const int p) : VectorFiniteElement(2, Geometry::TRIANGLE, p*(p + 2), p, H_CURL, FunctionSpace::Pk), dof2tk(dof) { const double *eop = poly1d.OpenPoints(p - 1); const double *iop = (p > 1) ? poly1d.OpenPoints(p - 2) : NULL; const int pm1 = p - 1, pm2 = p - 2; #ifndef MFEM_THREAD_SAFE shape_x.SetSize(p); shape_y.SetSize(p); shape_l.SetSize(p); dshape_x.SetSize(p); dshape_y.SetSize(p); dshape_l.SetSize(p); u.SetSize(dof, dim); curlu.SetSize(dof); #else Vector shape_x(p), shape_y(p), shape_l(p); #endif int n = 0; // edges for (int i = 0; i < p; i++) // (0,1) { Nodes.IntPoint(n).Set2(eop[i], 0.); dof2tk[n++] = 0; } for (int i = 0; i < p; i++) // (1,2) { Nodes.IntPoint(n).Set2(eop[pm1-i], eop[i]); dof2tk[n++] = 1; } for (int i = 0; i < p; i++) // (2,0) { Nodes.IntPoint(n).Set2(0., eop[pm1-i]); dof2tk[n++] = 2; } // interior for (int j = 0; j <= pm2; j++) for (int i = 0; i + j <= pm2; i++) { double w = iop[i] + iop[j] + iop[pm2-i-j]; Nodes.IntPoint(n).Set2(iop[i]/w, iop[j]/w); dof2tk[n++] = 0; Nodes.IntPoint(n).Set2(iop[i]/w, iop[j]/w); dof2tk[n++] = 3; } DenseMatrix T(dof); for (int m = 0; m < dof; m++) { const IntegrationPoint &ip = Nodes.IntPoint(m); const double *tm = tk + 2*dof2tk[m]; n = 0; poly1d.CalcBasis(pm1, ip.x, shape_x); poly1d.CalcBasis(pm1, ip.y, shape_y); poly1d.CalcBasis(pm1, 1. - ip.x - ip.y, shape_l); for (int j = 0; j <= pm1; j++) for (int i = 0; i + j <= pm1; i++) { double s = shape_x(i)*shape_y(j)*shape_l(pm1-i-j); T(n++, m) = s * tm[0]; T(n++, m) = s * tm[1]; } for (int j = 0; j <= pm1; j++) { T(n++, m) = shape_x(pm1-j)*shape_y(j)*((ip.y - c)*tm[0] - (ip.x - c)*tm[1]); } } Ti.Factor(T); // mfem::out << "ND_TriangleElement(" << p << ") : "; Ti.TestInversion(); } void ND_TriangleElement::CalcVShape(const IntegrationPoint &ip, DenseMatrix &shape) const { const int pm1 = order - 1; #ifdef MFEM_THREAD_SAFE const int p = order; Vector shape_x(p), shape_y(p), shape_l(p); DenseMatrix u(dof, dim); #endif poly1d.CalcBasis(pm1, ip.x, shape_x); poly1d.CalcBasis(pm1, ip.y, shape_y); poly1d.CalcBasis(pm1, 1. - ip.x - ip.y, shape_l); int n = 0; for (int j = 0; j <= pm1; j++) for (int i = 0; i + j <= pm1; i++) { double s = shape_x(i)*shape_y(j)*shape_l(pm1-i-j); u(n,0) = s; u(n,1) = 0; n++; u(n,0) = 0; u(n,1) = s; n++; } for (int j = 0; j <= pm1; j++) { double s = shape_x(pm1-j)*shape_y(j); u(n,0) = s*(ip.y - c); u(n,1) = -s*(ip.x - c); n++; } Ti.Mult(u, shape); } void ND_TriangleElement::CalcCurlShape(const IntegrationPoint &ip, DenseMatrix &curl_shape) const { const int pm1 = order - 1; #ifdef MFEM_THREAD_SAFE const int p = order; Vector shape_x(p), shape_y(p), shape_l(p); Vector dshape_x(p), dshape_y(p), dshape_l(p); Vector curlu(dof); #endif poly1d.CalcBasis(pm1, ip.x, shape_x, dshape_x); poly1d.CalcBasis(pm1, ip.y, shape_y, dshape_y); poly1d.CalcBasis(pm1, 1. - ip.x - ip.y, shape_l, dshape_l); int n = 0; for (int j = 0; j <= pm1; j++) for (int i = 0; i + j <= pm1; i++) { int l = pm1-i-j; const double dx = (dshape_x(i)*shape_l(l) - shape_x(i)*dshape_l(l)) * shape_y(j); const double dy = (dshape_y(j)*shape_l(l) - shape_y(j)*dshape_l(l)) * shape_x(i); curlu(n++) = -dy; curlu(n++) = dx; } for (int j = 0; j <= pm1; j++) { int i = pm1 - j; // curl of shape_x(i)*shape_y(j) * (ip.y - c, -(ip.x - c), 0): curlu(n++) = -((dshape_x(i)*(ip.x - c) + shape_x(i)) * shape_y(j) + (dshape_y(j)*(ip.y - c) + shape_y(j)) * shape_x(i)); } Vector curl2d(curl_shape.Data(),dof); Ti.Mult(curlu, curl2d); } const double ND_SegmentElement::tk[1] = { 1. }; ND_SegmentElement::ND_SegmentElement(const int p, const int ob_type) : VectorTensorFiniteElement(1, p, p - 1, ob_type, H_CURL, DofMapType::L2_DOF_MAP), dof2tk(dof) { if (obasis1d.IsIntegratedType()) { is_nodal = false; } const double *op = poly1d.OpenPoints(p - 1, ob_type); // set dof2tk and Nodes for (int i = 0; i < p; i++) { dof2tk[i] = 0; Nodes.IntPoint(i).x = op[i]; } } void ND_SegmentElement::CalcVShape(const IntegrationPoint &ip, DenseMatrix &shape) const { Vector vshape(shape.Data(), dof); obasis1d.Eval(ip.x, vshape); } }
ed5f145b4f016ff906377fab2824eccf4e3e927b
cd9313c4dfe06d831016919233e2d2886ddca8a7
/practice1.cpp
898ec348d71c966a34d12435275e600f0a9a9074
[]
no_license
HJPyo/C
b198efa19f7484cc5b13e3e83798cdac99b6cd20
47d49f3aea1bc928fec5bcb344197c3dfecf5dd1
refs/heads/main
2023-04-12T15:04:44.844842
2021-05-11T09:13:07
2021-05-11T09:13:07
328,389,106
0
0
null
null
null
null
UTF-8
C++
false
false
237
cpp
#include<stdio.h> int n; long long int dp[100000001] = {0,1,1}; int main() { scanf("%d", &n); if(n < 3){ printf("%d", dp[n]); return 0; } for(int i = 3; i <= n; i++){ dp[i] = dp[i-1] + dp[i-2]; } printf("%lld", dp[n]); }
2f8b9373df83f95f38b03f08830eb4fd9d095149
60bba31469dcc8d6ec4fb2db76d6dfafcd7f1636
/CppSourseCode/P45_66_3.cpp
0b8c6a65c2cd9f9e883eaf1ba1f4c6e48c39a7e3
[]
no_license
raynaasenova/FMI-PU
df02a5ccc99e94ebd5f3c298b63045627af0d552
dad61baf121e6c25460aedc434f8446a4b6aa6a7
refs/heads/master
2021-01-10T21:20:30.933583
2014-10-19T18:02:04
2014-10-19T18:02:04
null
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
1,130
cpp
// Да се състави програма, която по въведена шестнадесетъчна цифра извежда съответното десетично число. Решете програмата с помощта на оператор switch и без него. #include "stdafx.h" #include<iostream> #include<windows.h> using namespace std; int main() { SetConsoleOutputCP(1251); char c; cout<<"Въведете 16-ична цифра: ";cin>>c; switch (c) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': cout<<"десетично:"<<c; break; case 'A': case 'a': cout<<"десетично:"<<10; break; case 'B': case 'b': cout<<"десетично:"<<11; break; case 'C': case 'c': cout<<"десетично:"<<12; break; case 'D': case 'd': cout<<"десетично:"<<13; break; case 'E': case 'e': cout<<"десетично:"<<14; break; case 'F': case 'f': cout<<"десетично:"<<15; break; default: cout<<"Въвели сте некоректни данни!"; } cout<<endl; return 0; }
3b57852b8333333987ac0b22cc8da387020413c1
d6b4bdf418ae6ab89b721a79f198de812311c783
/rum/include/tencentcloud/rum/v20210622/model/CreateWhitelistRequest.h
79046480de3ab3367e549851f93828097d7ee129
[ "Apache-2.0" ]
permissive
TencentCloud/tencentcloud-sdk-cpp-intl-en
d0781d461e84eb81775c2145bacae13084561c15
d403a6b1cf3456322bbdfb462b63e77b1e71f3dc
refs/heads/master
2023-08-21T12:29:54.125071
2023-08-21T01:12:39
2023-08-21T01:12:39
277,769,407
2
0
null
null
null
null
UTF-8
C++
false
false
5,164
h
/* * 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. */ #ifndef TENCENTCLOUD_RUM_V20210622_MODEL_CREATEWHITELISTREQUEST_H_ #define TENCENTCLOUD_RUM_V20210622_MODEL_CREATEWHITELISTREQUEST_H_ #include <string> #include <vector> #include <map> #include <tencentcloud/core/AbstractModel.h> namespace TencentCloud { namespace Rum { namespace V20210622 { namespace Model { /** * CreateWhitelist request structure. */ class CreateWhitelistRequest : public AbstractModel { public: CreateWhitelistRequest(); ~CreateWhitelistRequest() = default; std::string ToJsonString() const; /** * 获取Instance ID, such as taw-123 * @return InstanceID Instance ID, such as taw-123 * */ std::string GetInstanceID() const; /** * 设置Instance ID, such as taw-123 * @param _instanceID Instance ID, such as taw-123 * */ void SetInstanceID(const std::string& _instanceID); /** * 判断参数 InstanceID 是否已赋值 * @return InstanceID 是否已赋值 * */ bool InstanceIDHasBeenSet() const; /** * 获取Remarks * @return Remark Remarks * */ std::string GetRemark() const; /** * 设置Remarks * @param _remark Remarks * */ void SetRemark(const std::string& _remark); /** * 判断参数 Remark 是否已赋值 * @return Remark 是否已赋值 * */ bool RemarkHasBeenSet() const; /** * 获取uin: business identifier * @return WhitelistUin uin: business identifier * */ std::string GetWhitelistUin() const; /** * 设置uin: business identifier * @param _whitelistUin uin: business identifier * */ void SetWhitelistUin(const std::string& _whitelistUin); /** * 判断参数 WhitelistUin 是否已赋值 * @return WhitelistUin 是否已赋值 * */ bool WhitelistUinHasBeenSet() const; /** * 获取Business identifier * @return Aid Business identifier * */ std::string GetAid() const; /** * 设置Business identifier * @param _aid Business identifier * */ void SetAid(const std::string& _aid); /** * 判断参数 Aid 是否已赋值 * @return Aid 是否已赋值 * */ bool AidHasBeenSet() const; private: /** * Instance ID, such as taw-123 */ std::string m_instanceID; bool m_instanceIDHasBeenSet; /** * Remarks */ std::string m_remark; bool m_remarkHasBeenSet; /** * uin: business identifier */ std::string m_whitelistUin; bool m_whitelistUinHasBeenSet; /** * Business identifier */ std::string m_aid; bool m_aidHasBeenSet; }; } } } } #endif // !TENCENTCLOUD_RUM_V20210622_MODEL_CREATEWHITELISTREQUEST_H_
81fb113d16bf64ded0027c4bc546871e109f9112
95e6ab1436de9ba5fcf936639b9bbea0ab5282b5
/src/AI_makeRoomForFriend.h
2a9293cb063709e564cc716b94ac278fc0f1947d
[]
no_license
Justice-/ia
c46f3536ad8e80d7a24f69d8921aa3a049c8c177
78b7e5d063bef5c1defee7366feb2e2f2a409fbf
refs/heads/master
2021-01-16T22:50:27.890916
2013-06-16T14:50:36
2013-06-16T14:50:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,072
h
#ifndef AI_MAKE_ROOM_FOR_FRIEND_H #define AI_MAKE_ROOM_FOR_FRIEND_H #include <algorithm> /*===========================================================================++ Purpose: Check if monster blocks the path to the player for another monster. If that is the case, try to move to a coordinate that lets the pal through. This should make monsters using this better at surrounding the player. ++===========================================================================*/ class AI_makeRoomForFriend { public: static bool action(Monster* monsterActing, Engine* engine) { if(monsterActing->deadState == actorDeadState_alive) { bool blockersVision[MAP_X_CELLS][MAP_Y_CELLS]; engine->mapTests->makeVisionBlockerArray(monsterActing->pos, blockersVision); if(monsterActing->checkIfSeeActor(*engine->player, blockersVision)) { const unsigned int LOOP_SIZE = engine->gameTime->getLoopSize(); Monster* otherMonster = NULL; Actor* actor = NULL; //Loop through all actors for(unsigned int i = 0; i < LOOP_SIZE; i++) { actor = engine->gameTime->getActorAt(i); if(actor != engine->player && actor != monsterActing) { if(actor->deadState == actorDeadState_alive) { otherMonster = dynamic_cast<Monster*>(actor); bool isOtherNeighbourWithoutVision = isNeighbourAndWithoutVision(monsterActing, otherMonster, blockersVision, engine); //Other monster sees the player, or it's a neighbour that does not see the player? if(otherMonster->checkIfSeeActor(*engine->player, blockersVision) || isOtherNeighbourWithoutVision) { // If we are indeed blocking a pal, check every neighbouring cell that is at equal // or closer distance to the player, to check whether they are fine. // TODO Vision must be checked from the cell candidates! // TODO If several good candidates are found, result should be picked from them at random if(checkIfBlockingMonster(monsterActing->pos, otherMonster, engine) || isOtherNeighbourWithoutVision) { // Get a list of neighbouring free cells vector<coord> candidates = getMoveCandidates(monsterActing, engine); // Sort the list by closeness to player IsCloserToOrigin sorter(engine->player->pos, engine); sort(candidates.begin(), candidates.end(), sorter); // Test the candidate cells until one is found that is not also blocking someone. for(unsigned int ii = 0; ii < candidates.size(); ii++) { bool isGoodCandidateFound = true; for(unsigned int iii = 0; iii < LOOP_SIZE; iii++) { actor = engine->gameTime->getActorAt(iii); if(actor != engine->player && actor != monsterActing) { otherMonster = dynamic_cast<Monster*>(actor); // isOtherNeighbourWithoutVision = isNeighbourAndWithoutVision(monsterActing, otherMonster, blockersVision, engine); if(otherMonster->checkIfSeeActor(*engine->player, blockersVision) /*|| isOtherNeighbourWithoutVision*/) { if(checkIfBlockingMonster(candidates.at(ii), otherMonster, engine) /*|| isOtherNeighbourWithoutVision*/) { isGoodCandidateFound = false; break; } } } } if(isGoodCandidateFound) { monsterActing->moveToCell(candidates.at(ii)); return true; } } } } } } } } } return false; } private: static bool checkIfBlockingMonster(const coord& pos, Monster* other, Engine* engine) { const vector<coord> line = engine->mapTests->getLine( other->pos, engine->player->pos, true, 99999); for(unsigned int i = 0; i < line.size(); i++) { if(line.at(i) == pos) { return true; } else if(line.at(i) == engine->player->pos) { return false; } } return false; } //Returns all the coordinates around the acting monster, that //is not occupied by landscape, actors or blocking features. static vector<coord> getMoveCandidates(Monster* self, Engine* engine) { vector<coord> ret; const int PLAYER_X = engine->player->pos.x; const int PLAYER_Y = engine->player->pos.y; const int OLD_X = self->pos.x; const int OLD_Y = self->pos.y; bool blockers[MAP_X_CELLS][MAP_Y_CELLS]; engine->mapTests->makeMoveBlockerArray(self, blockers); for(int x = -1; x <= 1; x++) { for(int y = -1; y <= 1; y++) { if(x != OLD_X || y != OLD_Y) { const int NEW_X = OLD_X + x; const int NEW_Y = OLD_Y + y; const int DIST_CUR = engine->basicUtils->chebyshevDistance(OLD_X, OLD_Y, PLAYER_X, PLAYER_Y); const int DIST_NEW = engine->basicUtils->chebyshevDistance(NEW_X, NEW_Y, PLAYER_X, PLAYER_Y); if(DIST_NEW <= DIST_CUR) { if(blockers[NEW_X][NEW_Y] == false) { ret.push_back(coord(NEW_X, NEW_Y)); } } } } } return ret; } /* The purpose of the following test is to handle this situation: ##### #.A.# #@#B# ##### */ static bool isNeighbourAndWithoutVision( const Monster* const self, Monster* const other, bool blockersVision[MAP_X_CELLS][MAP_Y_CELLS], Engine* engine) { //If the pal is next to me if(engine->mapTests->isCellsNeighbours(self->pos, other->pos, false)) { //If pal does not see player if(other->checkIfSeeActor(*engine->player, blockersVision) == false) { return true; } } return false; } }; #endif
9b2e7bb84b80eb030c1eaf42e4b544484e2ff015
b1aef802c0561f2a730ac3125c55325d9c480e45
/src/ripple/server/impl/Port.cpp
ffc4f29e6ca281ed0680b266f61801538f8c83d9
[]
no_license
sgy-official/sgy
d3f388cefed7cf20513c14a2a333c839aa0d66c6
8c5c356c81b24180d8763d3bbc0763f1046871ac
refs/heads/master
2021-05-19T07:08:54.121998
2020-03-31T11:08:16
2020-03-31T11:08:16
251,577,856
6
4
null
null
null
null
UTF-8
C++
false
false
7,175
cpp
#include <ripple/basics/safe_cast.h> #include <ripple/server/Port.h> #include <ripple/beast/rfc2616.h> #include <ripple/beast/core/LexicalCast.h> namespace ripple { bool Port::secure() const { return protocol.count("peer") > 0 || protocol.count("https") > 0 || protocol.count("wss") > 0 || protocol.count("wss2") > 0; } std::string Port::protocols() const { std::string s; for (auto iter = protocol.cbegin(); iter != protocol.cend(); ++iter) s += (iter != protocol.cbegin() ? "," : "") + *iter; return s; } std::ostream& operator<< (std::ostream& os, Port const& p) { os << "'" << p.name << "' (ip=" << p.ip << ":" << p.port << ", "; if (! p.admin_ip.empty ()) { os << "admin IPs:"; for (auto const& ip : p.admin_ip) os << ip.to_string () << ", "; } if (! p.secure_gateway_ip.empty ()) { os << "secure_gateway IPs:"; for (auto const& ip : p.secure_gateway_ip) os << ip.to_string () << ", "; } os << p.protocols () << ")"; return os; } static void populate (Section const& section, std::string const& field, std::ostream& log, boost::optional<std::vector<beast::IP::Address>>& ips, bool allowAllIps, std::vector<beast::IP::Address> const& admin_ip) { auto const result = section.find(field); if (result.second) { std::stringstream ss (result.first); std::string ip; bool has_any (false); ips.emplace(); while (std::getline (ss, ip, ',')) { auto const addr = beast::IP::Endpoint::from_string_checked (ip); if (! addr.second) { log << "Invalid value '" << ip << "' for key '" << field << "' in [" << section.name () << "]"; Throw<std::exception> (); } if (is_unspecified (addr.first)) { if (! allowAllIps) { log << addr.first.address() << " not allowed'" << "' for key '" << field << "' in [" << section.name () << "]"; Throw<std::exception> (); } else { has_any = true; } } if (has_any && ! ips->empty ()) { log << "IP specified along with " << addr.first.address() << " '" << ip << "' for key '" << field << "' in [" << section.name () << "]"; Throw<std::exception> (); } auto const& address = addr.first.address(); if (std::find_if (admin_ip.begin(), admin_ip.end(), [&address] (beast::IP::Address const& ip) { return address == ip; } ) != admin_ip.end()) { log << "IP specified for " << field << " is also for " << "admin: " << ip << " in [" << section.name() << "]"; Throw<std::exception> (); } ips->emplace_back (addr.first.address ()); } } } void parse_Port (ParsedPort& port, Section const& section, std::ostream& log) { { auto result = section.find("ip"); if (result.second) { try { port.ip = boost::asio::ip::address::from_string(result.first); } catch (std::exception const&) { log << "Invalid value '" << result.first << "' for key 'ip' in [" << section.name() << "]"; Rethrow(); } } } { auto const result = section.find("port"); if (result.second) { try { port.port = beast::lexicalCastThrow<std::uint16_t>(result.first); if (*port.port == 0) Throw<std::exception> (); } catch (std::exception const&) { log << "Invalid value '" << result.first << "' for key " << "'port' in [" << section.name() << "]"; Rethrow(); } } } { auto const result = section.find("protocol"); if (result.second) { for (auto const& s : beast::rfc2616::split_commas( result.first.begin(), result.first.end())) port.protocol.insert(s); } } { auto const lim = get (section, "limit", "unlimited"); if (!boost::beast::detail::iequals (lim, "unlimited")) { try { port.limit = safe_cast<int> ( beast::lexicalCastThrow<std::uint16_t>(lim)); } catch (std::exception const&) { log << "Invalid value '" << lim << "' for key " << "'limit' in [" << section.name() << "]"; Rethrow(); } } } { auto const result = section.find("send_queue_limit"); if (result.second) { try { port.ws_queue_limit = beast::lexicalCastThrow<std::uint16_t>(result.first); if (port.ws_queue_limit == 0) Throw<std::exception>(); } catch (std::exception const&) { log << "Invalid value '" << result.first << "' for key " << "'send_queue_limit' in [" << section.name() << "]"; Rethrow(); } } else { port.ws_queue_limit = 100; } } populate (section, "admin", log, port.admin_ip, true, {}); populate (section, "secure_gateway", log, port.secure_gateway_ip, false, port.admin_ip.get_value_or({})); set(port.user, "user", section); set(port.password, "password", section); set(port.admin_user, "admin_user", section); set(port.admin_password, "admin_password", section); set(port.ssl_key, "ssl_key", section); set(port.ssl_cert, "ssl_cert", section); set(port.ssl_chain, "ssl_chain", section); set(port.ssl_ciphers, "ssl_ciphers", section); port.pmd_options.server_enable = section.value_or("permessage_deflate", true); port.pmd_options.client_max_window_bits = section.value_or("client_max_window_bits", 15); port.pmd_options.server_max_window_bits = section.value_or("server_max_window_bits", 15); port.pmd_options.client_no_context_takeover = section.value_or("client_no_context_takeover", false); port.pmd_options.server_no_context_takeover = section.value_or("server_no_context_takeover", false); port.pmd_options.compLevel = section.value_or("compress_level", 8); port.pmd_options.memLevel = section.value_or("memory_level", 4); } }
b0e611b6a3ae67ced30423915e879846883e26d8
0705f12dbc200f600663908b65c67b2d29a6e7de
/CreateVoca/include/FeatureVector.h
d4839a5e44c818894192cc5b707b2dcda46cf9e5
[]
no_license
Leerw/SuperPoint2CPP
a34cb7984e430e0442b3a0abfa078dba01877efa
f4083d1added529a79740482b20603f5dcb6a8f8
refs/heads/master
2023-07-04T08:09:32.310639
2021-08-05T16:31:58
2021-08-05T16:31:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,397
h
/** * File: FeatureVector.h * Date: November 2011 * Author: Dorian Galvez-Lopez * Description: feature vector * License: see the LICENSE.txt file * */ #ifndef __D_T_FEATURE_VECTOR__ #define __D_T_FEATURE_VECTOR__ #include "BowVector.h" #include <map> #include <vector> #include <iostream> namespace DBoW2 { /** * @brief Vector of nodes with indexes of local features * 하나의 이미지에 들어있는 feature들이 있을 때의 인덱스를 이용하여, <NodeId, Local Index> * 를 가지는 map구조. * FeatureVector는 이미지당 하나의 객체를 가질 수 있으며, 어떤 NodeId에 어떠어떠한 feature가 포함되어 있는지 담는다. * */ class FeatureVector: public std::map<NodeId, std::vector<unsigned int> > { public: /** * Constructor */ FeatureVector(void); /** * Destructor */ ~FeatureVector(void); /** * Adds a feature to an existing node, or adds a new node with an initial * feature * @param id node id to add or to modify * @param i_feature index of feature to add to the given node */ void addFeature(NodeId id, unsigned int i_feature); /** * Sends a string versions of the feature vector through the stream * @param out stream * @param v feature vector */ friend std::ostream& operator<<(std::ostream &out, const FeatureVector &v); }; } // namespace DBoW2 #endif
8b3f3f80b8e53d0af066a3aab93fd839f9d8fba8
24862dcb99a7da2050768212be89e91b9acb67b5
/UE_4.21/Engine/Intermediate/Build/Win32/UE4/Inc/Engine/CurveTable.generated.h
fc6f7cdbaa7427880ffed08d21cb62a17e20712f
[]
no_license
dadtaylo/makingchanges
3f8f1b4b4c7b2605d2736789445fcda693c92eea
3ea08eab63976feab82561a9355c4fc2d0f76362
refs/heads/master
2020-04-22T05:28:01.381983
2019-02-25T02:56:07
2019-02-25T02:56:07
170,160,587
0
0
null
null
null
null
UTF-8
C++
false
false
4,782
h
// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "UObject/ObjectMacros.h" #include "UObject/ScriptMacros.h" PRAGMA_DISABLE_DEPRECATION_WARNINGS #ifdef ENGINE_CurveTable_generated_h #error "CurveTable.generated.h already included, missing '#pragma once' in CurveTable.h" #endif #define ENGINE_CurveTable_generated_h #define Engine_Source_Runtime_Engine_Classes_Engine_CurveTable_h_173_GENERATED_BODY \ friend struct Z_Construct_UScriptStruct_FCurveTableRowHandle_Statics; \ static class UScriptStruct* StaticStruct(); #define Engine_Source_Runtime_Engine_Classes_Engine_CurveTable_h_31_RPC_WRAPPERS #define Engine_Source_Runtime_Engine_Classes_Engine_CurveTable_h_31_RPC_WRAPPERS_NO_PURE_DECLS #define Engine_Source_Runtime_Engine_Classes_Engine_CurveTable_h_31_ARCHIVESERIALIZER \ DECLARE_FSTRUCTUREDARCHIVE_SERIALIZER(UCurveTable, ENGINE_API) #define Engine_Source_Runtime_Engine_Classes_Engine_CurveTable_h_31_INCLASS_NO_PURE_DECLS \ private: \ static void StaticRegisterNativesUCurveTable(); \ friend struct Z_Construct_UClass_UCurveTable_Statics; \ public: \ DECLARE_CLASS(UCurveTable, UObject, COMPILED_IN_FLAGS(0), CASTCLASS_None, TEXT("/Script/Engine"), ENGINE_API) \ DECLARE_SERIALIZER(UCurveTable) \ Engine_Source_Runtime_Engine_Classes_Engine_CurveTable_h_31_ARCHIVESERIALIZER #define Engine_Source_Runtime_Engine_Classes_Engine_CurveTable_h_31_INCLASS \ private: \ static void StaticRegisterNativesUCurveTable(); \ friend struct Z_Construct_UClass_UCurveTable_Statics; \ public: \ DECLARE_CLASS(UCurveTable, UObject, COMPILED_IN_FLAGS(0), CASTCLASS_None, TEXT("/Script/Engine"), ENGINE_API) \ DECLARE_SERIALIZER(UCurveTable) \ Engine_Source_Runtime_Engine_Classes_Engine_CurveTable_h_31_ARCHIVESERIALIZER #define Engine_Source_Runtime_Engine_Classes_Engine_CurveTable_h_31_STANDARD_CONSTRUCTORS \ /** Standard constructor, called after all reflected properties have been initialized */ \ ENGINE_API UCurveTable(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()); \ DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(UCurveTable) \ DECLARE_VTABLE_PTR_HELPER_CTOR(ENGINE_API, UCurveTable); \ DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(UCurveTable); \ private: \ /** Private move- and copy-constructors, should never be used */ \ ENGINE_API UCurveTable(UCurveTable&&); \ ENGINE_API UCurveTable(const UCurveTable&); \ public: #define Engine_Source_Runtime_Engine_Classes_Engine_CurveTable_h_31_ENHANCED_CONSTRUCTORS \ /** Standard constructor, called after all reflected properties have been initialized */ \ ENGINE_API UCurveTable(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()) : Super(ObjectInitializer) { }; \ private: \ /** Private move- and copy-constructors, should never be used */ \ ENGINE_API UCurveTable(UCurveTable&&); \ ENGINE_API UCurveTable(const UCurveTable&); \ public: \ DECLARE_VTABLE_PTR_HELPER_CTOR(ENGINE_API, UCurveTable); \ DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(UCurveTable); \ DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(UCurveTable) #define Engine_Source_Runtime_Engine_Classes_Engine_CurveTable_h_31_PRIVATE_PROPERTY_OFFSET #define Engine_Source_Runtime_Engine_Classes_Engine_CurveTable_h_26_PROLOG #define Engine_Source_Runtime_Engine_Classes_Engine_CurveTable_h_31_GENERATED_BODY_LEGACY \ PRAGMA_DISABLE_DEPRECATION_WARNINGS \ public: \ Engine_Source_Runtime_Engine_Classes_Engine_CurveTable_h_31_PRIVATE_PROPERTY_OFFSET \ Engine_Source_Runtime_Engine_Classes_Engine_CurveTable_h_31_RPC_WRAPPERS \ Engine_Source_Runtime_Engine_Classes_Engine_CurveTable_h_31_INCLASS \ Engine_Source_Runtime_Engine_Classes_Engine_CurveTable_h_31_STANDARD_CONSTRUCTORS \ public: \ PRAGMA_ENABLE_DEPRECATION_WARNINGS #define Engine_Source_Runtime_Engine_Classes_Engine_CurveTable_h_31_GENERATED_BODY \ PRAGMA_DISABLE_DEPRECATION_WARNINGS \ public: \ Engine_Source_Runtime_Engine_Classes_Engine_CurveTable_h_31_PRIVATE_PROPERTY_OFFSET \ Engine_Source_Runtime_Engine_Classes_Engine_CurveTable_h_31_RPC_WRAPPERS_NO_PURE_DECLS \ Engine_Source_Runtime_Engine_Classes_Engine_CurveTable_h_31_INCLASS_NO_PURE_DECLS \ Engine_Source_Runtime_Engine_Classes_Engine_CurveTable_h_31_ENHANCED_CONSTRUCTORS \ static_assert(false, "Unknown access specifier for GENERATED_BODY() macro in class CurveTable."); \ PRAGMA_ENABLE_DEPRECATION_WARNINGS #undef CURRENT_FILE_ID #define CURRENT_FILE_ID Engine_Source_Runtime_Engine_Classes_Engine_CurveTable_h PRAGMA_ENABLE_DEPRECATION_WARNINGS
e9dd5a8174863fba62f3f36b2cb57cbce12531cd
98628a5eca9efd7ef3a1106e30b3441fe04b8e31
/chrome/browser/nearby_sharing/certificates/nearby_share_decrypted_public_certificate.h
77456ba7c77fea455c75d3a419c892876dc3592d
[ "BSD-3-Clause" ]
permissive
blackwhale2020/chromium
9c012046c8555b6442b04f336c35711a4a139612
7a75987d261a5b18f71c49412b98c009237c8274
refs/heads/master
2022-11-28T02:23:26.982138
2020-08-12T03:56:23
2020-08-12T03:56:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,659
h
// Copyright 2020 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_NEARBY_SHARING_CERTIFICATES_NEARBY_SHARE_DECRYPTED_PUBLIC_CERTIFICATE_H_ #define CHROME_BROWSER_NEARBY_SHARING_CERTIFICATES_NEARBY_SHARE_DECRYPTED_PUBLIC_CERTIFICATE_H_ #include <memory> #include <vector> #include "base/containers/span.h" #include "base/optional.h" #include "base/time/time.h" #include "chrome/browser/nearby_sharing/certificates/nearby_share_encrypted_metadata_key.h" #include "chrome/browser/nearby_sharing/proto/encrypted_metadata.pb.h" #include "chrome/browser/nearby_sharing/proto/rpc_resources.pb.h" // Stores decrypted metadata and crypto keys for the remote device that uploaded // this certificate to the Nearby Share server. Use DecryptPublicCertificate() // to generate an instance. This class provides a method for verifying a signed // payload during the authentication flow. class NearbyShareDecryptedPublicCertificate { public: // Attempts to decrypt the encrypted metadata of the PublicCertificate proto // by first decrypting the |encrypted_metadata_key| using the secret key // then using the decrypted key to decrypt the metadata. Returns base::nullopt // if the metadata was not successfully decrypted or if the proto data is // invalid. static base::Optional<NearbyShareDecryptedPublicCertificate> DecryptPublicCertificate( const nearbyshare::proto::PublicCertificate& public_certificate, const NearbyShareEncryptedMetadataKey& encrypted_metadata_key); NearbyShareDecryptedPublicCertificate( const NearbyShareDecryptedPublicCertificate&); NearbyShareDecryptedPublicCertificate& operator=( const NearbyShareDecryptedPublicCertificate&); NearbyShareDecryptedPublicCertificate( NearbyShareDecryptedPublicCertificate&&); NearbyShareDecryptedPublicCertificate& operator=( NearbyShareDecryptedPublicCertificate&&); virtual ~NearbyShareDecryptedPublicCertificate(); const std::vector<uint8_t>& id() const { return id_; } base::Time not_before() const { return not_before_; } base::Time not_after() const { return not_after_; } const nearbyshare::proto::EncryptedMetadata& unencrypted_metadata() const { return unencrypted_metadata_; } // Verifies the |signature| of the signed |payload| using |public_key_|. // Returns true if verification was successful. bool VerifySignature(base::span<const uint8_t> payload, base::span<const uint8_t> signature) const; private: NearbyShareDecryptedPublicCertificate( base::Time not_before, base::Time not_after, std::vector<uint8_t> public_key, std::vector<uint8_t> id, nearbyshare::proto::EncryptedMetadata unencrypted_metadata); // The begin/end times of the certificate's validity period. To avoid issues // with clock skew, these time might be offset compared to the corresponding // private certificate. base::Time not_before_; base::Time not_after_; // A P-256 public key used for verification. The bytes comprise a DER-encoded // ASN.1 SubjectPublicKeyInfo from the X.509 specification (RFC 5280). std::vector<uint8_t> public_key_; // An ID for the certificate, most likely generated from the secret key. std::vector<uint8_t> id_; // Unencrypted device metadata. The proto name is misleading; it holds data // that was previously serialized and encrypted. nearbyshare::proto::EncryptedMetadata unencrypted_metadata_; }; #endif // CHROME_BROWSER_NEARBY_SHARING_CERTIFICATES_NEARBY_SHARE_DECRYPTED_PUBLIC_CERTIFICATE_H_
29e161cd1b10b017ce9fc5e0e3497d6f33356030
f8f6877731a71d9ff045ba856f0f20d529e9e666
/GameSolution/Engine/Particle.inl
7763e7f0efd57b756e19654318c111abc1d6d086
[]
no_license
JonECG/Cpp-Game-Engine
f925f10aaaa2f6d053e83ef56c4dee2503ba70de
c11b0ed268057eb17f06edb406f0d69448eb9008
refs/heads/master
2021-01-19T07:39:18.108901
2015-06-14T14:23:23
2015-06-14T14:23:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,083
inl
void Particle::draw( Core::Graphics& g ) const { if( fade ) { g.SetColor( ColorHelper::quad( color, midColor, RGB(0,0,0), 1 - (life/(float)startLife) ) ); } else { g.SetColor( ColorHelper::lerp( color, RGB(0,0,0), 1 - (life/(float)startLife) ) ); } for( int i = 0; i < size; i++ ) { g.DrawLine( position.x - i, position.y - i + size, position.x + size - i, position.y - i ); } } void Particle::draw( Core::Graphics& g, Matrix4& globalTransform ) const { if( fade ) { g.SetColor( ColorHelper::quad( color, midColor, RGB(0,0,0), 1 - (life/(float)startLife) ) ); } else { g.SetColor( ColorHelper::lerp( color, RGB(0,0,0), 1 - (life/(float)startLife) ) ); } for( float i = 0; i < size; i++ ) { Vector2 p1 = globalTransform * ( position + Vector2( -i, -i + size ) ); Vector2 p2 = globalTransform * ( position + Vector2( size-i, -i ) ); g.DrawLine( p1.x, p1.y, p2.x, p2.y ); //g.DrawLine( position.x - i, position.y - i + size, position.x + size - i, position.y - i ); } } void Particle::update( float dt ) { velocity += acceleration*dt; position += velocity*dt; life -= dt; } void Particle::setPosition( const Vector2& vec ) { position = vec; } Vector2 Particle::getPosition() const { return position; } void Particle::setVelocity( const Vector2& vec ) { velocity = vec; } Vector2 Particle::getVelocity() const { return velocity; } void Particle::setAcceleration( const Vector2& vec ) { acceleration = vec; } Vector2 Particle::getAcceleration() const { return acceleration; } bool Particle::isAlive() const { return (life > 0); } void Particle::kill() { life = 0; } void Particle::setLife( float life ) { this->life = life; this->startLife = life; } void Particle::setSize( int size ) { this->size = size; } void Particle::setColor( Core::RGB color ) { this->color = color; fade = false; } void Particle::setColor( Core::RGB color, Core::RGB midColor ) { this->color = color; this->midColor = midColor; fade = true; }
a711d6f68aca5a1b8b05fa55d7876e104033be6b
9f6d0c9e9f0877e0cc954f61e2245c88839918f9
/v8/gen/32/torque-generated/src/objects/embedder-data-array-tq-csa.cc
fd1377c46ec27e8f72424d6de50c28ff1c4bf856
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
fibjs/fibjs_vender
c2f4fd35b7ed9e9ea06680d75453b3ee81a25d0d
6aa2431f65e17f9a51b60f12c14a36a8464fad5d
refs/heads/dev
2023-08-03T18:39:02.369823
2023-07-27T14:12:00
2023-07-27T14:12:00
37,327,960
7
24
null
2022-05-18T15:08:24
2015-06-12T14:56:51
C++
UTF-8
C++
false
false
12,380
cc
#include "src/ast/ast.h" #include "src/builtins/builtins-array-gen.h" #include "src/builtins/builtins-bigint-gen.h" #include "src/builtins/builtins-collections-gen.h" #include "src/builtins/builtins-constructor-gen.h" #include "src/builtins/builtins-data-view-gen.h" #include "src/builtins/builtins-iterator-gen.h" #include "src/builtins/builtins-object-gen.h" #include "src/builtins/builtins-promise-gen.h" #include "src/builtins/builtins-promise.h" #include "src/builtins/builtins-proxy-gen.h" #include "src/builtins/builtins-regexp-gen.h" #include "src/builtins/builtins-string-gen.h" #include "src/builtins/builtins-typed-array-gen.h" #include "src/builtins/builtins-utils-gen.h" #include "src/builtins/builtins-wasm-gen.h" #include "src/builtins/builtins.h" #include "src/codegen/code-factory.h" #include "src/debug/debug-wasm-objects.h" #include "src/heap/factory-inl.h" #include "src/ic/binary-op-assembler.h" #include "src/ic/handler-configuration-inl.h" #include "src/objects/arguments.h" #include "src/objects/bigint.h" #include "src/objects/call-site-info.h" #include "src/objects/elements-kind.h" #include "src/objects/free-space.h" #include "src/objects/intl-objects.h" #include "src/objects/js-atomics-synchronization.h" #include "src/objects/js-break-iterator.h" #include "src/objects/js-collator.h" #include "src/objects/js-date-time-format.h" #include "src/objects/js-display-names.h" #include "src/objects/js-duration-format.h" #include "src/objects/js-function.h" #include "src/objects/js-generator.h" #include "src/objects/js-iterator-helpers.h" #include "src/objects/js-list-format.h" #include "src/objects/js-locale.h" #include "src/objects/js-number-format.h" #include "src/objects/js-objects.h" #include "src/objects/js-plural-rules.h" #include "src/objects/js-promise.h" #include "src/objects/js-raw-json.h" #include "src/objects/js-regexp-string-iterator.h" #include "src/objects/js-relative-time-format.h" #include "src/objects/js-segment-iterator.h" #include "src/objects/js-segmenter.h" #include "src/objects/js-segments.h" #include "src/objects/js-shadow-realm.h" #include "src/objects/js-shared-array.h" #include "src/objects/js-struct.h" #include "src/objects/js-temporal-objects.h" #include "src/objects/js-weak-refs.h" #include "src/objects/objects.h" #include "src/objects/ordered-hash-table.h" #include "src/objects/property-array.h" #include "src/objects/property-descriptor-object.h" #include "src/objects/source-text-module.h" #include "src/objects/swiss-hash-table-helpers.h" #include "src/objects/swiss-name-dictionary.h" #include "src/objects/synthetic-module.h" #include "src/objects/template-objects.h" #include "src/objects/torque-defined-classes.h" #include "src/objects/turbofan-types.h" #include "src/objects/turboshaft-types.h" #include "src/torque/runtime-support.h" // Required Builtins: #include "torque-generated/src/objects/embedder-data-array-tq-csa.h" #include "torque-generated/src/builtins/base-tq-csa.h" #include "torque-generated/src/builtins/convert-tq-csa.h" #include "torque-generated/src/builtins/torque-internal-tq-csa.h" #include "torque-generated/src/objects/embedder-data-array-tq-csa.h" #include "torque-generated/src/objects/string-tq-csa.h" namespace v8 { namespace internal { // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/objects/embedder-data-array.tq?l=5&c=1 TNode<EmbedderDataArray> Cast_EmbedderDataArray_0(compiler::CodeAssemblerState* state_, TNode<HeapObject> p_obj, compiler::CodeAssemblerLabel* label_CastError) { compiler::CodeAssembler ca_(state_); compiler::CodeAssembler::SourcePositionScope pos_scope(&ca_); compiler::CodeAssemblerParameterizedLabel<> block0(&ca_, compiler::CodeAssemblerLabel::kNonDeferred); compiler::CodeAssemblerParameterizedLabel<> block4(&ca_, compiler::CodeAssemblerLabel::kNonDeferred); compiler::CodeAssemblerParameterizedLabel<> block3(&ca_, compiler::CodeAssemblerLabel::kNonDeferred); compiler::CodeAssemblerParameterizedLabel<> block5(&ca_, compiler::CodeAssemblerLabel::kNonDeferred); ca_.Goto(&block0); TNode<EmbedderDataArray> tmp0; if (block0.is_used()) { ca_.Bind(&block0); compiler::CodeAssemblerLabel label1(&ca_); tmp0 = DownCastForTorqueClass_EmbedderDataArray_0(state_, TNode<HeapObject>{p_obj}, &label1); ca_.Goto(&block3); if (label1.is_used()) { ca_.Bind(&label1); ca_.Goto(&block4); } } if (block4.is_used()) { ca_.Bind(&block4); ca_.Goto(label_CastError); } if (block3.is_used()) { ca_.Bind(&block3); ca_.Goto(&block5); } ca_.Bind(&block5); return TNode<EmbedderDataArray>{tmp0}; } // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/objects/embedder-data-array.tq?l=7&c=3 TNode<Smi> LoadEmbedderDataArrayLength_0(compiler::CodeAssemblerState* state_, TNode<EmbedderDataArray> p_o) { compiler::CodeAssembler ca_(state_); compiler::CodeAssembler::SourcePositionScope pos_scope(&ca_); compiler::CodeAssemblerParameterizedLabel<> block0(&ca_, compiler::CodeAssemblerLabel::kNonDeferred); compiler::CodeAssemblerParameterizedLabel<> block2(&ca_, compiler::CodeAssemblerLabel::kNonDeferred); ca_.Goto(&block0); TNode<IntPtrT> tmp0; TNode<Smi> tmp1; if (block0.is_used()) { ca_.Bind(&block0); tmp0 = FromConstexpr_intptr_constexpr_int31_0(state_, 4); tmp1 = CodeStubAssembler(state_).LoadReference<Smi>(CodeStubAssembler::Reference{p_o, tmp0}); ca_.Goto(&block2); } ca_.Bind(&block2); return TNode<Smi>{tmp1}; } // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/objects/embedder-data-array.tq?l=7&c=3 void StoreEmbedderDataArrayLength_0(compiler::CodeAssemblerState* state_, TNode<EmbedderDataArray> p_o, TNode<Smi> p_v) { compiler::CodeAssembler ca_(state_); compiler::CodeAssembler::SourcePositionScope pos_scope(&ca_); compiler::CodeAssemblerParameterizedLabel<> block0(&ca_, compiler::CodeAssemblerLabel::kNonDeferred); compiler::CodeAssemblerParameterizedLabel<> block2(&ca_, compiler::CodeAssemblerLabel::kNonDeferred); ca_.Goto(&block0); TNode<IntPtrT> tmp0; if (block0.is_used()) { ca_.Bind(&block0); tmp0 = FromConstexpr_intptr_constexpr_int31_0(state_, 4); CodeStubAssembler(state_).StoreReference<Smi>(CodeStubAssembler::Reference{p_o, tmp0}, p_v); ca_.Goto(&block2); } ca_.Bind(&block2); } // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/objects/embedder-data-array.tq?l=5&c=1 TNode<EmbedderDataArray> DownCastForTorqueClass_EmbedderDataArray_0(compiler::CodeAssemblerState* state_, TNode<HeapObject> p_o, compiler::CodeAssemblerLabel* label_CastError) { compiler::CodeAssembler ca_(state_); compiler::CodeAssembler::SourcePositionScope pos_scope(&ca_); compiler::CodeAssemblerParameterizedLabel<> block0(&ca_, compiler::CodeAssemblerLabel::kNonDeferred); compiler::CodeAssemblerParameterizedLabel<> block3(&ca_, compiler::CodeAssemblerLabel::kNonDeferred); compiler::CodeAssemblerParameterizedLabel<> block6(&ca_, compiler::CodeAssemblerLabel::kNonDeferred); compiler::CodeAssemblerParameterizedLabel<> block9(&ca_, compiler::CodeAssemblerLabel::kNonDeferred); compiler::CodeAssemblerParameterizedLabel<> block10(&ca_, compiler::CodeAssemblerLabel::kNonDeferred); compiler::CodeAssemblerParameterizedLabel<> block7(&ca_, compiler::CodeAssemblerLabel::kNonDeferred); compiler::CodeAssemblerParameterizedLabel<> block11(&ca_, compiler::CodeAssemblerLabel::kNonDeferred); compiler::CodeAssemblerParameterizedLabel<> block12(&ca_, compiler::CodeAssemblerLabel::kNonDeferred); compiler::CodeAssemblerParameterizedLabel<> block8(&ca_, compiler::CodeAssemblerLabel::kNonDeferred); compiler::CodeAssemblerParameterizedLabel<> block4(&ca_, compiler::CodeAssemblerLabel::kNonDeferred); compiler::CodeAssemblerParameterizedLabel<> block13(&ca_, compiler::CodeAssemblerLabel::kNonDeferred); compiler::CodeAssemblerParameterizedLabel<> block14(&ca_, compiler::CodeAssemblerLabel::kNonDeferred); compiler::CodeAssemblerParameterizedLabel<> block5(&ca_, compiler::CodeAssemblerLabel::kNonDeferred); compiler::CodeAssemblerParameterizedLabel<> block1(&ca_, compiler::CodeAssemblerLabel::kNonDeferred); compiler::CodeAssemblerParameterizedLabel<> block15(&ca_, compiler::CodeAssemblerLabel::kNonDeferred); ca_.Goto(&block0); TNode<IntPtrT> tmp0; TNode<Map> tmp1; if (block0.is_used()) { ca_.Bind(&block0); tmp0 = FromConstexpr_intptr_constexpr_int31_0(state_, 0); tmp1 = CodeStubAssembler(state_).LoadReference<Map>(CodeStubAssembler::Reference{p_o, tmp0}); if (((CodeStubAssembler(state_).ConstexprInt31Equal(static_cast<InstanceType>(247), static_cast<InstanceType>(247))))) { ca_.Goto(&block3); } else { ca_.Goto(&block4); } } if (block3.is_used()) { ca_.Bind(&block3); if ((CodeStubAssembler(state_).ClassHasMapConstant<EmbedderDataArray>())) { ca_.Goto(&block6); } else { ca_.Goto(&block7); } } TNode<Map> tmp2; TNode<BoolT> tmp3; if (block6.is_used()) { ca_.Bind(&block6); tmp2 = CodeStubAssembler(state_).GetClassMapConstant<EmbedderDataArray>(); tmp3 = CodeStubAssembler(state_).TaggedNotEqual(TNode<HeapObject>{tmp1}, TNode<HeapObject>{tmp2}); ca_.Branch(tmp3, &block9, std::vector<compiler::Node*>{}, &block10, std::vector<compiler::Node*>{}); } if (block9.is_used()) { ca_.Bind(&block9); ca_.Goto(&block1); } if (block10.is_used()) { ca_.Bind(&block10); ca_.Goto(&block8); } TNode<IntPtrT> tmp4; TNode<Uint16T> tmp5; TNode<Uint32T> tmp6; TNode<BoolT> tmp7; if (block7.is_used()) { ca_.Bind(&block7); tmp4 = FromConstexpr_intptr_constexpr_int31_0(state_, 8); tmp5 = CodeStubAssembler(state_).LoadReference<Uint16T>(CodeStubAssembler::Reference{tmp1, tmp4}); tmp6 = FromConstexpr_uint32_constexpr_uint32_0(state_, static_cast<InstanceType>(247)); tmp7 = CodeStubAssembler(state_).Word32NotEqual(TNode<Uint32T>{tmp5}, TNode<Uint32T>{tmp6}); ca_.Branch(tmp7, &block11, std::vector<compiler::Node*>{}, &block12, std::vector<compiler::Node*>{}); } if (block11.is_used()) { ca_.Bind(&block11); ca_.Goto(&block1); } if (block12.is_used()) { ca_.Bind(&block12); ca_.Goto(&block8); } if (block8.is_used()) { ca_.Bind(&block8); ca_.Goto(&block5); } TNode<Int32T> tmp8; TNode<IntPtrT> tmp9; TNode<Uint16T> tmp10; TNode<Uint16T> tmp11; TNode<Int32T> tmp12; TNode<Uint16T> tmp13; TNode<Uint16T> tmp14; TNode<Int32T> tmp15; TNode<Int32T> tmp16; TNode<Uint32T> tmp17; TNode<Uint32T> tmp18; TNode<BoolT> tmp19; if (block4.is_used()) { ca_.Bind(&block4); tmp8 = FromConstexpr_int32_constexpr_int32_0(state_, (CodeStubAssembler(state_).ConstexprUint32Sub(static_cast<InstanceType>(247), static_cast<InstanceType>(247)))); tmp9 = FromConstexpr_intptr_constexpr_int31_0(state_, 8); tmp10 = CodeStubAssembler(state_).LoadReference<Uint16T>(CodeStubAssembler::Reference{tmp1, tmp9}); tmp11 = Convert_uint16_InstanceType_0(state_, TNode<Uint16T>{tmp10}); tmp12 = Convert_int32_uint16_0(state_, TNode<Uint16T>{tmp11}); tmp13 = FromConstexpr_InstanceType_constexpr_InstanceType_0(state_, static_cast<InstanceType>(247)); tmp14 = Convert_uint16_InstanceType_0(state_, TNode<Uint16T>{tmp13}); tmp15 = Convert_int32_uint16_0(state_, TNode<Uint16T>{tmp14}); tmp16 = CodeStubAssembler(state_).Int32Sub(TNode<Int32T>{tmp12}, TNode<Int32T>{tmp15}); tmp17 = CodeStubAssembler(state_).Unsigned(TNode<Int32T>{tmp16}); tmp18 = CodeStubAssembler(state_).Unsigned(TNode<Int32T>{tmp8}); tmp19 = CodeStubAssembler(state_).Uint32GreaterThan(TNode<Uint32T>{tmp17}, TNode<Uint32T>{tmp18}); ca_.Branch(tmp19, &block13, std::vector<compiler::Node*>{}, &block14, std::vector<compiler::Node*>{}); } if (block13.is_used()) { ca_.Bind(&block13); ca_.Goto(&block1); } if (block14.is_used()) { ca_.Bind(&block14); ca_.Goto(&block5); } TNode<EmbedderDataArray> tmp20; if (block5.is_used()) { ca_.Bind(&block5); tmp20 = TORQUE_CAST(TNode<HeapObject>{p_o}); ca_.Goto(&block15); } if (block1.is_used()) { ca_.Bind(&block1); ca_.Goto(label_CastError); } ca_.Bind(&block15); return TNode<EmbedderDataArray>{tmp20}; } } // namespace internal } // namespace v8
e19f1a1a1645045abe3f86a5996dabb11f812a8e
5f382f2c1d881593cc7f1d95701e7d110772dd6b
/bubble_sort.cpp
444eb94d32c2b942f067179ed11f0f0a3f0ee0d9
[]
no_license
Shafeequr1999/Arrays-in-cpp
b49d9350ada972488ed31f99afaa1c43464c202f
969ab49d9bf8885b8800f7c07ca0bb865bf6deda
refs/heads/main
2023-07-12T07:01:55.942670
2021-08-25T17:08:07
2021-08-25T17:08:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
506
cpp
#include<iostream> using namespace std; int main(){ int n; cin>>n; int arr[n]; for(int i=0;i<n;i++){ cin>>arr[i]; } int counter=1; /* for iterations */ while(counter<n){ for(int i=0;i<n-counter;i++){ if(arr[i]>arr[i+1]){ int temp=arr[i]; arr[i]=arr[i+1]; arr[i+1]=temp; } } counter++; } for(int i=0;i<n;i++){ cout<<arr[i]<<' '; } }
547ab763ea570b0702025c30cf3d90ae02d766a0
df192b4e12ff9fb349fe9a5bf2ced2bc8e3fee53
/IntroToProgramming/Car/Car/Car.h
6695cbf23026fd6a760cd19316109966082981c1
[]
no_license
matthewguillory65/IntroToProgramming
1d2c6eba77ffb04b6089c2724686b54b160b333f
b74f9d1980423b6092b44d65504183cabdedafee
refs/heads/master
2020-04-17T00:35:28.501294
2016-09-02T22:36:16
2017-03-08T21:19:40
66,005,290
0
0
null
null
null
null
UTF-8
C++
false
false
378
h
#pragma once class Vehicle { private: char m_Name; char m_Manufacturer; int m_Year; int m_Fuel; bool m_Run; public: Vehicle(); Vehicle(char m_Name, char m_Manufacturer, int m_Year, int m_Fuel, bool m_Run); Vehicle Camero("Camero, Chevorlet, 2007, 35, true"); }; Vehicle::Vehicle() { m_Name Camero; m_Manufacturer Chevorlet; m_Year 2007; m_Fuel 35; m_Run true; }
f148f8f5034de5c8505b4ea86eacc09214f52163
744bdc137a0139b7e2f02efcf67a3fcf1efd8631
/core/hooks/hooks.hpp
bb7fff621df1f5d079064f1b1d1c94d69fe6dab9
[]
no_license
ninecents/adderall
2054ef73e0967d8cd07c7c1393b58a972e29304b
cba5e9990e5ef409a2e4bd7edb404f8527e9330d
refs/heads/master
2022-11-04T08:28:45.205819
2020-06-12T17:07:45
2020-06-22T03:41:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,076
hpp
#pragma once namespace hooks { inline vmt_hook client_hook{ }; inline vmt_hook clientmode_hook{ }; inline vmt_hook panel_hook{ }; inline vmt_hook renderview_hook{ }; inline vmt_hook surface_hook{ }; inline WNDPROC wndproc_original{ }; void initialize( ); void shutdown( ); using create_move_fn = bool( __thiscall* )( i_client_mode*, float, c_usercmd* ); using frame_stage_notify_fn = void( __thiscall* )( i_base_client_dll*, int ); using paint_traverse_fn = void( __thiscall* )( i_panel*, unsigned int, bool, bool ); using scene_end_fn = void( __thiscall* )( void* ); using lock_cursor_fn = void(__thiscall*)(void*); static bool __stdcall create_move( float frame_time, c_usercmd* cmd ); static float __stdcall viewmodel_fov(); static void __stdcall frame_stage_notify( int frame_stage ); static void __stdcall paint_traverse( unsigned int panel, bool force_repaint, bool allow_force ); static void __stdcall scene_end( ); static void __stdcall lock_cursor(); static LRESULT __stdcall wndproc( HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam ); }
1fee2b65a3f5d8b34f18723c89472541b8adea80
877fff5bb313ccd23d1d01bf23b1e1f2b13bb85a
/app/src/main/cpp/dir7941/dir7942/dir8062/dir8063/dir12766/dir12767/dir13029/dir15097/dir15260/dir15321/dir17491/file17607.cpp
03d909720b59b6d3f0c3b0d59697252d257ba2fe
[]
no_license
tgeng/HugeProject
829c3bdfb7cbaf57727c41263212d4a67e3eb93d
4488d3b765e8827636ce5e878baacdf388710ef2
refs/heads/master
2022-08-21T16:58:54.161627
2020-05-28T01:54:03
2020-05-28T01:54:03
267,468,475
0
0
null
null
null
null
UTF-8
C++
false
false
115
cpp
#ifndef file17607 #error "macro file17607 must be defined" #endif static const char* file17607String = "file17607";
9ad93f0dd1bb314f702795c7a8edcf27e59c8dbf
d034a5ce6e10c7f5f129ddb739f02ebfcd4ffd71
/count_sort/count_sort.cpp
e723045484f90cdd8e747cddbf4a5f83b4f6f624
[]
no_license
RandGor/mpiaa
e778595c9a9a8530315aee4eb0bddc46e24b13de
d27024b48247efd6cd2ce3fa6203faa89d3acd03
refs/heads/master
2020-09-25T22:24:09.911104
2019-11-21T15:48:38
2019-11-21T15:48:38
226,100,878
0
0
null
2019-12-05T12:47:45
2019-12-05T12:47:44
null
UTF-8
C++
false
false
286
cpp
#include "count_sort.h" // All elements of array are from [start, end] diapason. // Function must return sorted array. std::vector<int> count_sort(const std::vector<int> &array, int start, int end) { std::vector<int> result; // Your implementation here. return result; }
d7b411a141fb0ea3624d3a6bc29ed419dac9f26f
ec11b1888fef669aa595e0e36b9b031a93fd8fcd
/insert.cpp
1aef17cef4cc88da604a7b7e41d5484802105533
[]
no_license
pranav2202/linked_list
cff34425a18c1e0e4abe80bd743dc9e84cc13db0
e599d0a222d004ae5bbca90286ab2b8fb2c536db
refs/heads/master
2020-08-23T11:27:07.199571
2019-10-21T15:51:29
2019-10-21T15:51:29
216,605,886
0
0
null
null
null
null
UTF-8
C++
false
false
1,017
cpp
#include <iostream> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ using namespace std; class node{ public: int data; node *next;//store address of next node in linked list }; node *head;//create a variable that will store address of first member of linked list and pointer to address . global variable void insert(int n){ node *temp = new node();//creating a node temp->data = n;//variable temp storing address temp->next = head;//points to head's previous pointer to address //corner case when node is empty head = temp;//value in head stores address of temp in head new value } void print(){ node *temp = head; while(temp!=NULL){ cout<<temp->data<<" "; temp = temp->next; } cout<<endl; } int main(int argc, char** argv) { head = NULL;//ponter variable points nowhere i.e list is empty int n; cout<<"how many no.s"<<endl; cin>>n; for (int i = 0;i<n;i++){ int x; cin>>x; insert(x); print(); } return 0; }
42ce3b73bdfdf0e49e6c6abfe0684033d44b06f6
e18a493f699ac5248d79a4d210f758b21e455954
/Unique_Letter/Source.cpp
199af4cd24f2b4189fc8ffd5fcb94775f0643c2b
[]
no_license
Phurich63010767/Unique_Letter
41483768760b65018e2c3fcaf7d98429ddce146c
c804752e9b819ef6ae7ad5c07a97981d7630e7d3
refs/heads/master
2022-12-09T00:08:02.562799
2020-09-09T07:19:52
2020-09-09T07:19:52
294,034,390
0
0
null
null
null
null
UTF-8
C++
false
false
394
cpp
#include<iostream> using namespace std; void unique(int i,int s,string x) { while (i < s) { char* p1 = &x[i]; if (i == 0) { cout << x[0]; } if (i > 0) { if (x[i] != x[i - 1]) { cout << *p1; } } i++; } } int main() { int s, i = 0; string x; cout << "Enter letters or numbers: "; cin >> x; s = x.size(); cout << "Unique: "; unique(i,s,x); return 0; }
f924e58b6d8022765ce8fcadeda533ed04378ae8
a96bec16551c66b2ef6dcefef86f9c630dbdcd8b
/src/client/DoubleLaser.cpp
cf723e87bfa86907938772155ca472b40dbae7d0
[]
no_license
Tmauc/R-Type
9aeed59104c6fe239e71f120340e4a3b3d730002
3622225005cb7ce36d2cefad3151ed9548cb623c
refs/heads/master
2023-05-22T17:53:53.541282
2021-06-10T17:42:52
2021-06-10T17:42:52
375,781,148
1
0
null
null
null
null
UTF-8
C++
false
false
594
cpp
#include "DoubleLaser.hpp" DoubleLaser::DoubleLaser() : Projectile("../res/proj/r-typesheet2.gif", sf::Vector2f(0,0), sf::IntRect(36,470,66,32), 10, 5, 1000, false) { } DoubleLaser::~DoubleLaser() { } void DoubleLaser::launch(float angle, sf::Vector2f pos) { _pos = pos; _alive = true; _angle = angle; _rangeDone = 0; } void DoubleLaser::update(float delta) { _anim.update(delta); updateAnimFrame(); if (_alive) { move(_sp, 0); _rangeDone += _sp; if (_rangeDone > _range) { launch(0, sf::Vector2f(200,200)); } } }
5c1444be9a8ca84ea6fba72e01e1ed87627aa68e
f299358f6bc39d0586887e52a0099b3f15ced70b
/src/gl/program.cpp
c30b5ec5db3927ba80575d85c8754903b5675c72
[]
no_license
LitEngine/Rendering
5432feaaf2b9fbefc1540fafaf5b17d271fc7b8b
94c33a8ca5135294be20aba9edbf14c1563b9d91
refs/heads/master
2023-05-03T11:02:26.023893
2021-05-15T06:45:06
2021-05-15T06:45:06
367,560,362
0
0
null
null
null
null
UTF-8
C++
false
false
416
cpp
#include <lit/gl/program.hpp> using namespace lit::gl; GlProgram::~GlProgram() { Delete(); } int GlProgram::GetUniformLocation(const std::string &name) { return glGetUniformLocation(m_program_id, name.c_str()); } void GlProgram::Use() { if (m_program_id) { glUseProgram(m_program_id); } } void GlProgram::Delete() { if (m_program_id) { glDeleteProgram(m_program_id); } }
5e4ed2fa780a3f6c661e23a0ff5d839917a7a744
f813e6de1ec4649cd9c35553e6928d331bdccfa4
/src/chainparams.cpp
84ddf842b51befde09fcd01f68f63db831f1d624
[ "MIT" ]
permissive
TaurusNetwork/TaurusNetwork
f93f8ace0291d8244e3a6c1a01268627f91c8a18
5abb721b9c60baafac02283b26a6400470fda7d3
refs/heads/master
2020-03-22T16:22:54.441113
2018-07-09T17:54:29
2018-07-09T17:54:29
138,114,950
0
0
null
null
null
null
UTF-8
C++
false
false
14,269
cpp
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Copyright (c) 2018 The TaurusNetwork developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "chainparams.h" #include "random.h" #include "util.h" #include "utilstrencodings.h" #include <assert.h> #include <boost/assign/list_of.hpp> using namespace std; using namespace boost::assign; struct SeedSpec6 { uint8_t addr[16]; uint16_t port; }; #include "chainparamsseeds.h" /** * Main network */ //! Convert the pnSeeds6 array into usable address objects. static void convertSeed6(std::vector<CAddress>& vSeedsOut, const SeedSpec6* data, unsigned int count) { // 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; for (unsigned int i = 0; i < count; i++) { struct in6_addr ip; memcpy(&ip, data[i].addr, sizeof(ip)); CAddress addr(CService(ip, data[i].port)); addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek; vSeedsOut.push_back(addr); } } // What makes a good checkpoint block? // + Is surrounded by blocks with reasonable timestamps // (no blocks before with a timestamp after, none after with // timestamp before) // + Contains no strange transactions static Checkpoints::MapCheckpoints mapCheckpoints = boost::assign::map_list_of(0, uint256("0x")); ; static const Checkpoints::CCheckpointData data = { &mapCheckpoints, 1527479817, // * UNIX timestamp of last checkpoint block 0, // * total number of transactions between genesis and last checkpoint // (the tx=... number in the SetBestChain debug.log lines) 1440 // * estimated number of transactions per day after checkpoint }; static Checkpoints::MapCheckpoints mapCheckpointsTestnet = boost::assign::map_list_of(0, uint256("0x")); static const Checkpoints::CCheckpointData dataTestnet = { &mapCheckpointsTestnet, 0, 0, 0}; static Checkpoints::MapCheckpoints mapCheckpointsRegtest = boost::assign::map_list_of(0, uint256("0x")); static const Checkpoints::CCheckpointData dataRegtest = { &mapCheckpointsRegtest, 0, 0, 0}; class CMainParams : public CChainParams { public: CMainParams() { networkID = CBaseChainParams::MAIN; strNetworkID = "main"; /** * The message start string is designed to be unlikely to occur in normal data. * The characters are rarely used upper ASCII, not valid as UTF-8, and produce * a large 4-byte int at any alignment. */ pchMessageStart[0] = 0x29; pchMessageStart[1] = 0x62; pchMessageStart[2] = 0x55; pchMessageStart[3] = 0x28; vAlertPubKey = ParseHex("04375db20be5c53b93678e2e41c9def7af38197280c65e813f682adf2ed501ac186022562dbdf2ce3204d07432660fb61ecad8e78b6b8d39c568fb892db8ecb736"); nDefaultPort = 19401; bnProofOfWorkLimit = ~uint256(0) >> 20; nSubsidyHalvingInterval = 210000; nMaxReorganizationDepth = 100; nEnforceBlockUpgradeMajority = 750; nRejectBlockOutdatedMajority = 950; nToCheckBlockUpgradeMajority = 1000; nMinerThreads = 0; nTargetTimespan = 1 * 60; nTargetSpacing = 1 * 60; nLastPOWBlock = 500; nMaturity = 201; nMasternodeCountDrift = 20; nMasternodeColleteralLimxDev = 5000; //Params().MasternodeColleteralLimxDev() nModifierUpdateBlock = 1; // we use the version 2 for dmd nMaxMoneyOut = 235813213 * COIN; const char* pszTimestamp = "TaurusNetwork cryptocurrency"; CMutableTransaction txNew; txNew.vin.resize(1); txNew.vout.resize(1); txNew.vin[0].scriptSig = CScript() << 486604799 << CScriptNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); txNew.vout[0].nValue = 0 * COIN; txNew.vout[0].scriptPubKey = CScript() << ParseHex("04e669b57880e492fdd2f0cdfd45b52b078a32a5282b4784202ac53b1299837e271f780192a8b014d33b51a6f8bbfc4cfaa3385829452bec7b77bf2f8f97520526") << OP_CHECKSIG; genesis.vtx.push_back(txNew); genesis.hashPrevBlock = 0; genesis.hashMerkleRoot = genesis.BuildMerkleTree(); genesis.nVersion = 1; genesis.nTime = 1529467399; genesis.nBits = 0x1e0ffff0; genesis.nNonce = 0; hashGenesisBlock = genesis.GetHash(); //printf("%s\n", hashGenesisBlock.ToString().c_str()); //printf("%s\n", genesis.hashMerkleRoot.ToString().c_str()); assert(hashGenesisBlock == uint256("0x")); assert(genesis.hashMerkleRoot == uint256("0x")); vSeeds.push_back(CDNSSeedData("taurusnetwork-node-1.dynu.net", "taurusnetwork-node-1.dynu.net")); vSeeds.push_back(CDNSSeedData("taurusnetwork-node-2.dynu.net", "taurusnetwork-node-2.dynu.net")); //vFixedSeeds.clear(); //vSeeds.clear(); base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1, 28); base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1, 16); base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1, 193); base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x04)(0x88)(0xB2)(0x1E).convert_to_container<std::vector<unsigned char> >(); base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x04)(0x88)(0xAD)(0xE4).convert_to_container<std::vector<unsigned char> >(); // BIP44 coin type is from https://github.com/satoshilabs/slips/blob/master/slip-0044.md 109 0x8000006d base58Prefixes[EXT_COIN_TYPE] = boost::assign::list_of(0x80)(0x00)(0x00)(0x6d).convert_to_container<std::vector<unsigned char> >(); convertSeed6(vFixedSeeds, pnSeed6_main, ARRAYLEN(pnSeed6_main)); fRequireRPCPassword = true; fMiningRequiresPeers = false; fAllowMinDifficultyBlocks = false; fDefaultConsistencyChecks = false; fRequireStandard = true; fMineBlocksOnDemand = false; fSkipProofOfWorkCheck = false; fTestnetToBeDeprecatedFieldRPC = false; fHeadersFirstSyncingActive = false; nPoolMaxTransactions = 3; strSporkKey = "0478c3e932fbe183b2f665de937866cb1cfc5ed4b0bf733b72286f265ffc03ff52dfd669fbb3f77d630e5393da65c721a9a891d2c4c6aa515dfd25ffe545582357"; strDarksendPoolDummyAddress = "AcmpqXViWUXNroqVNYRdKjKrFM6PNa1oTM"; nStartMasternodePayments = 1527479817; } const Checkpoints::CCheckpointData& Checkpoints() const { return data; } }; static CMainParams mainParams; /** * Testnet (v3) */ class CTestNetParams : public CMainParams { public: CTestNetParams() { networkID = CBaseChainParams::TESTNET; strNetworkID = "test"; pchMessageStart[0] = 0x14; pchMessageStart[1] = 0x64; pchMessageStart[2] = 0x54; pchMessageStart[3] = 0x65; vAlertPubKey = ParseHex("0485286086a0871308bf36519edb18d95bbe9b098abe14ec9b684b5255028ec644bacdbddb98a522a6bcd7ab8e7d3582d7a5b9bf59c427f7eabce447b5ba6de25f"); nDefaultPort = 56123; nEnforceBlockUpgradeMajority = 51; nRejectBlockOutdatedMajority = 75; nToCheckBlockUpgradeMajority = 100; nMinerThreads = 0; nTargetTimespan = 1 * 60; nTargetSpacing = 1 * 60; nLastPOWBlock = 200; nMaturity = 15; nModifierUpdateBlock = 51197; //approx Mon, 30 Apr 2018 04:00:00 GMT nMaxMoneyOut = 90000000 * COIN; //! Modify the testnet genesis block so the timestamp is valid for a later start. genesis.nTime = 1527479818; genesis.nNonce = 0; hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == uint256("0x")); vFixedSeeds.clear(); vSeeds.clear(); base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1, 83); base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1, 18); base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1, 193); // Testnet TaurusNetwork BIP32 pubkeys start with 'DRKV' base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x3a)(0x80)(0x61)(0xa0).convert_to_container<std::vector<unsigned char> >(); // Testnet TaurusNetwork BIP32 prvkeys start with 'DRKP' base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x3a)(0x80)(0x58)(0x37).convert_to_container<std::vector<unsigned char> >(); // Testnet TaurusNetwork BIP44 coin type is '1' (All coin's testnet default) base58Prefixes[EXT_COIN_TYPE] = boost::assign::list_of(0x80)(0x00)(0x00)(0x01).convert_to_container<std::vector<unsigned char> >(); convertSeed6(vFixedSeeds, pnSeed6_test, ARRAYLEN(pnSeed6_test)); fRequireRPCPassword = true; fMiningRequiresPeers = true; fAllowMinDifficultyBlocks = true; fDefaultConsistencyChecks = false; fRequireStandard = false; fMineBlocksOnDemand = false; fTestnetToBeDeprecatedFieldRPC = true; nPoolMaxTransactions = 2; strSporkKey = "04363509d5c65f5a9ca7ceedad4887007ae85469d249a6f566b788504ee5e105bcf1bbc515f49a7aac3bceb8864bb2ba84bebd92c66ff9022309e2bfbd5f70d11f"; strDarksendPoolDummyAddress = ""; nStartMasternodePayments = 1527479818; } const Checkpoints::CCheckpointData& Checkpoints() const { return dataTestnet; } }; static CTestNetParams testNetParams; /** * Regression test */ class CRegTestParams : public CTestNetParams { public: CRegTestParams() { networkID = CBaseChainParams::REGTEST; strNetworkID = "regtest"; strNetworkID = "regtest"; pchMessageStart[0] = 0x65; pchMessageStart[1] = 0x14; pchMessageStart[2] = 0x54; pchMessageStart[3] = 0x64; nSubsidyHalvingInterval = 150; nEnforceBlockUpgradeMajority = 750; nRejectBlockOutdatedMajority = 950; nToCheckBlockUpgradeMajority = 1000; nMinerThreads = 1; nTargetTimespan = 24 * 60 * 60; nTargetSpacing = 1 * 60; bnProofOfWorkLimit = ~uint256(0) >> 1; genesis.nTime = 1527479819; genesis.nBits = 0x207fffff; genesis.nNonce = 0; hashGenesisBlock = genesis.GetHash(); nDefaultPort = 57123; assert(hashGenesisBlock == uint256("0x")); vFixedSeeds.clear(); //! Testnet mode doesn't have any fixed seeds. vSeeds.clear(); //! Testnet mode doesn't have any DNS seeds. fRequireRPCPassword = false; fMiningRequiresPeers = false; fAllowMinDifficultyBlocks = true; fDefaultConsistencyChecks = true; fRequireStandard = false; fMineBlocksOnDemand = true; fTestnetToBeDeprecatedFieldRPC = false; } const Checkpoints::CCheckpointData& Checkpoints() const { return dataRegtest; } }; static CRegTestParams regTestParams; /** * Unit test */ class CUnitTestParams : public CMainParams, public CModifiableParams { public: CUnitTestParams() { networkID = CBaseChainParams::UNITTEST; strNetworkID = "unittest"; nDefaultPort = 56123; vFixedSeeds.clear(); //! Unit test mode doesn't have any fixed seeds. vSeeds.clear(); //! Unit test mode doesn't have any DNS seeds. fRequireRPCPassword = false; fMiningRequiresPeers = false; fDefaultConsistencyChecks = true; fAllowMinDifficultyBlocks = false; fMineBlocksOnDemand = true; } const Checkpoints::CCheckpointData& Checkpoints() const { // UnitTest share the same checkpoints as MAIN return data; } //! Published setters to allow changing values in unit test cases virtual void setSubsidyHalvingInterval(int anSubsidyHalvingInterval) { nSubsidyHalvingInterval = anSubsidyHalvingInterval; } virtual void setEnforceBlockUpgradeMajority(int anEnforceBlockUpgradeMajority) { nEnforceBlockUpgradeMajority = anEnforceBlockUpgradeMajority; } virtual void setRejectBlockOutdatedMajority(int anRejectBlockOutdatedMajority) { nRejectBlockOutdatedMajority = anRejectBlockOutdatedMajority; } virtual void setToCheckBlockUpgradeMajority(int anToCheckBlockUpgradeMajority) { nToCheckBlockUpgradeMajority = anToCheckBlockUpgradeMajority; } virtual void setDefaultConsistencyChecks(bool afDefaultConsistencyChecks) { fDefaultConsistencyChecks = afDefaultConsistencyChecks; } virtual void setAllowMinDifficultyBlocks(bool afAllowMinDifficultyBlocks) { fAllowMinDifficultyBlocks = afAllowMinDifficultyBlocks; } virtual void setSkipProofOfWorkCheck(bool afSkipProofOfWorkCheck) { fSkipProofOfWorkCheck = afSkipProofOfWorkCheck; } }; static CUnitTestParams unitTestParams; static CChainParams* pCurrentParams = 0; CModifiableParams* ModifiableParams() { assert(pCurrentParams); assert(pCurrentParams == &unitTestParams); return (CModifiableParams*)&unitTestParams; } const CChainParams& Params() { assert(pCurrentParams); return *pCurrentParams; } CChainParams& Params(CBaseChainParams::Network network) { switch (network) { case CBaseChainParams::MAIN: return mainParams; case CBaseChainParams::TESTNET: return testNetParams; case CBaseChainParams::REGTEST: return regTestParams; case CBaseChainParams::UNITTEST: return unitTestParams; default: assert(false && "Unimplemented network"); return mainParams; } } void SelectParams(CBaseChainParams::Network network) { SelectBaseParams(network); pCurrentParams = &Params(network); } bool SelectParamsFromCommandLine() { CBaseChainParams::Network network = NetworkIdFromCommandLine(); if (network == CBaseChainParams::MAX_NETWORK_TYPES) return false; SelectParams(network); return true; }
[ "1" ]
1
9b48bbadfcb5fa2d595d1492784c4d4577e0c08b
82d43f28d71f74d6f69cf2f005ace0e3bbb096df
/src/Types.hpp
cb42202f651026e7db9fdde15ef16f11effeff45
[ "MIT" ]
permissive
nandofioretto/DP_power_flow
99d34a70e89cb2e500084edcaf1d22f47356de0b
641e42ae4f1f7d9b82f323256fec86d7aa8f8ac1
refs/heads/master
2021-06-19T13:23:07.784900
2017-05-20T16:30:08
2017-05-20T16:30:08
75,733,854
0
0
null
null
null
null
UTF-8
C++
false
false
1,153
hpp
// // Created by Ferdinando Fioretto on 11/7/15. // #ifndef TYPES_H #define TYPES_H #include <limits> #include "Preferences.hpp" //typedef long long int power_t; // Bit encoding [1111 1111] [1111 1111] .. [] this can represent loads and generators up to optH=8 typedef double value_t; //typedef int value_t; typedef double util_t; //typedef int util_t; // Constants class Constants { public: static constexpr value_t NaN = std::numeric_limits<value_t>::min() + 1; static constexpr util_t inf = #ifdef MINIMIZE std::numeric_limits<util_t>::max(); #else std::numeric_limits<util_t>::min(); #endif static constexpr util_t unsat = inf; // move this to u_math:: namespace static constexpr bool isFinite(util_t c) { return c != inf && c != -inf; } static constexpr bool isSat(util_t c) { return c != unsat; } static constexpr util_t worstvalue = inf; // static constexpr util_t bestvalue = inf; static util_t aggregate(util_t a, util_t b) { return (a != unsat && b != unsat) ? a + b : unsat; } private: Constants() { } }; #endif //TYPES_H
07751ac17182ca96e51a64a1a503f8f8ddb00222
662aa82d67a190b936abcbe1ea6e694b31d8da03
/src/point_cloud_io/src/joint_logger.cpp
5c67befee3fdd35fb83db8c0c826d127ec73d0fa
[]
no_license
joosm/ur5_simulation
0fb3ea78a02becf83579e63029a24cd5d9863533
55573f471513923b8408b3e10d35ac5177ffb2c2
refs/heads/master
2020-12-21T11:01:05.516556
2017-06-18T17:43:20
2017-06-18T17:43:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
622
cpp
/* * write_node.cpp * * Created on: Nov 13, 2015 * Author: Remo Diethelm * Institute: ETH Zurich, Autonomous Systems Lab */ #include <ros/ros.h> #include <stdio.h> #include "point_cloud_io/Write.hpp" //point_cloud_io::RobotState stateMonitor; int main(int argc, char** argv) { std::cout << "whoa..." << std::endl; ros::init(argc, argv, "logger"); ros::NodeHandle nodeHandle("~"); point_cloud_io::RobotState stateMonitor; point_cloud_io::Record record(nodeHandle, &stateMonitor); //nodeHandle.subscribe("/joint_states", 1, &joint_state_callback); //ros::spin(); ros::spin(); return 0; }
651ea7a8805683c0f5c6380c2d5d5faae9595c43
46b17d9d2b075e5f930f2f8d14916a9c88ff9903
/LA/Langage/TP1/proc.cpp
ed021f5f2ad6b1c08d01812a498e66d2f4335c11
[]
no_license
Dinty0/Licence-3
6aaf14620382b71135e36fc6b53b231e88fc47d8
8ee02375520ba86eec87ad7576d3dc130b8249be
refs/heads/master
2021-01-10T18:03:57.052659
2016-01-29T12:27:11
2016-01-29T12:27:11
50,660,810
0
0
null
null
null
null
UTF-8
C++
false
false
257
cpp
#include <string> #include <iostream> #include <fstream> using namespace std; int main(){ string mot; int cpt=0; ifstream f; f.open("germinal2.txt",ifstream::in); while(f.good()){ f>>mot; cpt++; } cout<<cpt<<endl; f.close(); return 0; }
ccf84a693434bd9fa56faf94adb966acd1d02d9f
34878de1631becc28edf2624c7dee4810449dd54
/maxi.cpp
fc70d374c02671adf67789ebc81411e0f3648535
[]
no_license
Divyanshushandilyakiet/cpp
abcbd44f209f7f6e10a1d0e8bd150b0383e4a5dc
53a2184f857a4877dd1d370c400cdc6d7abdef00
refs/heads/master
2023-06-16T17:50:05.973843
2021-07-13T16:56:48
2021-07-13T16:56:48
359,115,552
3
0
null
null
null
null
UTF-8
C++
false
false
357
cpp
// check maximun and minimum number #include <iostream> using namespace std; int main(int argc, char const *argv[]) { int n1, n2; cout << "Enter two integers==>> "; cin >> n1 >> n2; if (n1 > n2) { cout << n1 << " is maximum "; } else { cout << n2 << " is maximun"; } return 0; }
3e07189de2bcf47442d7419e3a342db6ce0489a3
8903cb76cedac12995249e2e613af65365be7cf2
/ares/md/vdp/sprite.cpp
9b59671e42426d62035eafc9f754232df1466085
[ "ISC" ]
permissive
kirwinia/ares-emu-v121
0c1e21e073f291741406cd1ed01acca43acd56d7
722aa227caf943a4a64f1678c1bdd07b38b15caa
refs/heads/main
2023-06-09T15:28:23.665934
2021-06-28T06:10:46
2021-06-28T06:10:46
380,923,321
0
0
ISC
2021-06-28T06:05:04
2021-06-28T06:05:04
null
UTF-8
C++
false
false
5,089
cpp
auto VDP::Sprite::write(n16 address, n16 data) -> void { auto baseAddress = nametableAddress; if(vdp.h40()) baseAddress &= ~0x1ff; address -= baseAddress; if(address >= 320) return; auto& object = cache[address >> 2]; switch(address & 3) { case 0: object.y = data.bit( 0, 9); break; case 1: object.link = data.bit( 0, 6); object.height = data.bit( 8, 9); object.width = data.bit(10,11); break; } } //called before mapping fetches auto VDP::Sprite::begin() -> void { for(auto& mapping : mappings) mapping.valid = 0; mappingCount = 0; } //called before pattern fetches auto VDP::Sprite::end() -> void { for(auto& pixel : pixels) pixel.color = 0; visibleLink = 0; visibleCount = 0; visibleStop = 0; patternIndex = 0; patternSlice = 0; patternCount = 0; patternStop = 0; } //called 16 (H32) or 20 (H40) times auto VDP::Sprite::mappingFetch(u32) -> void { if(!vdp.displayEnable()) { return vdp.slot(); } if(test.disablePhase2) return; //mapping fetches are delayed when less than 16/20 objects are visible if(visibleCount++ < objectLimit()) return; auto interlace = vdp.io.interlaceMode == 3; auto y = 129 + (i9)vdp.vcounter(); if(interlace) y = y << 1 | vdp.field(); auto id = visible[mappingCount]; auto& object = cache[id]; auto height = 1 + object.height << 3 + interlace; auto baseAddress = nametableAddress; if(vdp.h40()) baseAddress &= ~0x1ff; auto& mapping = mappings[mappingCount++]; auto address = baseAddress + id * 4 + 2; n16 d2 = vdp.vram.read(address++); n16 d3 = vdp.vram.read(address++); mapping.valid = 1; mapping.width = object.width; mapping.height = object.height; mapping.address = d2.bit(0,10) << 4 + interlace; mapping.hflip = d2.bit(11); mapping.palette = d2.bit(13,14); mapping.priority = d2.bit(15); mapping.x = d3.bit(0,8); y = y - (object.y & (interlace ? 1023 : 511)); if(d2.bit(12)) y = (height - 1) - y; y &= 31; //only the lower 5-bits are considered by the VDP in phase 2 mapping.address += (y >> 3 + interlace) << 4 + interlace; mapping.address += (y & 7 + interlace * 8) << 1; } //called 32 (H32) or 40 (H40) times auto VDP::Sprite::patternFetch(u32) -> void { if(!vdp.displayEnable()) { return vdp.slot(); } if(test.disablePhase3) patternStop = 1; auto interlace = vdp.io.interlaceMode == 3; auto y = 129 + (i9)vdp.vcounter(); if(interlace) y = y << 1 | vdp.field(); if(!patternStop && mappings[patternIndex].valid) { auto& object = mappings[patternIndex]; if(patternX && !object.x) patternStop = 1; patternX = object.x; } else { patternX = 0; } if(!patternStop && mappings[patternIndex].valid) { auto& object = mappings[patternIndex]; auto width = 1 + object.width << 3; auto height = 1 + object.height << 3 + interlace; u32 x = patternSlice * 8; if(object.hflip) x = (width - 1) - x; u32 tileX = x >> 3; u32 tileNumber = tileX * (height >> 3 + interlace); n15 tileAddress = object.address + (tileNumber << 4 + interlace); u16 hi = vdp.vram.read(generatorAddress | tileAddress++); u16 lo = vdp.vram.read(generatorAddress | tileAddress++); u32 data = hi << 16 | lo << 0; if(object.hflip) data = hflip(data); for(auto index : range(8)) { n9 x = object.x + patternSlice * 8 + index - 128; n6 color = data >> 28; data <<= 4; if(!color) continue; if(pixels[x].color) { collision = 1; } else { color |= object.palette << 4; pixels[x] = {color, object.priority}; } } if(++patternSlice >= 1 + object.width) { patternSlice = 0; if(++patternIndex >= objectLimit()) patternStop = 1; } if(++patternCount >= tileLimit()) patternStop = 1; if(patternX && !object.x) patternStop = 1; patternX = object.x; } else { patternX = 0; } y = 129 + (i9)vdp.vcounter(); if(interlace) y = y << 1 | vdp.field(); if(test.disablePhase1) visibleStop = 1; for(auto index : range(2)) { if(visibleStop) break; auto id = visibleLink; auto& object = cache[id]; visibleLink = object.link; if(!visibleLink) visibleStop = 1; auto objectY = object.y & (interlace ? 1023 : 511); auto height = 1 + object.height << 3 + interlace; if(y < objectY) continue; if(y >= objectY + height) continue; visible[visibleCount++] = id; if(visibleCount >= objectLimit()) visibleStop = 1; } } auto VDP::Sprite::pixel(u32 pixelIndex) -> Pixel { return pixels[pixelIndex]; } auto VDP::Sprite::power(bool reset) -> void { generatorAddress = 0; nametableAddress = 0; collision = 0; overflow = 0; for(auto& pixel : pixels) pixel = {}; for(auto& cache : this->cache) cache = {}; for(auto& mapping : mappings) mapping = {}; mappingCount = 0; patternX = 0; patternIndex = 0; patternSlice = 0; patternCount = 0; patternStop = 0; for(auto& visible : this->visible) visible = {}; visibleLink = 0; visibleCount = 0; visibleStop = 0; test = {}; }
46cdaf501058f726d0279eb67912ee18f6855ade
00e06c903140e33964a0ea406c7c4b7702cb47c0
/Deleting_Element.cpp
8b8b9135bd2ba562a098ba89ee53fca0b45ca4c1
[ "Apache-2.0" ]
permissive
FrancoDAlappat/Cpp-BootCamp
e22c7c2d2b718fcdf9d135b08e056ed4a6dada57
556326e7827aa812f22f350e94f257b141ef208b
refs/heads/main
2022-12-30T06:26:42.336151
2020-10-18T12:26:50
2020-10-18T12:26:50
305,083,068
0
0
Apache-2.0
2020-10-18T11:11:30
2020-10-18T11:11:29
null
UTF-8
C++
false
false
736
cpp
#include<iostream.h> #include<conio.h> int Lsearch(int[],int,int); void main() { clrscr(); cout<<"\n***DELETION***\n"; int AR[50],ITEM,N,index; cout<<"\nEnter the array size:"; cin>>N; cout<<"\nEnter Array elements\n"; for(int i=0;i<N;++i) { cin>>AR[i]; } char ch; do { cout<<"\nEnter Element to be deleted :"; cin>>ITEM; index=Lsearch(AR,N,ITEM); if(index==-1) cout<<"\nSorry!! Item could not be found "; else { for(i=index;i<N;++i) AR[i]=AR[i+1]; N=N-1; cout<<"\nThe new array is\n "; for(i=0;i<N;++i) cout<<AR[i]<<" "; } cout<<"\nDo you want to delete more elements(y/n):"; cin>>ch; } while(ch=='y'||ch=='Y'); getch(); } int Lsearch(int AR[],int size ,int item) { for(int i=0;i<size;++i) { if(AR[i]==item) return i; } return -1; }
77bf70a6dd78dad82fe90705c55b66db0a220346
d38b7dd8f362a8f6b75e3ee13f467d6b0e69dcb3
/Data_Strucures/divisible&prime.cpp
51ee3b3679fbb58ea8c9c3715c89674501cc4092
[]
no_license
yatingupta10/Algorithms
84332e564e5c84dbeb696d924d92b4ad2d49a48a
a9de5ba2e52ca53543b4d4cdbdd018816f25ae15
refs/heads/master
2021-01-14T06:22:01.092476
2018-10-06T21:13:57
2018-10-06T21:13:57
50,761,068
7
3
null
2018-10-06T21:13:58
2016-01-31T05:55:36
C
UTF-8
C++
false
false
853
cpp
#include<iostream.h> #include<conio.h> int divide(int a,int b) { if((a%b)==0) return 1; else return 0; } int divide(int a) { int j=a/2,flag=1; for(int i=2;(i<=j)&&(flag);i++) { if(a%i==0) flag=0; } return flag; } int main() { clrscr(); int ch,res,a,b; do { cout<<"1.Check for divisibility\n"; cout<<"2.Check for prime\n"; cout<<"3.Exit\n"; cout<<"Enter your choice (1-3):"; cin>>ch; cout<<endl; switch(ch) { case 1 :cout<<"Enter the Numerator and Denominator\n"; cin>>a>>b; res=divide(a,b); cout<<((res)? "It is" : "It is not")<<endl; break; case 2 :cout<<"Enter the number\n"; cin>>a; res=0; res=divide(a); cout<<((res)? "It is" : "It is not")<<endl; break; case 3 :break; default:cout<<"Wrong choice!\n"; }; }while(ch>0&&ch<3); return 0; }
011995af42cdfbce89a1dca68db34a22803a4a17
0897560a7ebde50481f950c9a441e2fc3c34ba04
/10.0.15042.0/winrt/Windows.Security.EnterpriseData.h
158e7126682f079fe8550832dfe941d396ce3342
[ "LicenseRef-scancode-generic-cla", "MIT" ]
permissive
dngoins/cppwinrt
338f01171153cbca14a723217129ed36b6ce2c9d
0bb7a57392673f793ba99978738490100a9684ec
refs/heads/master
2021-01-19T19:14:59.993078
2017-03-01T22:14:18
2017-03-01T22:14:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
138,592
h
// C++ for the Windows Runtime v1.0.private // Copyright (c) 2017 Microsoft Corporation. All rights reserved. #pragma once #include "base.h" WINRT_WARNING_PUSH #include "internal/Windows.Storage.3.h" #include "internal/Windows.Foundation.3.h" #include "internal/Windows.Foundation.Collections.3.h" #include "internal/Windows.Storage.Streams.3.h" #include "internal/Windows.Networking.3.h" #include "internal/Windows.Security.EnterpriseData.3.h" #include "Windows.Foundation.h" WINRT_EXPORT namespace winrt { namespace impl { template <typename D> struct produce<D, Windows::Security::EnterpriseData::IBufferProtectUnprotectResult> : produce_base<D, Windows::Security::EnterpriseData::IBufferProtectUnprotectResult> { HRESULT __stdcall get_Buffer(impl::abi_arg_out<Windows::Storage::Streams::IBuffer> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Buffer()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_ProtectionInfo(impl::abi_arg_out<Windows::Security::EnterpriseData::IDataProtectionInfo> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().ProtectionInfo()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Security::EnterpriseData::IDataProtectionInfo> : produce_base<D, Windows::Security::EnterpriseData::IDataProtectionInfo> { HRESULT __stdcall get_Status(Windows::Security::EnterpriseData::DataProtectionStatus * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Status()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_Identity(impl::abi_arg_out<hstring> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Identity()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Security::EnterpriseData::IDataProtectionManagerStatics> : produce_base<D, Windows::Security::EnterpriseData::IDataProtectionManagerStatics> { HRESULT __stdcall abi_ProtectAsync(impl::abi_arg_in<Windows::Storage::Streams::IBuffer> data, impl::abi_arg_in<hstring> identity, impl::abi_arg_out<Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::BufferProtectUnprotectResult>> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().ProtectAsync(*reinterpret_cast<const Windows::Storage::Streams::IBuffer *>(&data), *reinterpret_cast<const hstring *>(&identity))); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_UnprotectAsync(impl::abi_arg_in<Windows::Storage::Streams::IBuffer> data, impl::abi_arg_out<Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::BufferProtectUnprotectResult>> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().UnprotectAsync(*reinterpret_cast<const Windows::Storage::Streams::IBuffer *>(&data))); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_ProtectStreamAsync(impl::abi_arg_in<Windows::Storage::Streams::IInputStream> unprotectedStream, impl::abi_arg_in<hstring> identity, impl::abi_arg_in<Windows::Storage::Streams::IOutputStream> protectedStream, impl::abi_arg_out<Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::DataProtectionInfo>> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().ProtectStreamAsync(*reinterpret_cast<const Windows::Storage::Streams::IInputStream *>(&unprotectedStream), *reinterpret_cast<const hstring *>(&identity), *reinterpret_cast<const Windows::Storage::Streams::IOutputStream *>(&protectedStream))); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_UnprotectStreamAsync(impl::abi_arg_in<Windows::Storage::Streams::IInputStream> protectedStream, impl::abi_arg_in<Windows::Storage::Streams::IOutputStream> unprotectedStream, impl::abi_arg_out<Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::DataProtectionInfo>> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().UnprotectStreamAsync(*reinterpret_cast<const Windows::Storage::Streams::IInputStream *>(&protectedStream), *reinterpret_cast<const Windows::Storage::Streams::IOutputStream *>(&unprotectedStream))); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_GetProtectionInfoAsync(impl::abi_arg_in<Windows::Storage::Streams::IBuffer> protectedData, impl::abi_arg_out<Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::DataProtectionInfo>> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().GetProtectionInfoAsync(*reinterpret_cast<const Windows::Storage::Streams::IBuffer *>(&protectedData))); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_GetStreamProtectionInfoAsync(impl::abi_arg_in<Windows::Storage::Streams::IInputStream> protectedStream, impl::abi_arg_out<Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::DataProtectionInfo>> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().GetStreamProtectionInfoAsync(*reinterpret_cast<const Windows::Storage::Streams::IInputStream *>(&protectedStream))); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Security::EnterpriseData::IFileProtectionInfo> : produce_base<D, Windows::Security::EnterpriseData::IFileProtectionInfo> { HRESULT __stdcall get_Status(Windows::Security::EnterpriseData::FileProtectionStatus * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Status()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_IsRoamable(bool * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().IsRoamable()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_Identity(impl::abi_arg_out<hstring> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Identity()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Security::EnterpriseData::IFileProtectionManagerStatics> : produce_base<D, Windows::Security::EnterpriseData::IFileProtectionManagerStatics> { HRESULT __stdcall abi_ProtectAsync(impl::abi_arg_in<Windows::Storage::IStorageItem> target, impl::abi_arg_in<hstring> identity, impl::abi_arg_out<Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::FileProtectionInfo>> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().ProtectAsync(*reinterpret_cast<const Windows::Storage::IStorageItem *>(&target), *reinterpret_cast<const hstring *>(&identity))); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_CopyProtectionAsync(impl::abi_arg_in<Windows::Storage::IStorageItem> source, impl::abi_arg_in<Windows::Storage::IStorageItem> target, impl::abi_arg_out<Windows::Foundation::IAsyncOperation<bool>> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().CopyProtectionAsync(*reinterpret_cast<const Windows::Storage::IStorageItem *>(&source), *reinterpret_cast<const Windows::Storage::IStorageItem *>(&target))); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_GetProtectionInfoAsync(impl::abi_arg_in<Windows::Storage::IStorageItem> source, impl::abi_arg_out<Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::FileProtectionInfo>> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().GetProtectionInfoAsync(*reinterpret_cast<const Windows::Storage::IStorageItem *>(&source))); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_SaveFileAsContainerAsync(impl::abi_arg_in<Windows::Storage::IStorageFile> protectedFile, impl::abi_arg_out<Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::ProtectedContainerExportResult>> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().SaveFileAsContainerAsync(*reinterpret_cast<const Windows::Storage::IStorageFile *>(&protectedFile))); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_LoadFileFromContainerAsync(impl::abi_arg_in<Windows::Storage::IStorageFile> containerFile, impl::abi_arg_out<Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::ProtectedContainerImportResult>> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().LoadFileFromContainerAsync(*reinterpret_cast<const Windows::Storage::IStorageFile *>(&containerFile))); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_LoadFileFromContainerWithTargetAsync(impl::abi_arg_in<Windows::Storage::IStorageFile> containerFile, impl::abi_arg_in<Windows::Storage::IStorageItem> target, impl::abi_arg_out<Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::ProtectedContainerImportResult>> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().LoadFileFromContainerAsync(*reinterpret_cast<const Windows::Storage::IStorageFile *>(&containerFile), *reinterpret_cast<const Windows::Storage::IStorageItem *>(&target))); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_CreateProtectedAndOpenAsync(impl::abi_arg_in<Windows::Storage::IStorageFolder> parentFolder, impl::abi_arg_in<hstring> desiredName, impl::abi_arg_in<hstring> identity, Windows::Storage::CreationCollisionOption collisionOption, impl::abi_arg_out<Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::ProtectedFileCreateResult>> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().CreateProtectedAndOpenAsync(*reinterpret_cast<const Windows::Storage::IStorageFolder *>(&parentFolder), *reinterpret_cast<const hstring *>(&desiredName), *reinterpret_cast<const hstring *>(&identity), collisionOption)); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Security::EnterpriseData::IFileProtectionManagerStatics2> : produce_base<D, Windows::Security::EnterpriseData::IFileProtectionManagerStatics2> { HRESULT __stdcall abi_IsContainerAsync(impl::abi_arg_in<Windows::Storage::IStorageFile> file, impl::abi_arg_out<Windows::Foundation::IAsyncOperation<bool>> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().IsContainerAsync(*reinterpret_cast<const Windows::Storage::IStorageFile *>(&file))); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_LoadFileFromContainerWithTargetAndNameCollisionOptionAsync(impl::abi_arg_in<Windows::Storage::IStorageFile> containerFile, impl::abi_arg_in<Windows::Storage::IStorageItem> target, Windows::Storage::NameCollisionOption collisionOption, impl::abi_arg_out<Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::ProtectedContainerImportResult>> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().LoadFileFromContainerAsync(*reinterpret_cast<const Windows::Storage::IStorageFile *>(&containerFile), *reinterpret_cast<const Windows::Storage::IStorageItem *>(&target), collisionOption)); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_SaveFileAsContainerWithSharingAsync(impl::abi_arg_in<Windows::Storage::IStorageFile> protectedFile, impl::abi_arg_in<Windows::Foundation::Collections::IIterable<hstring>> sharedWithIdentities, impl::abi_arg_out<Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::ProtectedContainerExportResult>> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().SaveFileAsContainerAsync(*reinterpret_cast<const Windows::Storage::IStorageFile *>(&protectedFile), *reinterpret_cast<const Windows::Foundation::Collections::IIterable<hstring> *>(&sharedWithIdentities))); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Security::EnterpriseData::IFileProtectionManagerStatics3> : produce_base<D, Windows::Security::EnterpriseData::IFileProtectionManagerStatics3> { HRESULT __stdcall abi_UnprotectAsync(impl::abi_arg_in<Windows::Storage::IStorageItem> target, impl::abi_arg_out<Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::FileProtectionInfo>> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().UnprotectAsync(*reinterpret_cast<const Windows::Storage::IStorageItem *>(&target))); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_UnprotectWithOptionsAsync(impl::abi_arg_in<Windows::Storage::IStorageItem> target, impl::abi_arg_in<Windows::Security::EnterpriseData::IFileUnprotectOptions> options, impl::abi_arg_out<Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::FileProtectionInfo>> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().UnprotectAsync(*reinterpret_cast<const Windows::Storage::IStorageItem *>(&target), *reinterpret_cast<const Windows::Security::EnterpriseData::FileUnprotectOptions *>(&options))); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Security::EnterpriseData::IFileRevocationManagerStatics> : produce_base<D, Windows::Security::EnterpriseData::IFileRevocationManagerStatics> { HRESULT __stdcall abi_ProtectAsync(impl::abi_arg_in<Windows::Storage::IStorageItem> storageItem, impl::abi_arg_in<hstring> enterpriseIdentity, impl::abi_arg_out<Windows::Foundation::IAsyncOperation<winrt::Windows::Security::EnterpriseData::FileProtectionStatus>> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().ProtectAsync(*reinterpret_cast<const Windows::Storage::IStorageItem *>(&storageItem), *reinterpret_cast<const hstring *>(&enterpriseIdentity))); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_CopyProtectionAsync(impl::abi_arg_in<Windows::Storage::IStorageItem> sourceStorageItem, impl::abi_arg_in<Windows::Storage::IStorageItem> targetStorageItem, impl::abi_arg_out<Windows::Foundation::IAsyncOperation<bool>> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().CopyProtectionAsync(*reinterpret_cast<const Windows::Storage::IStorageItem *>(&sourceStorageItem), *reinterpret_cast<const Windows::Storage::IStorageItem *>(&targetStorageItem))); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_Revoke(impl::abi_arg_in<hstring> enterpriseIdentity) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().Revoke(*reinterpret_cast<const hstring *>(&enterpriseIdentity)); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall abi_GetStatusAsync(impl::abi_arg_in<Windows::Storage::IStorageItem> storageItem, impl::abi_arg_out<Windows::Foundation::IAsyncOperation<winrt::Windows::Security::EnterpriseData::FileProtectionStatus>> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().GetStatusAsync(*reinterpret_cast<const Windows::Storage::IStorageItem *>(&storageItem))); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Security::EnterpriseData::IFileUnprotectOptions> : produce_base<D, Windows::Security::EnterpriseData::IFileUnprotectOptions> { HRESULT __stdcall put_Audit(bool value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().Audit(value); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_Audit(bool * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Audit()); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Security::EnterpriseData::IFileUnprotectOptionsFactory> : produce_base<D, Windows::Security::EnterpriseData::IFileUnprotectOptionsFactory> { HRESULT __stdcall abi_Create(bool audit, impl::abi_arg_out<Windows::Security::EnterpriseData::IFileUnprotectOptions> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().Create(audit)); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Security::EnterpriseData::IProtectedAccessResumedEventArgs> : produce_base<D, Windows::Security::EnterpriseData::IProtectedAccessResumedEventArgs> { HRESULT __stdcall get_Identities(impl::abi_arg_out<Windows::Foundation::Collections::IVectorView<hstring>> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Identities()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Security::EnterpriseData::IProtectedAccessSuspendingEventArgs> : produce_base<D, Windows::Security::EnterpriseData::IProtectedAccessSuspendingEventArgs> { HRESULT __stdcall get_Identities(impl::abi_arg_out<Windows::Foundation::Collections::IVectorView<hstring>> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Identities()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_Deadline(impl::abi_arg_out<Windows::Foundation::DateTime> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Deadline()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall abi_GetDeferral(impl::abi_arg_out<Windows::Foundation::IDeferral> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().GetDeferral()); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Security::EnterpriseData::IProtectedContainerExportResult> : produce_base<D, Windows::Security::EnterpriseData::IProtectedContainerExportResult> { HRESULT __stdcall get_Status(Windows::Security::EnterpriseData::ProtectedImportExportStatus * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Status()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_File(impl::abi_arg_out<Windows::Storage::IStorageFile> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().File()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Security::EnterpriseData::IProtectedContainerImportResult> : produce_base<D, Windows::Security::EnterpriseData::IProtectedContainerImportResult> { HRESULT __stdcall get_Status(Windows::Security::EnterpriseData::ProtectedImportExportStatus * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Status()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_File(impl::abi_arg_out<Windows::Storage::IStorageFile> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().File()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Security::EnterpriseData::IProtectedContentRevokedEventArgs> : produce_base<D, Windows::Security::EnterpriseData::IProtectedContentRevokedEventArgs> { HRESULT __stdcall get_Identities(impl::abi_arg_out<Windows::Foundation::Collections::IVectorView<hstring>> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Identities()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Security::EnterpriseData::IProtectedFileCreateResult> : produce_base<D, Windows::Security::EnterpriseData::IProtectedFileCreateResult> { HRESULT __stdcall get_File(impl::abi_arg_out<Windows::Storage::IStorageFile> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().File()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_Stream(impl::abi_arg_out<Windows::Storage::Streams::IRandomAccessStream> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Stream()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_ProtectionInfo(impl::abi_arg_out<Windows::Security::EnterpriseData::IFileProtectionInfo> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().ProtectionInfo()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Security::EnterpriseData::IProtectionPolicyAuditInfo> : produce_base<D, Windows::Security::EnterpriseData::IProtectionPolicyAuditInfo> { HRESULT __stdcall put_Action(Windows::Security::EnterpriseData::ProtectionPolicyAuditAction value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().Action(value); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_Action(Windows::Security::EnterpriseData::ProtectionPolicyAuditAction * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Action()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall put_DataDescription(impl::abi_arg_in<hstring> value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().DataDescription(*reinterpret_cast<const hstring *>(&value)); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_DataDescription(impl::abi_arg_out<hstring> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().DataDescription()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall put_SourceDescription(impl::abi_arg_in<hstring> value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().SourceDescription(*reinterpret_cast<const hstring *>(&value)); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_SourceDescription(impl::abi_arg_out<hstring> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().SourceDescription()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall put_TargetDescription(impl::abi_arg_in<hstring> value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().TargetDescription(*reinterpret_cast<const hstring *>(&value)); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_TargetDescription(impl::abi_arg_out<hstring> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().TargetDescription()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Security::EnterpriseData::IProtectionPolicyAuditInfoFactory> : produce_base<D, Windows::Security::EnterpriseData::IProtectionPolicyAuditInfoFactory> { HRESULT __stdcall abi_Create(Windows::Security::EnterpriseData::ProtectionPolicyAuditAction action, impl::abi_arg_in<hstring> dataDescription, impl::abi_arg_in<hstring> sourceDescription, impl::abi_arg_in<hstring> targetDescription, impl::abi_arg_out<Windows::Security::EnterpriseData::IProtectionPolicyAuditInfo> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().Create(action, *reinterpret_cast<const hstring *>(&dataDescription), *reinterpret_cast<const hstring *>(&sourceDescription), *reinterpret_cast<const hstring *>(&targetDescription))); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_CreateWithActionAndDataDescription(Windows::Security::EnterpriseData::ProtectionPolicyAuditAction action, impl::abi_arg_in<hstring> dataDescription, impl::abi_arg_out<Windows::Security::EnterpriseData::IProtectionPolicyAuditInfo> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().CreateWithActionAndDataDescription(action, *reinterpret_cast<const hstring *>(&dataDescription))); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Security::EnterpriseData::IProtectionPolicyManager> : produce_base<D, Windows::Security::EnterpriseData::IProtectionPolicyManager> { HRESULT __stdcall put_Identity(impl::abi_arg_in<hstring> value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().Identity(*reinterpret_cast<const hstring *>(&value)); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_Identity(impl::abi_arg_out<hstring> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Identity()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Security::EnterpriseData::IProtectionPolicyManager2> : produce_base<D, Windows::Security::EnterpriseData::IProtectionPolicyManager2> { HRESULT __stdcall put_ShowEnterpriseIndicator(bool value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().ShowEnterpriseIndicator(value); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_ShowEnterpriseIndicator(bool * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().ShowEnterpriseIndicator()); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Security::EnterpriseData::IProtectionPolicyManagerStatics> : produce_base<D, Windows::Security::EnterpriseData::IProtectionPolicyManagerStatics> { HRESULT __stdcall abi_IsIdentityManaged(impl::abi_arg_in<hstring> identity, bool * result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().IsIdentityManaged(*reinterpret_cast<const hstring *>(&identity))); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall abi_TryApplyProcessUIPolicy(impl::abi_arg_in<hstring> identity, bool * result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().TryApplyProcessUIPolicy(*reinterpret_cast<const hstring *>(&identity))); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall abi_ClearProcessUIPolicy() noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().ClearProcessUIPolicy(); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall abi_CreateCurrentThreadNetworkContext(impl::abi_arg_in<hstring> identity, impl::abi_arg_out<Windows::Security::EnterpriseData::IThreadNetworkContext> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().CreateCurrentThreadNetworkContext(*reinterpret_cast<const hstring *>(&identity))); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_GetPrimaryManagedIdentityForNetworkEndpointAsync(impl::abi_arg_in<Windows::Networking::IHostName> endpointHost, impl::abi_arg_out<Windows::Foundation::IAsyncOperation<hstring>> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().GetPrimaryManagedIdentityForNetworkEndpointAsync(*reinterpret_cast<const Windows::Networking::HostName *>(&endpointHost))); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_RevokeContent(impl::abi_arg_in<hstring> identity) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().RevokeContent(*reinterpret_cast<const hstring *>(&identity)); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall abi_GetForCurrentView(impl::abi_arg_out<Windows::Security::EnterpriseData::IProtectionPolicyManager> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().GetForCurrentView()); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } HRESULT __stdcall add_ProtectedAccessSuspending(impl::abi_arg_in<Windows::Foundation::EventHandler<Windows::Security::EnterpriseData::ProtectedAccessSuspendingEventArgs>> handler, event_token * token) noexcept override { try { typename D::abi_guard guard(this->shim()); *token = detach_abi(this->shim().ProtectedAccessSuspending(*reinterpret_cast<const Windows::Foundation::EventHandler<Windows::Security::EnterpriseData::ProtectedAccessSuspendingEventArgs> *>(&handler))); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall remove_ProtectedAccessSuspending(event_token token) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().ProtectedAccessSuspending(token); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall add_ProtectedAccessResumed(impl::abi_arg_in<Windows::Foundation::EventHandler<Windows::Security::EnterpriseData::ProtectedAccessResumedEventArgs>> handler, event_token * token) noexcept override { try { typename D::abi_guard guard(this->shim()); *token = detach_abi(this->shim().ProtectedAccessResumed(*reinterpret_cast<const Windows::Foundation::EventHandler<Windows::Security::EnterpriseData::ProtectedAccessResumedEventArgs> *>(&handler))); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall remove_ProtectedAccessResumed(event_token token) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().ProtectedAccessResumed(token); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall add_ProtectedContentRevoked(impl::abi_arg_in<Windows::Foundation::EventHandler<Windows::Security::EnterpriseData::ProtectedContentRevokedEventArgs>> handler, event_token * token) noexcept override { try { typename D::abi_guard guard(this->shim()); *token = detach_abi(this->shim().ProtectedContentRevoked(*reinterpret_cast<const Windows::Foundation::EventHandler<Windows::Security::EnterpriseData::ProtectedContentRevokedEventArgs> *>(&handler))); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall remove_ProtectedContentRevoked(event_token token) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().ProtectedContentRevoked(token); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall abi_CheckAccess(impl::abi_arg_in<hstring> sourceIdentity, impl::abi_arg_in<hstring> targetIdentity, Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult * result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().CheckAccess(*reinterpret_cast<const hstring *>(&sourceIdentity), *reinterpret_cast<const hstring *>(&targetIdentity))); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall abi_RequestAccessAsync(impl::abi_arg_in<hstring> sourceIdentity, impl::abi_arg_in<hstring> targetIdentity, impl::abi_arg_out<Windows::Foundation::IAsyncOperation<winrt::Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult>> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().RequestAccessAsync(*reinterpret_cast<const hstring *>(&sourceIdentity), *reinterpret_cast<const hstring *>(&targetIdentity))); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Security::EnterpriseData::IProtectionPolicyManagerStatics2> : produce_base<D, Windows::Security::EnterpriseData::IProtectionPolicyManagerStatics2> { HRESULT __stdcall abi_HasContentBeenRevokedSince(impl::abi_arg_in<hstring> identity, impl::abi_arg_in<Windows::Foundation::DateTime> since, bool * result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().HasContentBeenRevokedSince(*reinterpret_cast<const hstring *>(&identity), *reinterpret_cast<const Windows::Foundation::DateTime *>(&since))); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall abi_CheckAccessForApp(impl::abi_arg_in<hstring> sourceIdentity, impl::abi_arg_in<hstring> appPackageFamilyName, Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult * result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().CheckAccessForApp(*reinterpret_cast<const hstring *>(&sourceIdentity), *reinterpret_cast<const hstring *>(&appPackageFamilyName))); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall abi_RequestAccessForAppAsync(impl::abi_arg_in<hstring> sourceIdentity, impl::abi_arg_in<hstring> appPackageFamilyName, impl::abi_arg_out<Windows::Foundation::IAsyncOperation<winrt::Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult>> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().RequestAccessForAppAsync(*reinterpret_cast<const hstring *>(&sourceIdentity), *reinterpret_cast<const hstring *>(&appPackageFamilyName))); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_GetEnforcementLevel(impl::abi_arg_in<hstring> identity, Windows::Security::EnterpriseData::EnforcementLevel * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().GetEnforcementLevel(*reinterpret_cast<const hstring *>(&identity))); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall abi_IsUserDecryptionAllowed(impl::abi_arg_in<hstring> identity, bool * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().IsUserDecryptionAllowed(*reinterpret_cast<const hstring *>(&identity))); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall abi_IsProtectionUnderLockRequired(impl::abi_arg_in<hstring> identity, bool * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().IsProtectionUnderLockRequired(*reinterpret_cast<const hstring *>(&identity))); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall add_PolicyChanged(impl::abi_arg_in<Windows::Foundation::EventHandler<Windows::Foundation::IInspectable>> handler, event_token * token) noexcept override { try { typename D::abi_guard guard(this->shim()); *token = detach_abi(this->shim().PolicyChanged(*reinterpret_cast<const Windows::Foundation::EventHandler<Windows::Foundation::IInspectable> *>(&handler))); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall remove_PolicyChanged(event_token token) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().PolicyChanged(token); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_IsProtectionEnabled(bool * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().IsProtectionEnabled()); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Security::EnterpriseData::IProtectionPolicyManagerStatics3> : produce_base<D, Windows::Security::EnterpriseData::IProtectionPolicyManagerStatics3> { HRESULT __stdcall abi_RequestAccessWithAuditingInfoAsync(impl::abi_arg_in<hstring> sourceIdentity, impl::abi_arg_in<hstring> targetIdentity, impl::abi_arg_in<Windows::Security::EnterpriseData::IProtectionPolicyAuditInfo> auditInfo, impl::abi_arg_out<Windows::Foundation::IAsyncOperation<winrt::Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult>> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().RequestAccessAsync(*reinterpret_cast<const hstring *>(&sourceIdentity), *reinterpret_cast<const hstring *>(&targetIdentity), *reinterpret_cast<const Windows::Security::EnterpriseData::ProtectionPolicyAuditInfo *>(&auditInfo))); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_RequestAccessWithMessageAsync(impl::abi_arg_in<hstring> sourceIdentity, impl::abi_arg_in<hstring> targetIdentity, impl::abi_arg_in<Windows::Security::EnterpriseData::IProtectionPolicyAuditInfo> auditInfo, impl::abi_arg_in<hstring> messageFromApp, impl::abi_arg_out<Windows::Foundation::IAsyncOperation<winrt::Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult>> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().RequestAccessAsync(*reinterpret_cast<const hstring *>(&sourceIdentity), *reinterpret_cast<const hstring *>(&targetIdentity), *reinterpret_cast<const Windows::Security::EnterpriseData::ProtectionPolicyAuditInfo *>(&auditInfo), *reinterpret_cast<const hstring *>(&messageFromApp))); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_RequestAccessForAppWithAuditingInfoAsync(impl::abi_arg_in<hstring> sourceIdentity, impl::abi_arg_in<hstring> appPackageFamilyName, impl::abi_arg_in<Windows::Security::EnterpriseData::IProtectionPolicyAuditInfo> auditInfo, impl::abi_arg_out<Windows::Foundation::IAsyncOperation<winrt::Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult>> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().RequestAccessForAppAsync(*reinterpret_cast<const hstring *>(&sourceIdentity), *reinterpret_cast<const hstring *>(&appPackageFamilyName), *reinterpret_cast<const Windows::Security::EnterpriseData::ProtectionPolicyAuditInfo *>(&auditInfo))); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_RequestAccessForAppWithMessageAsync(impl::abi_arg_in<hstring> sourceIdentity, impl::abi_arg_in<hstring> appPackageFamilyName, impl::abi_arg_in<Windows::Security::EnterpriseData::IProtectionPolicyAuditInfo> auditInfo, impl::abi_arg_in<hstring> messageFromApp, impl::abi_arg_out<Windows::Foundation::IAsyncOperation<winrt::Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult>> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().RequestAccessForAppAsync(*reinterpret_cast<const hstring *>(&sourceIdentity), *reinterpret_cast<const hstring *>(&appPackageFamilyName), *reinterpret_cast<const Windows::Security::EnterpriseData::ProtectionPolicyAuditInfo *>(&auditInfo), *reinterpret_cast<const hstring *>(&messageFromApp))); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_LogAuditEvent(impl::abi_arg_in<hstring> sourceIdentity, impl::abi_arg_in<hstring> targetIdentity, impl::abi_arg_in<Windows::Security::EnterpriseData::IProtectionPolicyAuditInfo> auditInfo) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().LogAuditEvent(*reinterpret_cast<const hstring *>(&sourceIdentity), *reinterpret_cast<const hstring *>(&targetIdentity), *reinterpret_cast<const Windows::Security::EnterpriseData::ProtectionPolicyAuditInfo *>(&auditInfo)); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Security::EnterpriseData::IProtectionPolicyManagerStatics4> : produce_base<D, Windows::Security::EnterpriseData::IProtectionPolicyManagerStatics4> { HRESULT __stdcall abi_IsRoamableProtectionEnabled(impl::abi_arg_in<hstring> identity, bool * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().IsRoamableProtectionEnabled(*reinterpret_cast<const hstring *>(&identity))); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall abi_RequestAccessWithBehaviorAsync(impl::abi_arg_in<hstring> sourceIdentity, impl::abi_arg_in<hstring> targetIdentity, impl::abi_arg_in<Windows::Security::EnterpriseData::IProtectionPolicyAuditInfo> auditInfo, impl::abi_arg_in<hstring> messageFromApp, Windows::Security::EnterpriseData::ProtectionPolicyRequestAccessBehavior behavior, impl::abi_arg_out<Windows::Foundation::IAsyncOperation<winrt::Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult>> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().RequestAccessAsync(*reinterpret_cast<const hstring *>(&sourceIdentity), *reinterpret_cast<const hstring *>(&targetIdentity), *reinterpret_cast<const Windows::Security::EnterpriseData::ProtectionPolicyAuditInfo *>(&auditInfo), *reinterpret_cast<const hstring *>(&messageFromApp), behavior)); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_RequestAccessForAppWithBehaviorAsync(impl::abi_arg_in<hstring> sourceIdentity, impl::abi_arg_in<hstring> appPackageFamilyName, impl::abi_arg_in<Windows::Security::EnterpriseData::IProtectionPolicyAuditInfo> auditInfo, impl::abi_arg_in<hstring> messageFromApp, Windows::Security::EnterpriseData::ProtectionPolicyRequestAccessBehavior behavior, impl::abi_arg_out<Windows::Foundation::IAsyncOperation<winrt::Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult>> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().RequestAccessForAppAsync(*reinterpret_cast<const hstring *>(&sourceIdentity), *reinterpret_cast<const hstring *>(&appPackageFamilyName), *reinterpret_cast<const Windows::Security::EnterpriseData::ProtectionPolicyAuditInfo *>(&auditInfo), *reinterpret_cast<const hstring *>(&messageFromApp), behavior)); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_RequestAccessToFilesForAppAsync(impl::abi_arg_in<Windows::Foundation::Collections::IIterable<Windows::Storage::IStorageItem>> sourceItemList, impl::abi_arg_in<hstring> appPackageFamilyName, impl::abi_arg_in<Windows::Security::EnterpriseData::IProtectionPolicyAuditInfo> auditInfo, impl::abi_arg_out<Windows::Foundation::IAsyncOperation<winrt::Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult>> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().RequestAccessToFilesForAppAsync(*reinterpret_cast<const Windows::Foundation::Collections::IIterable<Windows::Storage::IStorageItem> *>(&sourceItemList), *reinterpret_cast<const hstring *>(&appPackageFamilyName), *reinterpret_cast<const Windows::Security::EnterpriseData::ProtectionPolicyAuditInfo *>(&auditInfo))); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_RequestAccessToFilesForAppWithMessageAndBehaviorAsync(impl::abi_arg_in<Windows::Foundation::Collections::IIterable<Windows::Storage::IStorageItem>> sourceItemList, impl::abi_arg_in<hstring> appPackageFamilyName, impl::abi_arg_in<Windows::Security::EnterpriseData::IProtectionPolicyAuditInfo> auditInfo, impl::abi_arg_in<hstring> messageFromApp, Windows::Security::EnterpriseData::ProtectionPolicyRequestAccessBehavior behavior, impl::abi_arg_out<Windows::Foundation::IAsyncOperation<winrt::Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult>> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().RequestAccessToFilesForAppAsync(*reinterpret_cast<const Windows::Foundation::Collections::IIterable<Windows::Storage::IStorageItem> *>(&sourceItemList), *reinterpret_cast<const hstring *>(&appPackageFamilyName), *reinterpret_cast<const Windows::Security::EnterpriseData::ProtectionPolicyAuditInfo *>(&auditInfo), *reinterpret_cast<const hstring *>(&messageFromApp), behavior)); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_RequestAccessToFilesForProcessAsync(impl::abi_arg_in<Windows::Foundation::Collections::IIterable<Windows::Storage::IStorageItem>> sourceItemList, uint32_t processId, impl::abi_arg_in<Windows::Security::EnterpriseData::IProtectionPolicyAuditInfo> auditInfo, impl::abi_arg_out<Windows::Foundation::IAsyncOperation<winrt::Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult>> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().RequestAccessToFilesForProcessAsync(*reinterpret_cast<const Windows::Foundation::Collections::IIterable<Windows::Storage::IStorageItem> *>(&sourceItemList), processId, *reinterpret_cast<const Windows::Security::EnterpriseData::ProtectionPolicyAuditInfo *>(&auditInfo))); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_RequestAccessToFilesForProcessWithMessageAndBehaviorAsync(impl::abi_arg_in<Windows::Foundation::Collections::IIterable<Windows::Storage::IStorageItem>> sourceItemList, uint32_t processId, impl::abi_arg_in<Windows::Security::EnterpriseData::IProtectionPolicyAuditInfo> auditInfo, impl::abi_arg_in<hstring> messageFromApp, Windows::Security::EnterpriseData::ProtectionPolicyRequestAccessBehavior behavior, impl::abi_arg_out<Windows::Foundation::IAsyncOperation<winrt::Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult>> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().RequestAccessToFilesForProcessAsync(*reinterpret_cast<const Windows::Foundation::Collections::IIterable<Windows::Storage::IStorageItem> *>(&sourceItemList), processId, *reinterpret_cast<const Windows::Security::EnterpriseData::ProtectionPolicyAuditInfo *>(&auditInfo), *reinterpret_cast<const hstring *>(&messageFromApp), behavior)); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_IsFileProtectionRequiredAsync(impl::abi_arg_in<Windows::Storage::IStorageItem> target, impl::abi_arg_in<hstring> identity, impl::abi_arg_out<Windows::Foundation::IAsyncOperation<bool>> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().IsFileProtectionRequiredAsync(*reinterpret_cast<const Windows::Storage::IStorageItem *>(&target), *reinterpret_cast<const hstring *>(&identity))); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_IsFileProtectionRequiredForNewFileAsync(impl::abi_arg_in<Windows::Storage::IStorageFolder> parentFolder, impl::abi_arg_in<hstring> identity, impl::abi_arg_in<hstring> desiredName, impl::abi_arg_out<Windows::Foundation::IAsyncOperation<bool>> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().IsFileProtectionRequiredForNewFileAsync(*reinterpret_cast<const Windows::Storage::IStorageFolder *>(&parentFolder), *reinterpret_cast<const hstring *>(&identity), *reinterpret_cast<const hstring *>(&desiredName))); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_PrimaryManagedIdentity(impl::abi_arg_out<hstring> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().PrimaryManagedIdentity()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_GetPrimaryManagedIdentityForIdentity(impl::abi_arg_in<hstring> identity, impl::abi_arg_out<hstring> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().GetPrimaryManagedIdentityForIdentity(*reinterpret_cast<const hstring *>(&identity))); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Security::EnterpriseData::IThreadNetworkContext> : produce_base<D, Windows::Security::EnterpriseData::IThreadNetworkContext> {}; } namespace Windows::Security::EnterpriseData { template <typename D> Windows::Foundation::IAsyncOperation<winrt::Windows::Security::EnterpriseData::FileProtectionStatus> impl_IFileRevocationManagerStatics<D>::ProtectAsync(const Windows::Storage::IStorageItem & storageItem, hstring_view enterpriseIdentity) const { Windows::Foundation::IAsyncOperation<winrt::Windows::Security::EnterpriseData::FileProtectionStatus> result; check_hresult(WINRT_SHIM(IFileRevocationManagerStatics)->abi_ProtectAsync(get_abi(storageItem), get_abi(enterpriseIdentity), put_abi(result))); return result; } template <typename D> Windows::Foundation::IAsyncOperation<bool> impl_IFileRevocationManagerStatics<D>::CopyProtectionAsync(const Windows::Storage::IStorageItem & sourceStorageItem, const Windows::Storage::IStorageItem & targetStorageItem) const { Windows::Foundation::IAsyncOperation<bool> result; check_hresult(WINRT_SHIM(IFileRevocationManagerStatics)->abi_CopyProtectionAsync(get_abi(sourceStorageItem), get_abi(targetStorageItem), put_abi(result))); return result; } template <typename D> void impl_IFileRevocationManagerStatics<D>::Revoke(hstring_view enterpriseIdentity) const { check_hresult(WINRT_SHIM(IFileRevocationManagerStatics)->abi_Revoke(get_abi(enterpriseIdentity))); } template <typename D> Windows::Foundation::IAsyncOperation<winrt::Windows::Security::EnterpriseData::FileProtectionStatus> impl_IFileRevocationManagerStatics<D>::GetStatusAsync(const Windows::Storage::IStorageItem & storageItem) const { Windows::Foundation::IAsyncOperation<winrt::Windows::Security::EnterpriseData::FileProtectionStatus> result; check_hresult(WINRT_SHIM(IFileRevocationManagerStatics)->abi_GetStatusAsync(get_abi(storageItem), put_abi(result))); return result; } template <typename D> Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::FileProtectionInfo> impl_IFileProtectionManagerStatics<D>::ProtectAsync(const Windows::Storage::IStorageItem & target, hstring_view identity) const { Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::FileProtectionInfo> result; check_hresult(WINRT_SHIM(IFileProtectionManagerStatics)->abi_ProtectAsync(get_abi(target), get_abi(identity), put_abi(result))); return result; } template <typename D> Windows::Foundation::IAsyncOperation<bool> impl_IFileProtectionManagerStatics<D>::CopyProtectionAsync(const Windows::Storage::IStorageItem & source, const Windows::Storage::IStorageItem & target) const { Windows::Foundation::IAsyncOperation<bool> result; check_hresult(WINRT_SHIM(IFileProtectionManagerStatics)->abi_CopyProtectionAsync(get_abi(source), get_abi(target), put_abi(result))); return result; } template <typename D> Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::FileProtectionInfo> impl_IFileProtectionManagerStatics<D>::GetProtectionInfoAsync(const Windows::Storage::IStorageItem & source) const { Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::FileProtectionInfo> result; check_hresult(WINRT_SHIM(IFileProtectionManagerStatics)->abi_GetProtectionInfoAsync(get_abi(source), put_abi(result))); return result; } template <typename D> Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::ProtectedContainerExportResult> impl_IFileProtectionManagerStatics<D>::SaveFileAsContainerAsync(const Windows::Storage::IStorageFile & protectedFile) const { Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::ProtectedContainerExportResult> result; check_hresult(WINRT_SHIM(IFileProtectionManagerStatics)->abi_SaveFileAsContainerAsync(get_abi(protectedFile), put_abi(result))); return result; } template <typename D> Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::ProtectedContainerImportResult> impl_IFileProtectionManagerStatics<D>::LoadFileFromContainerAsync(const Windows::Storage::IStorageFile & containerFile) const { Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::ProtectedContainerImportResult> result; check_hresult(WINRT_SHIM(IFileProtectionManagerStatics)->abi_LoadFileFromContainerAsync(get_abi(containerFile), put_abi(result))); return result; } template <typename D> Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::ProtectedContainerImportResult> impl_IFileProtectionManagerStatics<D>::LoadFileFromContainerAsync(const Windows::Storage::IStorageFile & containerFile, const Windows::Storage::IStorageItem & target) const { Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::ProtectedContainerImportResult> result; check_hresult(WINRT_SHIM(IFileProtectionManagerStatics)->abi_LoadFileFromContainerWithTargetAsync(get_abi(containerFile), get_abi(target), put_abi(result))); return result; } template <typename D> Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::ProtectedFileCreateResult> impl_IFileProtectionManagerStatics<D>::CreateProtectedAndOpenAsync(const Windows::Storage::IStorageFolder & parentFolder, hstring_view desiredName, hstring_view identity, Windows::Storage::CreationCollisionOption collisionOption) const { Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::ProtectedFileCreateResult> result; check_hresult(WINRT_SHIM(IFileProtectionManagerStatics)->abi_CreateProtectedAndOpenAsync(get_abi(parentFolder), get_abi(desiredName), get_abi(identity), collisionOption, put_abi(result))); return result; } template <typename D> Windows::Foundation::IAsyncOperation<bool> impl_IFileProtectionManagerStatics2<D>::IsContainerAsync(const Windows::Storage::IStorageFile & file) const { Windows::Foundation::IAsyncOperation<bool> result; check_hresult(WINRT_SHIM(IFileProtectionManagerStatics2)->abi_IsContainerAsync(get_abi(file), put_abi(result))); return result; } template <typename D> Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::ProtectedContainerImportResult> impl_IFileProtectionManagerStatics2<D>::LoadFileFromContainerAsync(const Windows::Storage::IStorageFile & containerFile, const Windows::Storage::IStorageItem & target, Windows::Storage::NameCollisionOption collisionOption) const { Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::ProtectedContainerImportResult> result; check_hresult(WINRT_SHIM(IFileProtectionManagerStatics2)->abi_LoadFileFromContainerWithTargetAndNameCollisionOptionAsync(get_abi(containerFile), get_abi(target), collisionOption, put_abi(result))); return result; } template <typename D> Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::ProtectedContainerExportResult> impl_IFileProtectionManagerStatics2<D>::SaveFileAsContainerAsync(const Windows::Storage::IStorageFile & protectedFile, iterable<hstring> sharedWithIdentities) const { Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::ProtectedContainerExportResult> result; check_hresult(WINRT_SHIM(IFileProtectionManagerStatics2)->abi_SaveFileAsContainerWithSharingAsync(get_abi(protectedFile), get_abi(sharedWithIdentities), put_abi(result))); return result; } template <typename D> Windows::Security::EnterpriseData::FileUnprotectOptions impl_IFileUnprotectOptionsFactory<D>::Create(bool audit) const { Windows::Security::EnterpriseData::FileUnprotectOptions result { nullptr }; check_hresult(WINRT_SHIM(IFileUnprotectOptionsFactory)->abi_Create(audit, put_abi(result))); return result; } template <typename D> void impl_IFileUnprotectOptions<D>::Audit(bool value) const { check_hresult(WINRT_SHIM(IFileUnprotectOptions)->put_Audit(value)); } template <typename D> bool impl_IFileUnprotectOptions<D>::Audit() const { bool value {}; check_hresult(WINRT_SHIM(IFileUnprotectOptions)->get_Audit(&value)); return value; } template <typename D> Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::FileProtectionInfo> impl_IFileProtectionManagerStatics3<D>::UnprotectAsync(const Windows::Storage::IStorageItem & target) const { Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::FileProtectionInfo> result; check_hresult(WINRT_SHIM(IFileProtectionManagerStatics3)->abi_UnprotectAsync(get_abi(target), put_abi(result))); return result; } template <typename D> Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::FileProtectionInfo> impl_IFileProtectionManagerStatics3<D>::UnprotectAsync(const Windows::Storage::IStorageItem & target, const Windows::Security::EnterpriseData::FileUnprotectOptions & options) const { Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::FileProtectionInfo> result; check_hresult(WINRT_SHIM(IFileProtectionManagerStatics3)->abi_UnprotectWithOptionsAsync(get_abi(target), get_abi(options), put_abi(result))); return result; } template <typename D> Windows::Storage::StorageFile impl_IProtectedFileCreateResult<D>::File() const { Windows::Storage::StorageFile value { nullptr }; check_hresult(WINRT_SHIM(IProtectedFileCreateResult)->get_File(put_abi(value))); return value; } template <typename D> Windows::Storage::Streams::IRandomAccessStream impl_IProtectedFileCreateResult<D>::Stream() const { Windows::Storage::Streams::IRandomAccessStream value; check_hresult(WINRT_SHIM(IProtectedFileCreateResult)->get_Stream(put_abi(value))); return value; } template <typename D> Windows::Security::EnterpriseData::FileProtectionInfo impl_IProtectedFileCreateResult<D>::ProtectionInfo() const { Windows::Security::EnterpriseData::FileProtectionInfo value { nullptr }; check_hresult(WINRT_SHIM(IProtectedFileCreateResult)->get_ProtectionInfo(put_abi(value))); return value; } template <typename D> Windows::Security::EnterpriseData::FileProtectionStatus impl_IFileProtectionInfo<D>::Status() const { Windows::Security::EnterpriseData::FileProtectionStatus value {}; check_hresult(WINRT_SHIM(IFileProtectionInfo)->get_Status(&value)); return value; } template <typename D> bool impl_IFileProtectionInfo<D>::IsRoamable() const { bool value {}; check_hresult(WINRT_SHIM(IFileProtectionInfo)->get_IsRoamable(&value)); return value; } template <typename D> hstring impl_IFileProtectionInfo<D>::Identity() const { hstring value; check_hresult(WINRT_SHIM(IFileProtectionInfo)->get_Identity(put_abi(value))); return value; } template <typename D> Windows::Security::EnterpriseData::ProtectedImportExportStatus impl_IProtectedContainerExportResult<D>::Status() const { Windows::Security::EnterpriseData::ProtectedImportExportStatus value {}; check_hresult(WINRT_SHIM(IProtectedContainerExportResult)->get_Status(&value)); return value; } template <typename D> Windows::Storage::StorageFile impl_IProtectedContainerExportResult<D>::File() const { Windows::Storage::StorageFile value { nullptr }; check_hresult(WINRT_SHIM(IProtectedContainerExportResult)->get_File(put_abi(value))); return value; } template <typename D> Windows::Security::EnterpriseData::ProtectedImportExportStatus impl_IProtectedContainerImportResult<D>::Status() const { Windows::Security::EnterpriseData::ProtectedImportExportStatus value {}; check_hresult(WINRT_SHIM(IProtectedContainerImportResult)->get_Status(&value)); return value; } template <typename D> Windows::Storage::StorageFile impl_IProtectedContainerImportResult<D>::File() const { Windows::Storage::StorageFile value { nullptr }; check_hresult(WINRT_SHIM(IProtectedContainerImportResult)->get_File(put_abi(value))); return value; } template <typename D> Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::BufferProtectUnprotectResult> impl_IDataProtectionManagerStatics<D>::ProtectAsync(const Windows::Storage::Streams::IBuffer & data, hstring_view identity) const { Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::BufferProtectUnprotectResult> result; check_hresult(WINRT_SHIM(IDataProtectionManagerStatics)->abi_ProtectAsync(get_abi(data), get_abi(identity), put_abi(result))); return result; } template <typename D> Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::BufferProtectUnprotectResult> impl_IDataProtectionManagerStatics<D>::UnprotectAsync(const Windows::Storage::Streams::IBuffer & data) const { Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::BufferProtectUnprotectResult> result; check_hresult(WINRT_SHIM(IDataProtectionManagerStatics)->abi_UnprotectAsync(get_abi(data), put_abi(result))); return result; } template <typename D> Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::DataProtectionInfo> impl_IDataProtectionManagerStatics<D>::ProtectStreamAsync(const Windows::Storage::Streams::IInputStream & unprotectedStream, hstring_view identity, const Windows::Storage::Streams::IOutputStream & protectedStream) const { Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::DataProtectionInfo> result; check_hresult(WINRT_SHIM(IDataProtectionManagerStatics)->abi_ProtectStreamAsync(get_abi(unprotectedStream), get_abi(identity), get_abi(protectedStream), put_abi(result))); return result; } template <typename D> Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::DataProtectionInfo> impl_IDataProtectionManagerStatics<D>::UnprotectStreamAsync(const Windows::Storage::Streams::IInputStream & protectedStream, const Windows::Storage::Streams::IOutputStream & unprotectedStream) const { Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::DataProtectionInfo> result; check_hresult(WINRT_SHIM(IDataProtectionManagerStatics)->abi_UnprotectStreamAsync(get_abi(protectedStream), get_abi(unprotectedStream), put_abi(result))); return result; } template <typename D> Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::DataProtectionInfo> impl_IDataProtectionManagerStatics<D>::GetProtectionInfoAsync(const Windows::Storage::Streams::IBuffer & protectedData) const { Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::DataProtectionInfo> result; check_hresult(WINRT_SHIM(IDataProtectionManagerStatics)->abi_GetProtectionInfoAsync(get_abi(protectedData), put_abi(result))); return result; } template <typename D> Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::DataProtectionInfo> impl_IDataProtectionManagerStatics<D>::GetStreamProtectionInfoAsync(const Windows::Storage::Streams::IInputStream & protectedStream) const { Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::DataProtectionInfo> result; check_hresult(WINRT_SHIM(IDataProtectionManagerStatics)->abi_GetStreamProtectionInfoAsync(get_abi(protectedStream), put_abi(result))); return result; } template <typename D> Windows::Security::EnterpriseData::DataProtectionStatus impl_IDataProtectionInfo<D>::Status() const { Windows::Security::EnterpriseData::DataProtectionStatus value {}; check_hresult(WINRT_SHIM(IDataProtectionInfo)->get_Status(&value)); return value; } template <typename D> hstring impl_IDataProtectionInfo<D>::Identity() const { hstring value; check_hresult(WINRT_SHIM(IDataProtectionInfo)->get_Identity(put_abi(value))); return value; } template <typename D> Windows::Storage::Streams::IBuffer impl_IBufferProtectUnprotectResult<D>::Buffer() const { Windows::Storage::Streams::IBuffer value; check_hresult(WINRT_SHIM(IBufferProtectUnprotectResult)->get_Buffer(put_abi(value))); return value; } template <typename D> Windows::Security::EnterpriseData::DataProtectionInfo impl_IBufferProtectUnprotectResult<D>::ProtectionInfo() const { Windows::Security::EnterpriseData::DataProtectionInfo value { nullptr }; check_hresult(WINRT_SHIM(IBufferProtectUnprotectResult)->get_ProtectionInfo(put_abi(value))); return value; } template <typename D> Windows::Security::EnterpriseData::ProtectionPolicyAuditInfo impl_IProtectionPolicyAuditInfoFactory<D>::Create(Windows::Security::EnterpriseData::ProtectionPolicyAuditAction action, hstring_view dataDescription, hstring_view sourceDescription, hstring_view targetDescription) const { Windows::Security::EnterpriseData::ProtectionPolicyAuditInfo result { nullptr }; check_hresult(WINRT_SHIM(IProtectionPolicyAuditInfoFactory)->abi_Create(action, get_abi(dataDescription), get_abi(sourceDescription), get_abi(targetDescription), put_abi(result))); return result; } template <typename D> Windows::Security::EnterpriseData::ProtectionPolicyAuditInfo impl_IProtectionPolicyAuditInfoFactory<D>::CreateWithActionAndDataDescription(Windows::Security::EnterpriseData::ProtectionPolicyAuditAction action, hstring_view dataDescription) const { Windows::Security::EnterpriseData::ProtectionPolicyAuditInfo result { nullptr }; check_hresult(WINRT_SHIM(IProtectionPolicyAuditInfoFactory)->abi_CreateWithActionAndDataDescription(action, get_abi(dataDescription), put_abi(result))); return result; } template <typename D> void impl_IProtectionPolicyAuditInfo<D>::Action(Windows::Security::EnterpriseData::ProtectionPolicyAuditAction value) const { check_hresult(WINRT_SHIM(IProtectionPolicyAuditInfo)->put_Action(value)); } template <typename D> Windows::Security::EnterpriseData::ProtectionPolicyAuditAction impl_IProtectionPolicyAuditInfo<D>::Action() const { Windows::Security::EnterpriseData::ProtectionPolicyAuditAction value {}; check_hresult(WINRT_SHIM(IProtectionPolicyAuditInfo)->get_Action(&value)); return value; } template <typename D> void impl_IProtectionPolicyAuditInfo<D>::DataDescription(hstring_view value) const { check_hresult(WINRT_SHIM(IProtectionPolicyAuditInfo)->put_DataDescription(get_abi(value))); } template <typename D> hstring impl_IProtectionPolicyAuditInfo<D>::DataDescription() const { hstring value; check_hresult(WINRT_SHIM(IProtectionPolicyAuditInfo)->get_DataDescription(put_abi(value))); return value; } template <typename D> void impl_IProtectionPolicyAuditInfo<D>::SourceDescription(hstring_view value) const { check_hresult(WINRT_SHIM(IProtectionPolicyAuditInfo)->put_SourceDescription(get_abi(value))); } template <typename D> hstring impl_IProtectionPolicyAuditInfo<D>::SourceDescription() const { hstring value; check_hresult(WINRT_SHIM(IProtectionPolicyAuditInfo)->get_SourceDescription(put_abi(value))); return value; } template <typename D> void impl_IProtectionPolicyAuditInfo<D>::TargetDescription(hstring_view value) const { check_hresult(WINRT_SHIM(IProtectionPolicyAuditInfo)->put_TargetDescription(get_abi(value))); } template <typename D> hstring impl_IProtectionPolicyAuditInfo<D>::TargetDescription() const { hstring value; check_hresult(WINRT_SHIM(IProtectionPolicyAuditInfo)->get_TargetDescription(put_abi(value))); return value; } template <typename D> void impl_IProtectionPolicyManager<D>::Identity(hstring_view value) const { check_hresult(WINRT_SHIM(IProtectionPolicyManager)->put_Identity(get_abi(value))); } template <typename D> hstring impl_IProtectionPolicyManager<D>::Identity() const { hstring value; check_hresult(WINRT_SHIM(IProtectionPolicyManager)->get_Identity(put_abi(value))); return value; } template <typename D> void impl_IProtectionPolicyManager2<D>::ShowEnterpriseIndicator(bool value) const { check_hresult(WINRT_SHIM(IProtectionPolicyManager2)->put_ShowEnterpriseIndicator(value)); } template <typename D> bool impl_IProtectionPolicyManager2<D>::ShowEnterpriseIndicator() const { bool value {}; check_hresult(WINRT_SHIM(IProtectionPolicyManager2)->get_ShowEnterpriseIndicator(&value)); return value; } template <typename D> bool impl_IProtectionPolicyManagerStatics<D>::IsIdentityManaged(hstring_view identity) const { bool result {}; check_hresult(WINRT_SHIM(IProtectionPolicyManagerStatics)->abi_IsIdentityManaged(get_abi(identity), &result)); return result; } template <typename D> bool impl_IProtectionPolicyManagerStatics<D>::TryApplyProcessUIPolicy(hstring_view identity) const { bool result {}; check_hresult(WINRT_SHIM(IProtectionPolicyManagerStatics)->abi_TryApplyProcessUIPolicy(get_abi(identity), &result)); return result; } template <typename D> void impl_IProtectionPolicyManagerStatics<D>::ClearProcessUIPolicy() const { check_hresult(WINRT_SHIM(IProtectionPolicyManagerStatics)->abi_ClearProcessUIPolicy()); } template <typename D> Windows::Security::EnterpriseData::ThreadNetworkContext impl_IProtectionPolicyManagerStatics<D>::CreateCurrentThreadNetworkContext(hstring_view identity) const { Windows::Security::EnterpriseData::ThreadNetworkContext result { nullptr }; check_hresult(WINRT_SHIM(IProtectionPolicyManagerStatics)->abi_CreateCurrentThreadNetworkContext(get_abi(identity), put_abi(result))); return result; } template <typename D> Windows::Foundation::IAsyncOperation<hstring> impl_IProtectionPolicyManagerStatics<D>::GetPrimaryManagedIdentityForNetworkEndpointAsync(const Windows::Networking::HostName & endpointHost) const { Windows::Foundation::IAsyncOperation<hstring> result; check_hresult(WINRT_SHIM(IProtectionPolicyManagerStatics)->abi_GetPrimaryManagedIdentityForNetworkEndpointAsync(get_abi(endpointHost), put_abi(result))); return result; } template <typename D> void impl_IProtectionPolicyManagerStatics<D>::RevokeContent(hstring_view identity) const { check_hresult(WINRT_SHIM(IProtectionPolicyManagerStatics)->abi_RevokeContent(get_abi(identity))); } template <typename D> Windows::Security::EnterpriseData::ProtectionPolicyManager impl_IProtectionPolicyManagerStatics<D>::GetForCurrentView() const { Windows::Security::EnterpriseData::ProtectionPolicyManager result { nullptr }; check_hresult(WINRT_SHIM(IProtectionPolicyManagerStatics)->abi_GetForCurrentView(put_abi(result))); return result; } template <typename D> event_token impl_IProtectionPolicyManagerStatics<D>::ProtectedAccessSuspending(const Windows::Foundation::EventHandler<Windows::Security::EnterpriseData::ProtectedAccessSuspendingEventArgs> & handler) const { event_token token {}; check_hresult(WINRT_SHIM(IProtectionPolicyManagerStatics)->add_ProtectedAccessSuspending(get_abi(handler), &token)); return token; } template <typename D> event_revoker<IProtectionPolicyManagerStatics> impl_IProtectionPolicyManagerStatics<D>::ProtectedAccessSuspending(auto_revoke_t, const Windows::Foundation::EventHandler<Windows::Security::EnterpriseData::ProtectedAccessSuspendingEventArgs> & handler) const { return impl::make_event_revoker<D, IProtectionPolicyManagerStatics>(this, &ABI::Windows::Security::EnterpriseData::IProtectionPolicyManagerStatics::remove_ProtectedAccessSuspending, ProtectedAccessSuspending(handler)); } template <typename D> void impl_IProtectionPolicyManagerStatics<D>::ProtectedAccessSuspending(event_token token) const { check_hresult(WINRT_SHIM(IProtectionPolicyManagerStatics)->remove_ProtectedAccessSuspending(token)); } template <typename D> event_token impl_IProtectionPolicyManagerStatics<D>::ProtectedAccessResumed(const Windows::Foundation::EventHandler<Windows::Security::EnterpriseData::ProtectedAccessResumedEventArgs> & handler) const { event_token token {}; check_hresult(WINRT_SHIM(IProtectionPolicyManagerStatics)->add_ProtectedAccessResumed(get_abi(handler), &token)); return token; } template <typename D> event_revoker<IProtectionPolicyManagerStatics> impl_IProtectionPolicyManagerStatics<D>::ProtectedAccessResumed(auto_revoke_t, const Windows::Foundation::EventHandler<Windows::Security::EnterpriseData::ProtectedAccessResumedEventArgs> & handler) const { return impl::make_event_revoker<D, IProtectionPolicyManagerStatics>(this, &ABI::Windows::Security::EnterpriseData::IProtectionPolicyManagerStatics::remove_ProtectedAccessResumed, ProtectedAccessResumed(handler)); } template <typename D> void impl_IProtectionPolicyManagerStatics<D>::ProtectedAccessResumed(event_token token) const { check_hresult(WINRT_SHIM(IProtectionPolicyManagerStatics)->remove_ProtectedAccessResumed(token)); } template <typename D> event_token impl_IProtectionPolicyManagerStatics<D>::ProtectedContentRevoked(const Windows::Foundation::EventHandler<Windows::Security::EnterpriseData::ProtectedContentRevokedEventArgs> & handler) const { event_token token {}; check_hresult(WINRT_SHIM(IProtectionPolicyManagerStatics)->add_ProtectedContentRevoked(get_abi(handler), &token)); return token; } template <typename D> event_revoker<IProtectionPolicyManagerStatics> impl_IProtectionPolicyManagerStatics<D>::ProtectedContentRevoked(auto_revoke_t, const Windows::Foundation::EventHandler<Windows::Security::EnterpriseData::ProtectedContentRevokedEventArgs> & handler) const { return impl::make_event_revoker<D, IProtectionPolicyManagerStatics>(this, &ABI::Windows::Security::EnterpriseData::IProtectionPolicyManagerStatics::remove_ProtectedContentRevoked, ProtectedContentRevoked(handler)); } template <typename D> void impl_IProtectionPolicyManagerStatics<D>::ProtectedContentRevoked(event_token token) const { check_hresult(WINRT_SHIM(IProtectionPolicyManagerStatics)->remove_ProtectedContentRevoked(token)); } template <typename D> Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult impl_IProtectionPolicyManagerStatics<D>::CheckAccess(hstring_view sourceIdentity, hstring_view targetIdentity) const { Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult result {}; check_hresult(WINRT_SHIM(IProtectionPolicyManagerStatics)->abi_CheckAccess(get_abi(sourceIdentity), get_abi(targetIdentity), &result)); return result; } template <typename D> Windows::Foundation::IAsyncOperation<winrt::Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult> impl_IProtectionPolicyManagerStatics<D>::RequestAccessAsync(hstring_view sourceIdentity, hstring_view targetIdentity) const { Windows::Foundation::IAsyncOperation<winrt::Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult> result; check_hresult(WINRT_SHIM(IProtectionPolicyManagerStatics)->abi_RequestAccessAsync(get_abi(sourceIdentity), get_abi(targetIdentity), put_abi(result))); return result; } template <typename D> bool impl_IProtectionPolicyManagerStatics2<D>::HasContentBeenRevokedSince(hstring_view identity, const Windows::Foundation::DateTime & since) const { bool result {}; check_hresult(WINRT_SHIM(IProtectionPolicyManagerStatics2)->abi_HasContentBeenRevokedSince(get_abi(identity), get_abi(since), &result)); return result; } template <typename D> Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult impl_IProtectionPolicyManagerStatics2<D>::CheckAccessForApp(hstring_view sourceIdentity, hstring_view appPackageFamilyName) const { Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult result {}; check_hresult(WINRT_SHIM(IProtectionPolicyManagerStatics2)->abi_CheckAccessForApp(get_abi(sourceIdentity), get_abi(appPackageFamilyName), &result)); return result; } template <typename D> Windows::Foundation::IAsyncOperation<winrt::Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult> impl_IProtectionPolicyManagerStatics2<D>::RequestAccessForAppAsync(hstring_view sourceIdentity, hstring_view appPackageFamilyName) const { Windows::Foundation::IAsyncOperation<winrt::Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult> result; check_hresult(WINRT_SHIM(IProtectionPolicyManagerStatics2)->abi_RequestAccessForAppAsync(get_abi(sourceIdentity), get_abi(appPackageFamilyName), put_abi(result))); return result; } template <typename D> Windows::Security::EnterpriseData::EnforcementLevel impl_IProtectionPolicyManagerStatics2<D>::GetEnforcementLevel(hstring_view identity) const { Windows::Security::EnterpriseData::EnforcementLevel value {}; check_hresult(WINRT_SHIM(IProtectionPolicyManagerStatics2)->abi_GetEnforcementLevel(get_abi(identity), &value)); return value; } template <typename D> bool impl_IProtectionPolicyManagerStatics2<D>::IsUserDecryptionAllowed(hstring_view identity) const { bool value {}; check_hresult(WINRT_SHIM(IProtectionPolicyManagerStatics2)->abi_IsUserDecryptionAllowed(get_abi(identity), &value)); return value; } template <typename D> bool impl_IProtectionPolicyManagerStatics2<D>::IsProtectionUnderLockRequired(hstring_view identity) const { bool value {}; check_hresult(WINRT_SHIM(IProtectionPolicyManagerStatics2)->abi_IsProtectionUnderLockRequired(get_abi(identity), &value)); return value; } template <typename D> event_token impl_IProtectionPolicyManagerStatics2<D>::PolicyChanged(const Windows::Foundation::EventHandler<Windows::Foundation::IInspectable> & handler) const { event_token token {}; check_hresult(WINRT_SHIM(IProtectionPolicyManagerStatics2)->add_PolicyChanged(get_abi(handler), &token)); return token; } template <typename D> event_revoker<IProtectionPolicyManagerStatics2> impl_IProtectionPolicyManagerStatics2<D>::PolicyChanged(auto_revoke_t, const Windows::Foundation::EventHandler<Windows::Foundation::IInspectable> & handler) const { return impl::make_event_revoker<D, IProtectionPolicyManagerStatics2>(this, &ABI::Windows::Security::EnterpriseData::IProtectionPolicyManagerStatics2::remove_PolicyChanged, PolicyChanged(handler)); } template <typename D> void impl_IProtectionPolicyManagerStatics2<D>::PolicyChanged(event_token token) const { check_hresult(WINRT_SHIM(IProtectionPolicyManagerStatics2)->remove_PolicyChanged(token)); } template <typename D> bool impl_IProtectionPolicyManagerStatics2<D>::IsProtectionEnabled() const { bool value {}; check_hresult(WINRT_SHIM(IProtectionPolicyManagerStatics2)->get_IsProtectionEnabled(&value)); return value; } template <typename D> Windows::Foundation::IAsyncOperation<winrt::Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult> impl_IProtectionPolicyManagerStatics3<D>::RequestAccessAsync(hstring_view sourceIdentity, hstring_view targetIdentity, const Windows::Security::EnterpriseData::ProtectionPolicyAuditInfo & auditInfo) const { Windows::Foundation::IAsyncOperation<winrt::Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult> result; check_hresult(WINRT_SHIM(IProtectionPolicyManagerStatics3)->abi_RequestAccessWithAuditingInfoAsync(get_abi(sourceIdentity), get_abi(targetIdentity), get_abi(auditInfo), put_abi(result))); return result; } template <typename D> Windows::Foundation::IAsyncOperation<winrt::Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult> impl_IProtectionPolicyManagerStatics3<D>::RequestAccessAsync(hstring_view sourceIdentity, hstring_view targetIdentity, const Windows::Security::EnterpriseData::ProtectionPolicyAuditInfo & auditInfo, hstring_view messageFromApp) const { Windows::Foundation::IAsyncOperation<winrt::Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult> result; check_hresult(WINRT_SHIM(IProtectionPolicyManagerStatics3)->abi_RequestAccessWithMessageAsync(get_abi(sourceIdentity), get_abi(targetIdentity), get_abi(auditInfo), get_abi(messageFromApp), put_abi(result))); return result; } template <typename D> Windows::Foundation::IAsyncOperation<winrt::Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult> impl_IProtectionPolicyManagerStatics3<D>::RequestAccessForAppAsync(hstring_view sourceIdentity, hstring_view appPackageFamilyName, const Windows::Security::EnterpriseData::ProtectionPolicyAuditInfo & auditInfo) const { Windows::Foundation::IAsyncOperation<winrt::Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult> result; check_hresult(WINRT_SHIM(IProtectionPolicyManagerStatics3)->abi_RequestAccessForAppWithAuditingInfoAsync(get_abi(sourceIdentity), get_abi(appPackageFamilyName), get_abi(auditInfo), put_abi(result))); return result; } template <typename D> Windows::Foundation::IAsyncOperation<winrt::Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult> impl_IProtectionPolicyManagerStatics3<D>::RequestAccessForAppAsync(hstring_view sourceIdentity, hstring_view appPackageFamilyName, const Windows::Security::EnterpriseData::ProtectionPolicyAuditInfo & auditInfo, hstring_view messageFromApp) const { Windows::Foundation::IAsyncOperation<winrt::Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult> result; check_hresult(WINRT_SHIM(IProtectionPolicyManagerStatics3)->abi_RequestAccessForAppWithMessageAsync(get_abi(sourceIdentity), get_abi(appPackageFamilyName), get_abi(auditInfo), get_abi(messageFromApp), put_abi(result))); return result; } template <typename D> void impl_IProtectionPolicyManagerStatics3<D>::LogAuditEvent(hstring_view sourceIdentity, hstring_view targetIdentity, const Windows::Security::EnterpriseData::ProtectionPolicyAuditInfo & auditInfo) const { check_hresult(WINRT_SHIM(IProtectionPolicyManagerStatics3)->abi_LogAuditEvent(get_abi(sourceIdentity), get_abi(targetIdentity), get_abi(auditInfo))); } template <typename D> bool impl_IProtectionPolicyManagerStatics4<D>::IsRoamableProtectionEnabled(hstring_view identity) const { bool value {}; check_hresult(WINRT_SHIM(IProtectionPolicyManagerStatics4)->abi_IsRoamableProtectionEnabled(get_abi(identity), &value)); return value; } template <typename D> Windows::Foundation::IAsyncOperation<winrt::Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult> impl_IProtectionPolicyManagerStatics4<D>::RequestAccessAsync(hstring_view sourceIdentity, hstring_view targetIdentity, const Windows::Security::EnterpriseData::ProtectionPolicyAuditInfo & auditInfo, hstring_view messageFromApp, Windows::Security::EnterpriseData::ProtectionPolicyRequestAccessBehavior behavior) const { Windows::Foundation::IAsyncOperation<winrt::Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult> result; check_hresult(WINRT_SHIM(IProtectionPolicyManagerStatics4)->abi_RequestAccessWithBehaviorAsync(get_abi(sourceIdentity), get_abi(targetIdentity), get_abi(auditInfo), get_abi(messageFromApp), behavior, put_abi(result))); return result; } template <typename D> Windows::Foundation::IAsyncOperation<winrt::Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult> impl_IProtectionPolicyManagerStatics4<D>::RequestAccessForAppAsync(hstring_view sourceIdentity, hstring_view appPackageFamilyName, const Windows::Security::EnterpriseData::ProtectionPolicyAuditInfo & auditInfo, hstring_view messageFromApp, Windows::Security::EnterpriseData::ProtectionPolicyRequestAccessBehavior behavior) const { Windows::Foundation::IAsyncOperation<winrt::Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult> result; check_hresult(WINRT_SHIM(IProtectionPolicyManagerStatics4)->abi_RequestAccessForAppWithBehaviorAsync(get_abi(sourceIdentity), get_abi(appPackageFamilyName), get_abi(auditInfo), get_abi(messageFromApp), behavior, put_abi(result))); return result; } template <typename D> Windows::Foundation::IAsyncOperation<winrt::Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult> impl_IProtectionPolicyManagerStatics4<D>::RequestAccessToFilesForAppAsync(iterable<Windows::Storage::IStorageItem> sourceItemList, hstring_view appPackageFamilyName, const Windows::Security::EnterpriseData::ProtectionPolicyAuditInfo & auditInfo) const { Windows::Foundation::IAsyncOperation<winrt::Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult> result; check_hresult(WINRT_SHIM(IProtectionPolicyManagerStatics4)->abi_RequestAccessToFilesForAppAsync(get_abi(sourceItemList), get_abi(appPackageFamilyName), get_abi(auditInfo), put_abi(result))); return result; } template <typename D> Windows::Foundation::IAsyncOperation<winrt::Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult> impl_IProtectionPolicyManagerStatics4<D>::RequestAccessToFilesForAppAsync(iterable<Windows::Storage::IStorageItem> sourceItemList, hstring_view appPackageFamilyName, const Windows::Security::EnterpriseData::ProtectionPolicyAuditInfo & auditInfo, hstring_view messageFromApp, Windows::Security::EnterpriseData::ProtectionPolicyRequestAccessBehavior behavior) const { Windows::Foundation::IAsyncOperation<winrt::Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult> result; check_hresult(WINRT_SHIM(IProtectionPolicyManagerStatics4)->abi_RequestAccessToFilesForAppWithMessageAndBehaviorAsync(get_abi(sourceItemList), get_abi(appPackageFamilyName), get_abi(auditInfo), get_abi(messageFromApp), behavior, put_abi(result))); return result; } template <typename D> Windows::Foundation::IAsyncOperation<winrt::Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult> impl_IProtectionPolicyManagerStatics4<D>::RequestAccessToFilesForProcessAsync(iterable<Windows::Storage::IStorageItem> sourceItemList, uint32_t processId, const Windows::Security::EnterpriseData::ProtectionPolicyAuditInfo & auditInfo) const { Windows::Foundation::IAsyncOperation<winrt::Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult> result; check_hresult(WINRT_SHIM(IProtectionPolicyManagerStatics4)->abi_RequestAccessToFilesForProcessAsync(get_abi(sourceItemList), processId, get_abi(auditInfo), put_abi(result))); return result; } template <typename D> Windows::Foundation::IAsyncOperation<winrt::Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult> impl_IProtectionPolicyManagerStatics4<D>::RequestAccessToFilesForProcessAsync(iterable<Windows::Storage::IStorageItem> sourceItemList, uint32_t processId, const Windows::Security::EnterpriseData::ProtectionPolicyAuditInfo & auditInfo, hstring_view messageFromApp, Windows::Security::EnterpriseData::ProtectionPolicyRequestAccessBehavior behavior) const { Windows::Foundation::IAsyncOperation<winrt::Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult> result; check_hresult(WINRT_SHIM(IProtectionPolicyManagerStatics4)->abi_RequestAccessToFilesForProcessWithMessageAndBehaviorAsync(get_abi(sourceItemList), processId, get_abi(auditInfo), get_abi(messageFromApp), behavior, put_abi(result))); return result; } template <typename D> Windows::Foundation::IAsyncOperation<bool> impl_IProtectionPolicyManagerStatics4<D>::IsFileProtectionRequiredAsync(const Windows::Storage::IStorageItem & target, hstring_view identity) const { Windows::Foundation::IAsyncOperation<bool> result; check_hresult(WINRT_SHIM(IProtectionPolicyManagerStatics4)->abi_IsFileProtectionRequiredAsync(get_abi(target), get_abi(identity), put_abi(result))); return result; } template <typename D> Windows::Foundation::IAsyncOperation<bool> impl_IProtectionPolicyManagerStatics4<D>::IsFileProtectionRequiredForNewFileAsync(const Windows::Storage::IStorageFolder & parentFolder, hstring_view identity, hstring_view desiredName) const { Windows::Foundation::IAsyncOperation<bool> result; check_hresult(WINRT_SHIM(IProtectionPolicyManagerStatics4)->abi_IsFileProtectionRequiredForNewFileAsync(get_abi(parentFolder), get_abi(identity), get_abi(desiredName), put_abi(result))); return result; } template <typename D> hstring impl_IProtectionPolicyManagerStatics4<D>::PrimaryManagedIdentity() const { hstring value; check_hresult(WINRT_SHIM(IProtectionPolicyManagerStatics4)->get_PrimaryManagedIdentity(put_abi(value))); return value; } template <typename D> hstring impl_IProtectionPolicyManagerStatics4<D>::GetPrimaryManagedIdentityForIdentity(hstring_view identity) const { hstring value; check_hresult(WINRT_SHIM(IProtectionPolicyManagerStatics4)->abi_GetPrimaryManagedIdentityForIdentity(get_abi(identity), put_abi(value))); return value; } template <typename D> Windows::Foundation::Collections::IVectorView<hstring> impl_IProtectedAccessSuspendingEventArgs<D>::Identities() const { Windows::Foundation::Collections::IVectorView<hstring> value; check_hresult(WINRT_SHIM(IProtectedAccessSuspendingEventArgs)->get_Identities(put_abi(value))); return value; } template <typename D> Windows::Foundation::DateTime impl_IProtectedAccessSuspendingEventArgs<D>::Deadline() const { Windows::Foundation::DateTime value {}; check_hresult(WINRT_SHIM(IProtectedAccessSuspendingEventArgs)->get_Deadline(put_abi(value))); return value; } template <typename D> Windows::Foundation::Deferral impl_IProtectedAccessSuspendingEventArgs<D>::GetDeferral() const { Windows::Foundation::Deferral result { nullptr }; check_hresult(WINRT_SHIM(IProtectedAccessSuspendingEventArgs)->abi_GetDeferral(put_abi(result))); return result; } template <typename D> Windows::Foundation::Collections::IVectorView<hstring> impl_IProtectedAccessResumedEventArgs<D>::Identities() const { Windows::Foundation::Collections::IVectorView<hstring> value; check_hresult(WINRT_SHIM(IProtectedAccessResumedEventArgs)->get_Identities(put_abi(value))); return value; } template <typename D> Windows::Foundation::Collections::IVectorView<hstring> impl_IProtectedContentRevokedEventArgs<D>::Identities() const { Windows::Foundation::Collections::IVectorView<hstring> value; check_hresult(WINRT_SHIM(IProtectedContentRevokedEventArgs)->get_Identities(put_abi(value))); return value; } inline Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::BufferProtectUnprotectResult> DataProtectionManager::ProtectAsync(const Windows::Storage::Streams::IBuffer & data, hstring_view identity) { return get_activation_factory<DataProtectionManager, IDataProtectionManagerStatics>().ProtectAsync(data, identity); } inline Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::BufferProtectUnprotectResult> DataProtectionManager::UnprotectAsync(const Windows::Storage::Streams::IBuffer & data) { return get_activation_factory<DataProtectionManager, IDataProtectionManagerStatics>().UnprotectAsync(data); } inline Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::DataProtectionInfo> DataProtectionManager::ProtectStreamAsync(const Windows::Storage::Streams::IInputStream & unprotectedStream, hstring_view identity, const Windows::Storage::Streams::IOutputStream & protectedStream) { return get_activation_factory<DataProtectionManager, IDataProtectionManagerStatics>().ProtectStreamAsync(unprotectedStream, identity, protectedStream); } inline Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::DataProtectionInfo> DataProtectionManager::UnprotectStreamAsync(const Windows::Storage::Streams::IInputStream & protectedStream, const Windows::Storage::Streams::IOutputStream & unprotectedStream) { return get_activation_factory<DataProtectionManager, IDataProtectionManagerStatics>().UnprotectStreamAsync(protectedStream, unprotectedStream); } inline Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::DataProtectionInfo> DataProtectionManager::GetProtectionInfoAsync(const Windows::Storage::Streams::IBuffer & protectedData) { return get_activation_factory<DataProtectionManager, IDataProtectionManagerStatics>().GetProtectionInfoAsync(protectedData); } inline Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::DataProtectionInfo> DataProtectionManager::GetStreamProtectionInfoAsync(const Windows::Storage::Streams::IInputStream & protectedStream) { return get_activation_factory<DataProtectionManager, IDataProtectionManagerStatics>().GetStreamProtectionInfoAsync(protectedStream); } inline Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::FileProtectionInfo> FileProtectionManager::ProtectAsync(const Windows::Storage::IStorageItem & target, hstring_view identity) { return get_activation_factory<FileProtectionManager, IFileProtectionManagerStatics>().ProtectAsync(target, identity); } inline Windows::Foundation::IAsyncOperation<bool> FileProtectionManager::CopyProtectionAsync(const Windows::Storage::IStorageItem & source, const Windows::Storage::IStorageItem & target) { return get_activation_factory<FileProtectionManager, IFileProtectionManagerStatics>().CopyProtectionAsync(source, target); } inline Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::FileProtectionInfo> FileProtectionManager::GetProtectionInfoAsync(const Windows::Storage::IStorageItem & source) { return get_activation_factory<FileProtectionManager, IFileProtectionManagerStatics>().GetProtectionInfoAsync(source); } inline Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::ProtectedContainerExportResult> FileProtectionManager::SaveFileAsContainerAsync(const Windows::Storage::IStorageFile & protectedFile) { return get_activation_factory<FileProtectionManager, IFileProtectionManagerStatics>().SaveFileAsContainerAsync(protectedFile); } inline Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::ProtectedContainerImportResult> FileProtectionManager::LoadFileFromContainerAsync(const Windows::Storage::IStorageFile & containerFile) { return get_activation_factory<FileProtectionManager, IFileProtectionManagerStatics>().LoadFileFromContainerAsync(containerFile); } inline Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::ProtectedContainerImportResult> FileProtectionManager::LoadFileFromContainerAsync(const Windows::Storage::IStorageFile & containerFile, const Windows::Storage::IStorageItem & target) { return get_activation_factory<FileProtectionManager, IFileProtectionManagerStatics>().LoadFileFromContainerAsync(containerFile, target); } inline Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::ProtectedFileCreateResult> FileProtectionManager::CreateProtectedAndOpenAsync(const Windows::Storage::IStorageFolder & parentFolder, hstring_view desiredName, hstring_view identity, Windows::Storage::CreationCollisionOption collisionOption) { return get_activation_factory<FileProtectionManager, IFileProtectionManagerStatics>().CreateProtectedAndOpenAsync(parentFolder, desiredName, identity, collisionOption); } inline Windows::Foundation::IAsyncOperation<bool> FileProtectionManager::IsContainerAsync(const Windows::Storage::IStorageFile & file) { return get_activation_factory<FileProtectionManager, IFileProtectionManagerStatics2>().IsContainerAsync(file); } inline Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::ProtectedContainerImportResult> FileProtectionManager::LoadFileFromContainerAsync(const Windows::Storage::IStorageFile & containerFile, const Windows::Storage::IStorageItem & target, Windows::Storage::NameCollisionOption collisionOption) { return get_activation_factory<FileProtectionManager, IFileProtectionManagerStatics2>().LoadFileFromContainerAsync(containerFile, target, collisionOption); } inline Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::ProtectedContainerExportResult> FileProtectionManager::SaveFileAsContainerAsync(const Windows::Storage::IStorageFile & protectedFile, iterable<hstring> sharedWithIdentities) { return get_activation_factory<FileProtectionManager, IFileProtectionManagerStatics2>().SaveFileAsContainerAsync(protectedFile, sharedWithIdentities); } inline Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::FileProtectionInfo> FileProtectionManager::UnprotectAsync(const Windows::Storage::IStorageItem & target) { return get_activation_factory<FileProtectionManager, IFileProtectionManagerStatics3>().UnprotectAsync(target); } inline Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::FileProtectionInfo> FileProtectionManager::UnprotectAsync(const Windows::Storage::IStorageItem & target, const Windows::Security::EnterpriseData::FileUnprotectOptions & options) { return get_activation_factory<FileProtectionManager, IFileProtectionManagerStatics3>().UnprotectAsync(target, options); } inline Windows::Foundation::IAsyncOperation<winrt::Windows::Security::EnterpriseData::FileProtectionStatus> FileRevocationManager::ProtectAsync(const Windows::Storage::IStorageItem & storageItem, hstring_view enterpriseIdentity) { return get_activation_factory<FileRevocationManager, IFileRevocationManagerStatics>().ProtectAsync(storageItem, enterpriseIdentity); } inline Windows::Foundation::IAsyncOperation<bool> FileRevocationManager::CopyProtectionAsync(const Windows::Storage::IStorageItem & sourceStorageItem, const Windows::Storage::IStorageItem & targetStorageItem) { return get_activation_factory<FileRevocationManager, IFileRevocationManagerStatics>().CopyProtectionAsync(sourceStorageItem, targetStorageItem); } inline void FileRevocationManager::Revoke(hstring_view enterpriseIdentity) { get_activation_factory<FileRevocationManager, IFileRevocationManagerStatics>().Revoke(enterpriseIdentity); } inline Windows::Foundation::IAsyncOperation<winrt::Windows::Security::EnterpriseData::FileProtectionStatus> FileRevocationManager::GetStatusAsync(const Windows::Storage::IStorageItem & storageItem) { return get_activation_factory<FileRevocationManager, IFileRevocationManagerStatics>().GetStatusAsync(storageItem); } inline FileUnprotectOptions::FileUnprotectOptions(bool audit) : FileUnprotectOptions(get_activation_factory<FileUnprotectOptions, IFileUnprotectOptionsFactory>().Create(audit)) {} inline ProtectionPolicyAuditInfo::ProtectionPolicyAuditInfo(Windows::Security::EnterpriseData::ProtectionPolicyAuditAction action, hstring_view dataDescription, hstring_view sourceDescription, hstring_view targetDescription) : ProtectionPolicyAuditInfo(get_activation_factory<ProtectionPolicyAuditInfo, IProtectionPolicyAuditInfoFactory>().Create(action, dataDescription, sourceDescription, targetDescription)) {} inline ProtectionPolicyAuditInfo::ProtectionPolicyAuditInfo(Windows::Security::EnterpriseData::ProtectionPolicyAuditAction action, hstring_view dataDescription) : ProtectionPolicyAuditInfo(get_activation_factory<ProtectionPolicyAuditInfo, IProtectionPolicyAuditInfoFactory>().CreateWithActionAndDataDescription(action, dataDescription)) {} inline bool ProtectionPolicyManager::IsIdentityManaged(hstring_view identity) { return get_activation_factory<ProtectionPolicyManager, IProtectionPolicyManagerStatics>().IsIdentityManaged(identity); } inline bool ProtectionPolicyManager::TryApplyProcessUIPolicy(hstring_view identity) { return get_activation_factory<ProtectionPolicyManager, IProtectionPolicyManagerStatics>().TryApplyProcessUIPolicy(identity); } inline void ProtectionPolicyManager::ClearProcessUIPolicy() { get_activation_factory<ProtectionPolicyManager, IProtectionPolicyManagerStatics>().ClearProcessUIPolicy(); } inline Windows::Security::EnterpriseData::ThreadNetworkContext ProtectionPolicyManager::CreateCurrentThreadNetworkContext(hstring_view identity) { return get_activation_factory<ProtectionPolicyManager, IProtectionPolicyManagerStatics>().CreateCurrentThreadNetworkContext(identity); } inline Windows::Foundation::IAsyncOperation<hstring> ProtectionPolicyManager::GetPrimaryManagedIdentityForNetworkEndpointAsync(const Windows::Networking::HostName & endpointHost) { return get_activation_factory<ProtectionPolicyManager, IProtectionPolicyManagerStatics>().GetPrimaryManagedIdentityForNetworkEndpointAsync(endpointHost); } inline void ProtectionPolicyManager::RevokeContent(hstring_view identity) { get_activation_factory<ProtectionPolicyManager, IProtectionPolicyManagerStatics>().RevokeContent(identity); } inline Windows::Security::EnterpriseData::ProtectionPolicyManager ProtectionPolicyManager::GetForCurrentView() { return get_activation_factory<ProtectionPolicyManager, IProtectionPolicyManagerStatics>().GetForCurrentView(); } inline event_token ProtectionPolicyManager::ProtectedAccessSuspending(const Windows::Foundation::EventHandler<Windows::Security::EnterpriseData::ProtectedAccessSuspendingEventArgs> & handler) { return get_activation_factory<ProtectionPolicyManager, IProtectionPolicyManagerStatics>().ProtectedAccessSuspending(handler); } inline factory_event_revoker<IProtectionPolicyManagerStatics> ProtectionPolicyManager::ProtectedAccessSuspending(auto_revoke_t, const Windows::Foundation::EventHandler<Windows::Security::EnterpriseData::ProtectedAccessSuspendingEventArgs> & handler) { auto factory = get_activation_factory<ProtectionPolicyManager, IProtectionPolicyManagerStatics>(); return { factory, &ABI::Windows::Security::EnterpriseData::IProtectionPolicyManagerStatics::remove_ProtectedAccessSuspending, factory.ProtectedAccessSuspending(handler) }; } inline void ProtectionPolicyManager::ProtectedAccessSuspending(event_token token) { get_activation_factory<ProtectionPolicyManager, IProtectionPolicyManagerStatics>().ProtectedAccessSuspending(token); } inline event_token ProtectionPolicyManager::ProtectedAccessResumed(const Windows::Foundation::EventHandler<Windows::Security::EnterpriseData::ProtectedAccessResumedEventArgs> & handler) { return get_activation_factory<ProtectionPolicyManager, IProtectionPolicyManagerStatics>().ProtectedAccessResumed(handler); } inline factory_event_revoker<IProtectionPolicyManagerStatics> ProtectionPolicyManager::ProtectedAccessResumed(auto_revoke_t, const Windows::Foundation::EventHandler<Windows::Security::EnterpriseData::ProtectedAccessResumedEventArgs> & handler) { auto factory = get_activation_factory<ProtectionPolicyManager, IProtectionPolicyManagerStatics>(); return { factory, &ABI::Windows::Security::EnterpriseData::IProtectionPolicyManagerStatics::remove_ProtectedAccessResumed, factory.ProtectedAccessResumed(handler) }; } inline void ProtectionPolicyManager::ProtectedAccessResumed(event_token token) { get_activation_factory<ProtectionPolicyManager, IProtectionPolicyManagerStatics>().ProtectedAccessResumed(token); } inline event_token ProtectionPolicyManager::ProtectedContentRevoked(const Windows::Foundation::EventHandler<Windows::Security::EnterpriseData::ProtectedContentRevokedEventArgs> & handler) { return get_activation_factory<ProtectionPolicyManager, IProtectionPolicyManagerStatics>().ProtectedContentRevoked(handler); } inline factory_event_revoker<IProtectionPolicyManagerStatics> ProtectionPolicyManager::ProtectedContentRevoked(auto_revoke_t, const Windows::Foundation::EventHandler<Windows::Security::EnterpriseData::ProtectedContentRevokedEventArgs> & handler) { auto factory = get_activation_factory<ProtectionPolicyManager, IProtectionPolicyManagerStatics>(); return { factory, &ABI::Windows::Security::EnterpriseData::IProtectionPolicyManagerStatics::remove_ProtectedContentRevoked, factory.ProtectedContentRevoked(handler) }; } inline void ProtectionPolicyManager::ProtectedContentRevoked(event_token token) { get_activation_factory<ProtectionPolicyManager, IProtectionPolicyManagerStatics>().ProtectedContentRevoked(token); } inline Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult ProtectionPolicyManager::CheckAccess(hstring_view sourceIdentity, hstring_view targetIdentity) { return get_activation_factory<ProtectionPolicyManager, IProtectionPolicyManagerStatics>().CheckAccess(sourceIdentity, targetIdentity); } inline Windows::Foundation::IAsyncOperation<winrt::Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult> ProtectionPolicyManager::RequestAccessAsync(hstring_view sourceIdentity, hstring_view targetIdentity) { return get_activation_factory<ProtectionPolicyManager, IProtectionPolicyManagerStatics>().RequestAccessAsync(sourceIdentity, targetIdentity); } inline bool ProtectionPolicyManager::HasContentBeenRevokedSince(hstring_view identity, const Windows::Foundation::DateTime & since) { return get_activation_factory<ProtectionPolicyManager, IProtectionPolicyManagerStatics2>().HasContentBeenRevokedSince(identity, since); } inline Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult ProtectionPolicyManager::CheckAccessForApp(hstring_view sourceIdentity, hstring_view appPackageFamilyName) { return get_activation_factory<ProtectionPolicyManager, IProtectionPolicyManagerStatics2>().CheckAccessForApp(sourceIdentity, appPackageFamilyName); } inline Windows::Foundation::IAsyncOperation<winrt::Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult> ProtectionPolicyManager::RequestAccessForAppAsync(hstring_view sourceIdentity, hstring_view appPackageFamilyName) { return get_activation_factory<ProtectionPolicyManager, IProtectionPolicyManagerStatics2>().RequestAccessForAppAsync(sourceIdentity, appPackageFamilyName); } inline Windows::Security::EnterpriseData::EnforcementLevel ProtectionPolicyManager::GetEnforcementLevel(hstring_view identity) { return get_activation_factory<ProtectionPolicyManager, IProtectionPolicyManagerStatics2>().GetEnforcementLevel(identity); } inline bool ProtectionPolicyManager::IsUserDecryptionAllowed(hstring_view identity) { return get_activation_factory<ProtectionPolicyManager, IProtectionPolicyManagerStatics2>().IsUserDecryptionAllowed(identity); } inline bool ProtectionPolicyManager::IsProtectionUnderLockRequired(hstring_view identity) { return get_activation_factory<ProtectionPolicyManager, IProtectionPolicyManagerStatics2>().IsProtectionUnderLockRequired(identity); } inline event_token ProtectionPolicyManager::PolicyChanged(const Windows::Foundation::EventHandler<Windows::Foundation::IInspectable> & handler) { return get_activation_factory<ProtectionPolicyManager, IProtectionPolicyManagerStatics2>().PolicyChanged(handler); } inline factory_event_revoker<IProtectionPolicyManagerStatics2> ProtectionPolicyManager::PolicyChanged(auto_revoke_t, const Windows::Foundation::EventHandler<Windows::Foundation::IInspectable> & handler) { auto factory = get_activation_factory<ProtectionPolicyManager, IProtectionPolicyManagerStatics2>(); return { factory, &ABI::Windows::Security::EnterpriseData::IProtectionPolicyManagerStatics2::remove_PolicyChanged, factory.PolicyChanged(handler) }; } inline void ProtectionPolicyManager::PolicyChanged(event_token token) { get_activation_factory<ProtectionPolicyManager, IProtectionPolicyManagerStatics2>().PolicyChanged(token); } inline bool ProtectionPolicyManager::IsProtectionEnabled() { return get_activation_factory<ProtectionPolicyManager, IProtectionPolicyManagerStatics2>().IsProtectionEnabled(); } inline Windows::Foundation::IAsyncOperation<winrt::Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult> ProtectionPolicyManager::RequestAccessAsync(hstring_view sourceIdentity, hstring_view targetIdentity, const Windows::Security::EnterpriseData::ProtectionPolicyAuditInfo & auditInfo) { return get_activation_factory<ProtectionPolicyManager, IProtectionPolicyManagerStatics3>().RequestAccessAsync(sourceIdentity, targetIdentity, auditInfo); } inline Windows::Foundation::IAsyncOperation<winrt::Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult> ProtectionPolicyManager::RequestAccessAsync(hstring_view sourceIdentity, hstring_view targetIdentity, const Windows::Security::EnterpriseData::ProtectionPolicyAuditInfo & auditInfo, hstring_view messageFromApp) { return get_activation_factory<ProtectionPolicyManager, IProtectionPolicyManagerStatics3>().RequestAccessAsync(sourceIdentity, targetIdentity, auditInfo, messageFromApp); } inline Windows::Foundation::IAsyncOperation<winrt::Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult> ProtectionPolicyManager::RequestAccessForAppAsync(hstring_view sourceIdentity, hstring_view appPackageFamilyName, const Windows::Security::EnterpriseData::ProtectionPolicyAuditInfo & auditInfo) { return get_activation_factory<ProtectionPolicyManager, IProtectionPolicyManagerStatics3>().RequestAccessForAppAsync(sourceIdentity, appPackageFamilyName, auditInfo); } inline Windows::Foundation::IAsyncOperation<winrt::Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult> ProtectionPolicyManager::RequestAccessForAppAsync(hstring_view sourceIdentity, hstring_view appPackageFamilyName, const Windows::Security::EnterpriseData::ProtectionPolicyAuditInfo & auditInfo, hstring_view messageFromApp) { return get_activation_factory<ProtectionPolicyManager, IProtectionPolicyManagerStatics3>().RequestAccessForAppAsync(sourceIdentity, appPackageFamilyName, auditInfo, messageFromApp); } inline void ProtectionPolicyManager::LogAuditEvent(hstring_view sourceIdentity, hstring_view targetIdentity, const Windows::Security::EnterpriseData::ProtectionPolicyAuditInfo & auditInfo) { get_activation_factory<ProtectionPolicyManager, IProtectionPolicyManagerStatics3>().LogAuditEvent(sourceIdentity, targetIdentity, auditInfo); } inline bool ProtectionPolicyManager::IsRoamableProtectionEnabled(hstring_view identity) { return get_activation_factory<ProtectionPolicyManager, IProtectionPolicyManagerStatics4>().IsRoamableProtectionEnabled(identity); } inline Windows::Foundation::IAsyncOperation<winrt::Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult> ProtectionPolicyManager::RequestAccessAsync(hstring_view sourceIdentity, hstring_view targetIdentity, const Windows::Security::EnterpriseData::ProtectionPolicyAuditInfo & auditInfo, hstring_view messageFromApp, Windows::Security::EnterpriseData::ProtectionPolicyRequestAccessBehavior behavior) { return get_activation_factory<ProtectionPolicyManager, IProtectionPolicyManagerStatics4>().RequestAccessAsync(sourceIdentity, targetIdentity, auditInfo, messageFromApp, behavior); } inline Windows::Foundation::IAsyncOperation<winrt::Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult> ProtectionPolicyManager::RequestAccessForAppAsync(hstring_view sourceIdentity, hstring_view appPackageFamilyName, const Windows::Security::EnterpriseData::ProtectionPolicyAuditInfo & auditInfo, hstring_view messageFromApp, Windows::Security::EnterpriseData::ProtectionPolicyRequestAccessBehavior behavior) { return get_activation_factory<ProtectionPolicyManager, IProtectionPolicyManagerStatics4>().RequestAccessForAppAsync(sourceIdentity, appPackageFamilyName, auditInfo, messageFromApp, behavior); } inline Windows::Foundation::IAsyncOperation<winrt::Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult> ProtectionPolicyManager::RequestAccessToFilesForAppAsync(iterable<Windows::Storage::IStorageItem> sourceItemList, hstring_view appPackageFamilyName, const Windows::Security::EnterpriseData::ProtectionPolicyAuditInfo & auditInfo) { return get_activation_factory<ProtectionPolicyManager, IProtectionPolicyManagerStatics4>().RequestAccessToFilesForAppAsync(sourceItemList, appPackageFamilyName, auditInfo); } inline Windows::Foundation::IAsyncOperation<winrt::Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult> ProtectionPolicyManager::RequestAccessToFilesForAppAsync(iterable<Windows::Storage::IStorageItem> sourceItemList, hstring_view appPackageFamilyName, const Windows::Security::EnterpriseData::ProtectionPolicyAuditInfo & auditInfo, hstring_view messageFromApp, Windows::Security::EnterpriseData::ProtectionPolicyRequestAccessBehavior behavior) { return get_activation_factory<ProtectionPolicyManager, IProtectionPolicyManagerStatics4>().RequestAccessToFilesForAppAsync(sourceItemList, appPackageFamilyName, auditInfo, messageFromApp, behavior); } inline Windows::Foundation::IAsyncOperation<winrt::Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult> ProtectionPolicyManager::RequestAccessToFilesForProcessAsync(iterable<Windows::Storage::IStorageItem> sourceItemList, uint32_t processId, const Windows::Security::EnterpriseData::ProtectionPolicyAuditInfo & auditInfo) { return get_activation_factory<ProtectionPolicyManager, IProtectionPolicyManagerStatics4>().RequestAccessToFilesForProcessAsync(sourceItemList, processId, auditInfo); } inline Windows::Foundation::IAsyncOperation<winrt::Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult> ProtectionPolicyManager::RequestAccessToFilesForProcessAsync(iterable<Windows::Storage::IStorageItem> sourceItemList, uint32_t processId, const Windows::Security::EnterpriseData::ProtectionPolicyAuditInfo & auditInfo, hstring_view messageFromApp, Windows::Security::EnterpriseData::ProtectionPolicyRequestAccessBehavior behavior) { return get_activation_factory<ProtectionPolicyManager, IProtectionPolicyManagerStatics4>().RequestAccessToFilesForProcessAsync(sourceItemList, processId, auditInfo, messageFromApp, behavior); } inline Windows::Foundation::IAsyncOperation<bool> ProtectionPolicyManager::IsFileProtectionRequiredAsync(const Windows::Storage::IStorageItem & target, hstring_view identity) { return get_activation_factory<ProtectionPolicyManager, IProtectionPolicyManagerStatics4>().IsFileProtectionRequiredAsync(target, identity); } inline Windows::Foundation::IAsyncOperation<bool> ProtectionPolicyManager::IsFileProtectionRequiredForNewFileAsync(const Windows::Storage::IStorageFolder & parentFolder, hstring_view identity, hstring_view desiredName) { return get_activation_factory<ProtectionPolicyManager, IProtectionPolicyManagerStatics4>().IsFileProtectionRequiredForNewFileAsync(parentFolder, identity, desiredName); } inline hstring ProtectionPolicyManager::PrimaryManagedIdentity() { return get_activation_factory<ProtectionPolicyManager, IProtectionPolicyManagerStatics4>().PrimaryManagedIdentity(); } inline hstring ProtectionPolicyManager::GetPrimaryManagedIdentityForIdentity(hstring_view identity) { return get_activation_factory<ProtectionPolicyManager, IProtectionPolicyManagerStatics4>().GetPrimaryManagedIdentityForIdentity(identity); } } } template<> struct std::hash<winrt::Windows::Security::EnterpriseData::IBufferProtectUnprotectResult> { size_t operator()(const winrt::Windows::Security::EnterpriseData::IBufferProtectUnprotectResult & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Security::EnterpriseData::IDataProtectionInfo> { size_t operator()(const winrt::Windows::Security::EnterpriseData::IDataProtectionInfo & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Security::EnterpriseData::IDataProtectionManagerStatics> { size_t operator()(const winrt::Windows::Security::EnterpriseData::IDataProtectionManagerStatics & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Security::EnterpriseData::IFileProtectionInfo> { size_t operator()(const winrt::Windows::Security::EnterpriseData::IFileProtectionInfo & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Security::EnterpriseData::IFileProtectionManagerStatics> { size_t operator()(const winrt::Windows::Security::EnterpriseData::IFileProtectionManagerStatics & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Security::EnterpriseData::IFileProtectionManagerStatics2> { size_t operator()(const winrt::Windows::Security::EnterpriseData::IFileProtectionManagerStatics2 & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Security::EnterpriseData::IFileProtectionManagerStatics3> { size_t operator()(const winrt::Windows::Security::EnterpriseData::IFileProtectionManagerStatics3 & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Security::EnterpriseData::IFileRevocationManagerStatics> { size_t operator()(const winrt::Windows::Security::EnterpriseData::IFileRevocationManagerStatics & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Security::EnterpriseData::IFileUnprotectOptions> { size_t operator()(const winrt::Windows::Security::EnterpriseData::IFileUnprotectOptions & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Security::EnterpriseData::IFileUnprotectOptionsFactory> { size_t operator()(const winrt::Windows::Security::EnterpriseData::IFileUnprotectOptionsFactory & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Security::EnterpriseData::IProtectedAccessResumedEventArgs> { size_t operator()(const winrt::Windows::Security::EnterpriseData::IProtectedAccessResumedEventArgs & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Security::EnterpriseData::IProtectedAccessSuspendingEventArgs> { size_t operator()(const winrt::Windows::Security::EnterpriseData::IProtectedAccessSuspendingEventArgs & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Security::EnterpriseData::IProtectedContainerExportResult> { size_t operator()(const winrt::Windows::Security::EnterpriseData::IProtectedContainerExportResult & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Security::EnterpriseData::IProtectedContainerImportResult> { size_t operator()(const winrt::Windows::Security::EnterpriseData::IProtectedContainerImportResult & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Security::EnterpriseData::IProtectedContentRevokedEventArgs> { size_t operator()(const winrt::Windows::Security::EnterpriseData::IProtectedContentRevokedEventArgs & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Security::EnterpriseData::IProtectedFileCreateResult> { size_t operator()(const winrt::Windows::Security::EnterpriseData::IProtectedFileCreateResult & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Security::EnterpriseData::IProtectionPolicyAuditInfo> { size_t operator()(const winrt::Windows::Security::EnterpriseData::IProtectionPolicyAuditInfo & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Security::EnterpriseData::IProtectionPolicyAuditInfoFactory> { size_t operator()(const winrt::Windows::Security::EnterpriseData::IProtectionPolicyAuditInfoFactory & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Security::EnterpriseData::IProtectionPolicyManager> { size_t operator()(const winrt::Windows::Security::EnterpriseData::IProtectionPolicyManager & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Security::EnterpriseData::IProtectionPolicyManager2> { size_t operator()(const winrt::Windows::Security::EnterpriseData::IProtectionPolicyManager2 & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Security::EnterpriseData::IProtectionPolicyManagerStatics> { size_t operator()(const winrt::Windows::Security::EnterpriseData::IProtectionPolicyManagerStatics & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Security::EnterpriseData::IProtectionPolicyManagerStatics2> { size_t operator()(const winrt::Windows::Security::EnterpriseData::IProtectionPolicyManagerStatics2 & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Security::EnterpriseData::IProtectionPolicyManagerStatics3> { size_t operator()(const winrt::Windows::Security::EnterpriseData::IProtectionPolicyManagerStatics3 & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Security::EnterpriseData::IProtectionPolicyManagerStatics4> { size_t operator()(const winrt::Windows::Security::EnterpriseData::IProtectionPolicyManagerStatics4 & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Security::EnterpriseData::IThreadNetworkContext> { size_t operator()(const winrt::Windows::Security::EnterpriseData::IThreadNetworkContext & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Security::EnterpriseData::BufferProtectUnprotectResult> { size_t operator()(const winrt::Windows::Security::EnterpriseData::BufferProtectUnprotectResult & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Security::EnterpriseData::DataProtectionInfo> { size_t operator()(const winrt::Windows::Security::EnterpriseData::DataProtectionInfo & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Security::EnterpriseData::FileProtectionInfo> { size_t operator()(const winrt::Windows::Security::EnterpriseData::FileProtectionInfo & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Security::EnterpriseData::FileUnprotectOptions> { size_t operator()(const winrt::Windows::Security::EnterpriseData::FileUnprotectOptions & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Security::EnterpriseData::ProtectedAccessResumedEventArgs> { size_t operator()(const winrt::Windows::Security::EnterpriseData::ProtectedAccessResumedEventArgs & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Security::EnterpriseData::ProtectedAccessSuspendingEventArgs> { size_t operator()(const winrt::Windows::Security::EnterpriseData::ProtectedAccessSuspendingEventArgs & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Security::EnterpriseData::ProtectedContainerExportResult> { size_t operator()(const winrt::Windows::Security::EnterpriseData::ProtectedContainerExportResult & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Security::EnterpriseData::ProtectedContainerImportResult> { size_t operator()(const winrt::Windows::Security::EnterpriseData::ProtectedContainerImportResult & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Security::EnterpriseData::ProtectedContentRevokedEventArgs> { size_t operator()(const winrt::Windows::Security::EnterpriseData::ProtectedContentRevokedEventArgs & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Security::EnterpriseData::ProtectedFileCreateResult> { size_t operator()(const winrt::Windows::Security::EnterpriseData::ProtectedFileCreateResult & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Security::EnterpriseData::ProtectionPolicyAuditInfo> { size_t operator()(const winrt::Windows::Security::EnterpriseData::ProtectionPolicyAuditInfo & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Security::EnterpriseData::ProtectionPolicyManager> { size_t operator()(const winrt::Windows::Security::EnterpriseData::ProtectionPolicyManager & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Security::EnterpriseData::ThreadNetworkContext> { size_t operator()(const winrt::Windows::Security::EnterpriseData::ThreadNetworkContext & value) const noexcept { return winrt::impl::hash_unknown(value); } }; WINRT_WARNING_POP
1227f015fcbdf85b272b9d6847251779c3313f18
9e6b687da34c799e006c629aa8a33c3809bf9dee
/src/Driver/BaseControl.cpp
64dcc60a19aab3422fdb956b2c6d35bc6ea75343
[]
no_license
Taz7842K/7842K-Highland-New
54647711a0ff336dd455088fe56f6b2eff2aae28
2ac766761ae074d12f534a69330fa4ef1de210eb
refs/heads/master
2020-04-12T07:16:03.557640
2018-12-19T17:49:45
2018-12-19T17:49:45
162,362,131
1
0
null
null
null
null
UTF-8
C++
false
false
705
cpp
#include "main.h" #include "MainConfig.h" pros::Controller HIDMain(pros::E_CONTROLLER_MASTER); double Joystickch2; double Joystickch4; void setBasePower(int xPower, int yPower, int zPower) { m_frontLeft.move(yPower-xPower-zPower); m_rearRight.move(yPower+xPower-zPower); m_frontLeft.move(yPower+xPower+zPower); m_rearLeft.move(yPower-xPower+zPower); } void baseControlTask(void*) { while(true) { int Joystickch2 = HIDMain.get_analog(ANALOG_LEFT_X); int Joystickch4 = HIDMain.get_analog(ANALOG_LEFT_Y); int Joystickch3 = HIDMain.get_analog(ANALOG_RIGHT_X);//PLACEHOLDER!! setBasePower(Joystickch2,Joystickch4,Joystickch3); } } // remove error your problem // telllletype
56eb2b51ee2a8ad777753398fbde7f42eccbc56a
26ad4cc35496d364b31396e43a863aee08ef2636
/SDK/SoT_BP_cmp_lantern_oos_01_b_ItemDesc_functions.cpp
83a31619a3c75c659a8281d1e16a78593d7fd531
[]
no_license
cw100/SoT-SDK
ddb9b19ce6ae623299b2b02dee51c29581537ba1
3e6f12384c8e21ed83ef56f00030ca0506d297fb
refs/heads/master
2020-05-05T12:09:55.938323
2019-03-20T14:11:57
2019-03-20T14:11:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
369
cpp
// Sea of Thieves (1.4) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "SoT_BP_cmp_lantern_oos_01_b_ItemDesc_classes.hpp" namespace SDK { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- } #ifdef _MSC_VER #pragma pack(pop) #endif
2936e1a76ef63722494d98f1fb8eb3861222e6f1
f207164511f0dfe3f01f6e0c21fd7548e626397f
/gfx/thebes/gfxTextRun.h
bde5c5fe1f950553e65198b18f01b9a927270655
[]
no_license
PortableApps/palemoon27
24dbac1a4b6fe620611f4fb6800a29ae6f008d37
3d7e107cc639bc714906baad262a3492372e05d7
refs/heads/master
2023-08-15T12:32:23.822300
2021-10-11T01:54:45
2021-10-11T01:54:45
416,058,642
1
0
null
null
null
null
UTF-8
C++
false
false
49,956
h
/* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 4 -*- * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef GFX_TEXTRUN_H #define GFX_TEXTRUN_H #include "gfxTypes.h" #include "nsString.h" #include "gfxPoint.h" #include "gfxFont.h" #include "nsTArray.h" #include "gfxSkipChars.h" #include "gfxPlatform.h" #include "mozilla/MemoryReporting.h" #include "DrawMode.h" #include "harfbuzz/hb.h" #include "nsUnicodeScriptCodes.h" #ifdef DEBUG #include <stdio.h> #endif class gfxContext; class gfxFontGroup; class gfxUserFontEntry; class gfxUserFontSet; class gfxTextContextPaint; class nsIAtom; class nsILanguageAtomService; class gfxMissingFontRecorder; /** * Callback for Draw() to use when drawing text with mode * DrawMode::GLYPH_PATH. */ struct gfxTextRunDrawCallbacks { /** * Constructs a new DrawCallbacks object. * * @param aShouldPaintSVGGlyphs If true, SVG glyphs will be painted. If * false, SVG glyphs will not be painted; fallback plain glyphs are not * emitted either. */ explicit gfxTextRunDrawCallbacks(bool aShouldPaintSVGGlyphs = false) : mShouldPaintSVGGlyphs(aShouldPaintSVGGlyphs) { } /** * Called when a path has been emitted to the gfxContext when * painting a text run. This can be called any number of times, * due to partial ligatures and intervening SVG glyphs. */ virtual void NotifyGlyphPathEmitted() = 0; bool mShouldPaintSVGGlyphs; }; /** * gfxTextRun is an abstraction for drawing and measuring substrings of a run * of text. It stores runs of positioned glyph data, each run having a single * gfxFont. The glyphs are associated with a string of source text, and the * gfxTextRun APIs take parameters that are offsets into that source text. * * gfxTextRuns are not refcounted. They should be deleted when no longer required. * * gfxTextRuns are mostly immutable. The only things that can change are * inter-cluster spacing and line break placement. Spacing is always obtained * lazily by methods that need it, it is not cached. Line breaks are stored * persistently (insofar as they affect the shaping of glyphs; gfxTextRun does * not actually do anything to explicitly account for line breaks). Initially * there are no line breaks. The textrun can record line breaks before or after * any given cluster. (Line breaks specified inside clusters are ignored.) * * It is important that zero-length substrings are handled correctly. This will * be on the test! */ class gfxTextRun : public gfxShapedText { public: // Override operator delete to properly free the object that was // allocated via moz_malloc. void operator delete(void* p) { moz_free(p); } virtual ~gfxTextRun(); typedef gfxFont::RunMetrics Metrics; // Public textrun API for general use bool IsClusterStart(uint32_t aPos) const { NS_ASSERTION(aPos < GetLength(), "aPos out of range"); return mCharacterGlyphs[aPos].IsClusterStart(); } bool IsLigatureGroupStart(uint32_t aPos) const { NS_ASSERTION(aPos < GetLength(), "aPos out of range"); return mCharacterGlyphs[aPos].IsLigatureGroupStart(); } bool CanBreakLineBefore(uint32_t aPos) const { return CanBreakBefore(aPos) == CompressedGlyph::FLAG_BREAK_TYPE_NORMAL; } bool CanHyphenateBefore(uint32_t aPos) const { return CanBreakBefore(aPos) == CompressedGlyph::FLAG_BREAK_TYPE_HYPHEN; } // Returns a gfxShapedText::CompressedGlyph::FLAG_BREAK_TYPE_* value // as defined in gfxFont.h (may be NONE, NORMAL or HYPHEN). uint8_t CanBreakBefore(uint32_t aPos) const { NS_ASSERTION(aPos < GetLength(), "aPos out of range"); return mCharacterGlyphs[aPos].CanBreakBefore(); } bool CharIsSpace(uint32_t aPos) const { NS_ASSERTION(aPos < GetLength(), "aPos out of range"); return mCharacterGlyphs[aPos].CharIsSpace(); } bool CharIsTab(uint32_t aPos) const { NS_ASSERTION(aPos < GetLength(), "aPos out of range"); return mCharacterGlyphs[aPos].CharIsTab(); } bool CharIsNewline(uint32_t aPos) const { NS_ASSERTION(aPos < GetLength(), "aPos out of range"); return mCharacterGlyphs[aPos].CharIsNewline(); } bool CharIsLowSurrogate(uint32_t aPos) const { NS_ASSERTION(aPos < GetLength(), "aPos out of range"); return mCharacterGlyphs[aPos].CharIsLowSurrogate(); } // All uint32_t aStart, uint32_t aLength ranges below are restricted to // grapheme cluster boundaries! All offsets are in terms of the string // passed into MakeTextRun. // All coordinates are in layout/app units /** * Set the potential linebreaks for a substring of the textrun. These are * the "allow break before" points. Initially, there are no potential * linebreaks. * * This can change glyphs and/or geometry! Some textruns' shapes * depend on potential line breaks (e.g., title-case-converting textruns). * This function is virtual so that those textruns can reshape themselves. * * @return true if this changed the linebreaks, false if the new line * breaks are the same as the old */ virtual bool SetPotentialLineBreaks(uint32_t aStart, uint32_t aLength, uint8_t *aBreakBefore, gfxContext *aRefContext); /** * Layout provides PropertyProvider objects. These allow detection of * potential line break points and computation of spacing. We pass the data * this way to allow lazy data acquisition; for example BreakAndMeasureText * will want to only ask for properties of text it's actually looking at. * * NOTE that requested spacing may not actually be applied, if the textrun * is unable to apply it in some context. Exception: spacing around a * whitespace character MUST always be applied. */ class PropertyProvider { public: // Detect hyphenation break opportunities in the given range; breaks // not at cluster boundaries will be ignored. virtual void GetHyphenationBreaks(uint32_t aStart, uint32_t aLength, bool *aBreakBefore) = 0; // Returns the provider's hyphenation setting, so callers can decide // whether it is necessary to call GetHyphenationBreaks. // Result is an NS_STYLE_HYPHENS_* value. virtual int8_t GetHyphensOption() = 0; // Returns the extra width that will be consumed by a hyphen. This should // be constant for a given textrun. virtual gfxFloat GetHyphenWidth() = 0; typedef gfxFont::Spacing Spacing; /** * Get the spacing around the indicated characters. Spacing must be zero * inside clusters. In other words, if character i is not * CLUSTER_START, then character i-1 must have zero after-spacing and * character i must have zero before-spacing. */ virtual void GetSpacing(uint32_t aStart, uint32_t aLength, Spacing *aSpacing) = 0; // Returns a gfxContext that can be used to measure the hyphen glyph. // Only called if the hyphen width is requested. virtual already_AddRefed<gfxContext> GetContext() = 0; // Return the appUnitsPerDevUnit value to be used when measuring. // Only called if the hyphen width is requested. virtual uint32_t GetAppUnitsPerDevUnit() = 0; }; class ClusterIterator { public: explicit ClusterIterator(gfxTextRun *aTextRun); void Reset(); bool NextCluster(); uint32_t Position() const { return mCurrentChar; } uint32_t ClusterLength() const; gfxFloat ClusterAdvance(PropertyProvider *aProvider) const; private: gfxTextRun *mTextRun; uint32_t mCurrentChar; }; /** * Draws a substring. Uses only GetSpacing from aBreakProvider. * The provided point is the baseline origin on the left of the string * for LTR, on the right of the string for RTL. * @param aAdvanceWidth if non-null, the advance width of the substring * is returned here. * * Drawing should respect advance widths in the sense that for LTR runs, * Draw(ctx, pt, offset1, length1, dirty, &provider, &advance) followed by * Draw(ctx, gfxPoint(pt.x + advance, pt.y), offset1 + length1, length2, * dirty, &provider, nullptr) should have the same effect as * Draw(ctx, pt, offset1, length1+length2, dirty, &provider, nullptr). * For RTL runs the rule is: * Draw(ctx, pt, offset1 + length1, length2, dirty, &provider, &advance) followed by * Draw(ctx, gfxPoint(pt.x + advance, pt.y), offset1, length1, * dirty, &provider, nullptr) should have the same effect as * Draw(ctx, pt, offset1, length1+length2, dirty, &provider, nullptr). * * Glyphs should be drawn in logical content order, which can be significant * if they overlap (perhaps due to negative spacing). */ void Draw(gfxContext *aContext, gfxPoint aPt, DrawMode aDrawMode, uint32_t aStart, uint32_t aLength, PropertyProvider *aProvider, gfxFloat *aAdvanceWidth, gfxTextContextPaint *aContextPaint, gfxTextRunDrawCallbacks *aCallbacks = nullptr); /** * Computes the ReflowMetrics for a substring. * Uses GetSpacing from aBreakProvider. * @param aBoundingBoxType which kind of bounding box (loose/tight) */ Metrics MeasureText(uint32_t aStart, uint32_t aLength, gfxFont::BoundingBoxType aBoundingBoxType, gfxContext *aRefContextForTightBoundingBox, PropertyProvider *aProvider); /** * Computes just the advance width for a substring. * Uses GetSpacing from aBreakProvider. * If aSpacing is not null, the spacing attached before and after * the substring would be returned in it. NOTE: the spacing is * included in the advance width. */ gfxFloat GetAdvanceWidth(uint32_t aStart, uint32_t aLength, PropertyProvider *aProvider, PropertyProvider::Spacing* aSpacing = nullptr); /** * Clear all stored line breaks for the given range (both before and after), * and then set the line-break state before aStart to aBreakBefore and * after the last cluster to aBreakAfter. * * We require that before and after line breaks be consistent. For clusters * i and i+1, we require that if there is a break after cluster i, a break * will be specified before cluster i+1. This may be temporarily violated * (e.g. after reflowing line L and before reflowing line L+1); to handle * these temporary violations, we say that there is a break betwen i and i+1 * if a break is specified after i OR a break is specified before i+1. * * This can change textrun geometry! The existence of a linebreak can affect * the advance width of the cluster before the break (when kerning) or the * geometry of one cluster before the break or any number of clusters * after the break. (The one-cluster-before-the-break limit is somewhat * arbitrary; if some scripts require breaking it, then we need to * alter nsTextFrame::TrimTrailingWhitespace, perhaps drastically becase * it could affect the layout of frames before it...) * * We return true if glyphs or geometry changed, false otherwise. This * function is virtual so that gfxTextRun subclasses can reshape * properly. * * @param aAdvanceWidthDelta if non-null, returns the change in advance * width of the given range. */ virtual bool SetLineBreaks(uint32_t aStart, uint32_t aLength, bool aLineBreakBefore, bool aLineBreakAfter, gfxFloat *aAdvanceWidthDelta, gfxContext *aRefContext); enum SuppressBreak { eNoSuppressBreak, // Measure the range of text as if there is no break before it. eSuppressInitialBreak, // Measure the range of text as if it contains no break eSuppressAllBreaks }; /** * Finds the longest substring that will fit into the given width. * Uses GetHyphenationBreaks and GetSpacing from aBreakProvider. * Guarantees the following: * -- 0 <= result <= aMaxLength * -- result is the maximal value of N such that either * N < aMaxLength && line break at N && GetAdvanceWidth(aStart, N) <= aWidth * OR N < aMaxLength && hyphen break at N && GetAdvanceWidth(aStart, N) + GetHyphenWidth() <= aWidth * OR N == aMaxLength && GetAdvanceWidth(aStart, N) <= aWidth * where GetAdvanceWidth assumes the effect of * SetLineBreaks(aStart, N, aLineBreakBefore, N < aMaxLength, aProvider) * -- if no such N exists, then result is the smallest N such that * N < aMaxLength && line break at N * OR N < aMaxLength && hyphen break at N * OR N == aMaxLength * * The call has the effect of * SetLineBreaks(aStart, result, aLineBreakBefore, result < aMaxLength, aProvider) * and the returned metrics and the invariants above reflect this. * * @param aMaxLength this can be UINT32_MAX, in which case the length used * is up to the end of the string * @param aLineBreakBefore set to true if and only if there is an actual * line break at the start of this string. * @param aSuppressBreak what break should be suppressed. * @param aTrimWhitespace if non-null, then we allow a trailing run of * spaces to be trimmed; the width of the space(s) will not be included in * the measured string width for comparison with the limit aWidth, and * trimmed spaces will not be included in returned metrics. The width * of the trimmed spaces will be returned in aTrimWhitespace. * Trimmed spaces are still counted in the "characters fit" result. * @param aMetrics if non-null, we fill this in for the returned substring. * If a hyphenation break was used, the hyphen is NOT included in the returned metrics. * @param aBoundingBoxType whether to make the bounding box in aMetrics tight * @param aRefContextForTightBoundingBox a reference context to get the * tight bounding box, if requested * @param aUsedHyphenation if non-null, records if we selected a hyphenation break * @param aLastBreak if non-null and result is aMaxLength, we set this to * the maximal N such that * N < aMaxLength && line break at N && GetAdvanceWidth(aStart, N) <= aWidth * OR N < aMaxLength && hyphen break at N && GetAdvanceWidth(aStart, N) + GetHyphenWidth() <= aWidth * or UINT32_MAX if no such N exists, where GetAdvanceWidth assumes * the effect of * SetLineBreaks(aStart, N, aLineBreakBefore, N < aMaxLength, aProvider) * * @param aCanWordWrap true if we can break between any two grapheme * clusters. This is set by word-wrap: break-word * * @param aBreakPriority in/out the priority of the break opportunity * saved in the line. If we are prioritizing break opportunities, we will * not set a break with a lower priority. @see gfxBreakPriority. * * Note that negative advance widths are possible especially if negative * spacing is provided. */ uint32_t BreakAndMeasureText(uint32_t aStart, uint32_t aMaxLength, bool aLineBreakBefore, gfxFloat aWidth, PropertyProvider *aProvider, SuppressBreak aSuppressBreak, gfxFloat *aTrimWhitespace, Metrics *aMetrics, gfxFont::BoundingBoxType aBoundingBoxType, gfxContext *aRefContextForTightBoundingBox, bool *aUsedHyphenation, uint32_t *aLastBreak, bool aCanWordWrap, gfxBreakPriority *aBreakPriority); /** * Update the reference context. * XXX this is a hack. New text frame does not call this. Use only * temporarily for old text frame. */ void SetContext(gfxContext *aContext) {} // Utility getters void *GetUserData() const { return mUserData; } void SetUserData(void *aUserData) { mUserData = aUserData; } void SetFlagBits(uint32_t aFlags) { NS_ASSERTION(!(aFlags & ~gfxTextRunFactory::SETTABLE_FLAGS), "Only user flags should be mutable"); mFlags |= aFlags; } void ClearFlagBits(uint32_t aFlags) { NS_ASSERTION(!(aFlags & ~gfxTextRunFactory::SETTABLE_FLAGS), "Only user flags should be mutable"); mFlags &= ~aFlags; } const gfxSkipChars& GetSkipChars() const { return mSkipChars; } gfxFontGroup *GetFontGroup() const { return mFontGroup; } // Call this, don't call "new gfxTextRun" directly. This does custom // allocation and initialization static gfxTextRun *Create(const gfxTextRunFactory::Parameters *aParams, uint32_t aLength, gfxFontGroup *aFontGroup, uint32_t aFlags); // The text is divided into GlyphRuns as necessary struct GlyphRun { nsRefPtr<gfxFont> mFont; // never null uint32_t mCharacterOffset; // into original UTF16 string uint8_t mMatchType; uint16_t mOrientation; // gfxTextRunFactory::TEXT_ORIENT_* value }; class GlyphRunIterator { public: GlyphRunIterator(gfxTextRun *aTextRun, uint32_t aStart, uint32_t aLength) : mTextRun(aTextRun), mStartOffset(aStart), mEndOffset(aStart + aLength) { mNextIndex = mTextRun->FindFirstGlyphRunContaining(aStart); } bool NextRun(); GlyphRun *GetGlyphRun() { return mGlyphRun; } uint32_t GetStringStart() { return mStringStart; } uint32_t GetStringEnd() { return mStringEnd; } private: gfxTextRun *mTextRun; GlyphRun *mGlyphRun; uint32_t mStringStart; uint32_t mStringEnd; uint32_t mNextIndex; uint32_t mStartOffset; uint32_t mEndOffset; }; class GlyphRunOffsetComparator { public: bool Equals(const GlyphRun& a, const GlyphRun& b) const { return a.mCharacterOffset == b.mCharacterOffset; } bool LessThan(const GlyphRun& a, const GlyphRun& b) const { return a.mCharacterOffset < b.mCharacterOffset; } }; friend class GlyphRunIterator; friend class FontSelector; // API for setting up the textrun glyphs. Should only be called by // things that construct textruns. /** * We've found a run of text that should use a particular font. Call this * only during initialization when font substitution has been computed. * Call it before setting up the glyphs for the characters in this run; * SetMissingGlyph requires that the correct glyphrun be installed. * * If aForceNewRun, a new glyph run will be added, even if the * previously added run uses the same font. If glyph runs are * added out of strictly increasing aStartCharIndex order (via * force), then SortGlyphRuns must be called after all glyph runs * are added before any further operations are performed with this * TextRun. */ nsresult AddGlyphRun(gfxFont *aFont, uint8_t aMatchType, uint32_t aStartCharIndex, bool aForceNewRun, uint16_t aOrientation); void ResetGlyphRuns() { mGlyphRuns.Clear(); } void SortGlyphRuns(); void SanitizeGlyphRuns(); CompressedGlyph* GetCharacterGlyphs() { NS_ASSERTION(mCharacterGlyphs, "failed to initialize mCharacterGlyphs"); return mCharacterGlyphs; } // clean out results from shaping in progress, used for fallback scenarios void ClearGlyphsAndCharacters(); void SetSpaceGlyph(gfxFont *aFont, gfxContext *aContext, uint32_t aCharIndex, uint16_t aOrientation); // Set the glyph data for the given character index to the font's // space glyph, IF this can be done as a "simple" glyph record // (not requiring a DetailedGlyph entry). This avoids the need to call // the font shaper and go through the shaped-word cache for most spaces. // // The parameter aSpaceChar is the original character code for which // this space glyph is being used; if this is U+0020, we need to record // that it could be trimmed at a run edge, whereas other kinds of space // (currently just U+00A0) would not be trimmable/breakable. // // Returns true if it was able to set simple glyph data for the space; // if it returns false, the caller needs to fall back to some other // means to create the necessary (detailed) glyph data. bool SetSpaceGlyphIfSimple(gfxFont *aFont, gfxContext *aContext, uint32_t aCharIndex, char16_t aSpaceChar, uint16_t aOrientation); // Record the positions of specific characters that layout may need to // detect in the textrun, even though it doesn't have an explicit copy // of the original text. These are recorded using flag bits in the // CompressedGlyph record; if necessary, we convert "simple" glyph records // to "complex" ones as the Tab and Newline flags are not present in // simple CompressedGlyph records. void SetIsTab(uint32_t aIndex) { CompressedGlyph *g = &mCharacterGlyphs[aIndex]; if (g->IsSimpleGlyph()) { DetailedGlyph *details = AllocateDetailedGlyphs(aIndex, 1); details->mGlyphID = g->GetSimpleGlyph(); details->mAdvance = g->GetSimpleAdvance(); details->mXOffset = details->mYOffset = 0; SetGlyphs(aIndex, CompressedGlyph().SetComplex(true, true, 1), details); } g->SetIsTab(); } void SetIsNewline(uint32_t aIndex) { CompressedGlyph *g = &mCharacterGlyphs[aIndex]; if (g->IsSimpleGlyph()) { DetailedGlyph *details = AllocateDetailedGlyphs(aIndex, 1); details->mGlyphID = g->GetSimpleGlyph(); details->mAdvance = g->GetSimpleAdvance(); details->mXOffset = details->mYOffset = 0; SetGlyphs(aIndex, CompressedGlyph().SetComplex(true, true, 1), details); } g->SetIsNewline(); } void SetIsLowSurrogate(uint32_t aIndex) { SetGlyphs(aIndex, CompressedGlyph().SetComplex(false, false, 0), nullptr); mCharacterGlyphs[aIndex].SetIsLowSurrogate(); } /** * Prefetch all the glyph extents needed to ensure that Measure calls * on this textrun not requesting tight boundingBoxes will succeed. Note * that some glyph extents might not be fetched due to OOM or other * errors. */ void FetchGlyphExtents(gfxContext *aRefContext); uint32_t CountMissingGlyphs(); const GlyphRun *GetGlyphRuns(uint32_t *aNumGlyphRuns) { *aNumGlyphRuns = mGlyphRuns.Length(); return mGlyphRuns.Elements(); } // Returns the index of the GlyphRun containing the given offset. // Returns mGlyphRuns.Length() when aOffset is mCharacterCount. uint32_t FindFirstGlyphRunContaining(uint32_t aOffset); // Copy glyph data from a ShapedWord into this textrun. void CopyGlyphDataFrom(gfxShapedWord *aSource, uint32_t aStart); // Copy glyph data for a range of characters from aSource to this // textrun. void CopyGlyphDataFrom(gfxTextRun *aSource, uint32_t aStart, uint32_t aLength, uint32_t aDest); nsExpirationState *GetExpirationState() { return &mExpirationState; } // Tell the textrun to release its reference to its creating gfxFontGroup // immediately, rather than on destruction. This is used for textruns // that are actually owned by a gfxFontGroup, so that they don't keep it // permanently alive due to a circular reference. (The caller of this is // taking responsibility for ensuring the textrun will not outlive its // mFontGroup.) void ReleaseFontGroup(); struct LigatureData { // textrun offsets of the start and end of the containing ligature uint32_t mLigatureStart; uint32_t mLigatureEnd; // appunits advance to the start of the ligature part within the ligature; // never includes any spacing gfxFloat mPartAdvance; // appunits width of the ligature part; includes before-spacing // when the part is at the start of the ligature, and after-spacing // when the part is as the end of the ligature gfxFloat mPartWidth; bool mClipBeforePart; bool mClipAfterPart; }; // return storage used by this run, for memory reporter; // nsTransformedTextRun needs to override this as it holds additional data virtual size_t SizeOfExcludingThis(mozilla::MallocSizeOf aMallocSizeOf) MOZ_MUST_OVERRIDE; virtual size_t SizeOfIncludingThis(mozilla::MallocSizeOf aMallocSizeOf) MOZ_MUST_OVERRIDE; // Get the size, if it hasn't already been gotten, marking as it goes. size_t MaybeSizeOfIncludingThis(mozilla::MallocSizeOf aMallocSizeOf) { if (mFlags & gfxTextRunFactory::TEXT_RUN_SIZE_ACCOUNTED) { return 0; } mFlags |= gfxTextRunFactory::TEXT_RUN_SIZE_ACCOUNTED; return SizeOfIncludingThis(aMallocSizeOf); } void ResetSizeOfAccountingFlags() { mFlags &= ~gfxTextRunFactory::TEXT_RUN_SIZE_ACCOUNTED; } // shaping state - for some font features, fallback is required that // affects the entire run. for example, fallback for one script/font // portion of a textrun requires fallback to be applied to the entire run enum ShapingState { eShapingState_Normal, // default state eShapingState_ShapingWithFeature, // have shaped with feature eShapingState_ShapingWithFallback, // have shaped with fallback eShapingState_Aborted, // abort initial iteration eShapingState_ForceFallbackFeature // redo with fallback forced on }; ShapingState GetShapingState() const { return mShapingState; } void SetShapingState(ShapingState aShapingState) { mShapingState = aShapingState; } #ifdef DEBUG void Dump(FILE* aOutput); #endif protected: /** * Create a textrun, and set its mCharacterGlyphs to point immediately * after the base object; this is ONLY used in conjunction with placement * new, after allocating a block large enough for the glyph records to * follow the base textrun object. */ gfxTextRun(const gfxTextRunFactory::Parameters *aParams, uint32_t aLength, gfxFontGroup *aFontGroup, uint32_t aFlags); /** * Helper for the Create() factory method to allocate the required * glyph storage for a textrun object with the basic size aSize, * plus room for aLength glyph records. */ static void* AllocateStorageForTextRun(size_t aSize, uint32_t aLength); // Pointer to the array of CompressedGlyph records; must be initialized // when the object is constructed. CompressedGlyph *mCharacterGlyphs; private: // **** general helpers **** // Get the total advance for a range of glyphs. int32_t GetAdvanceForGlyphs(uint32_t aStart, uint32_t aEnd); // Spacing for characters outside the range aSpacingStart/aSpacingEnd // is assumed to be zero; such characters are not passed to aProvider. // This is useful to protect aProvider from being passed character indices // it is not currently able to handle. bool GetAdjustedSpacingArray(uint32_t aStart, uint32_t aEnd, PropertyProvider *aProvider, uint32_t aSpacingStart, uint32_t aSpacingEnd, nsTArray<PropertyProvider::Spacing> *aSpacing); // **** ligature helpers **** // (Platforms do the actual ligaturization, but we need to do a bunch of stuff // to handle requests that begin or end inside a ligature) // if aProvider is null then mBeforeSpacing and mAfterSpacing are set to zero LigatureData ComputeLigatureData(uint32_t aPartStart, uint32_t aPartEnd, PropertyProvider *aProvider); gfxFloat ComputePartialLigatureWidth(uint32_t aPartStart, uint32_t aPartEnd, PropertyProvider *aProvider); void DrawPartialLigature(gfxFont *aFont, uint32_t aStart, uint32_t aEnd, gfxPoint *aPt, PropertyProvider *aProvider, TextRunDrawParams& aParams, uint16_t aOrientation); // Advance aStart to the start of the nearest ligature; back up aEnd // to the nearest ligature end; may result in *aStart == *aEnd void ShrinkToLigatureBoundaries(uint32_t *aStart, uint32_t *aEnd); // result in appunits gfxFloat GetPartialLigatureWidth(uint32_t aStart, uint32_t aEnd, PropertyProvider *aProvider); void AccumulatePartialLigatureMetrics(gfxFont *aFont, uint32_t aStart, uint32_t aEnd, gfxFont::BoundingBoxType aBoundingBoxType, gfxContext *aRefContext, PropertyProvider *aProvider, uint16_t aOrientation, Metrics *aMetrics); // **** measurement helper **** void AccumulateMetricsForRun(gfxFont *aFont, uint32_t aStart, uint32_t aEnd, gfxFont::BoundingBoxType aBoundingBoxType, gfxContext *aRefContext, PropertyProvider *aProvider, uint32_t aSpacingStart, uint32_t aSpacingEnd, uint16_t aOrientation, Metrics *aMetrics); // **** drawing helper **** void DrawGlyphs(gfxFont *aFont, uint32_t aStart, uint32_t aEnd, gfxPoint *aPt, PropertyProvider *aProvider, uint32_t aSpacingStart, uint32_t aSpacingEnd, TextRunDrawParams& aParams, uint16_t aOrientation); // XXX this should be changed to a GlyphRun plus a maybe-null GlyphRun*, // for smaller size especially in the super-common one-glyphrun case nsAutoTArray<GlyphRun,1> mGlyphRuns; void *mUserData; gfxFontGroup *mFontGroup; // addrefed on creation, but our reference // may be released by ReleaseFontGroup() gfxSkipChars mSkipChars; nsExpirationState mExpirationState; bool mSkipDrawing; // true if the font group we used had a user font // download that's in progress, so we should hide text // until the download completes (or timeout fires) bool mReleasedFontGroup; // we already called NS_RELEASE on // mFontGroup, so don't do it again // shaping state for handling variant fallback features // such as subscript/superscript variant glyphs ShapingState mShapingState; }; class gfxFontGroup : public gfxTextRunFactory { public: static void Shutdown(); // platform must call this to release the languageAtomService gfxFontGroup(const mozilla::FontFamilyList& aFontFamilyList, const gfxFontStyle *aStyle, gfxUserFontSet *aUserFontSet = nullptr); virtual ~gfxFontGroup(); // Returns first valid font in the fontlist or default font. // Initiates userfont loads if userfont not loaded virtual gfxFont* GetFirstValidFont(uint32_t aCh = 0x20); // Returns the first font in the font-group that has an OpenType MATH table, // or null if no such font is available. The GetMathConstant methods may be // called on the returned font. gfxFont *GetFirstMathFont(); const gfxFontStyle *GetStyle() const { return &mStyle; } virtual gfxFontGroup *Copy(const gfxFontStyle *aStyle); /** * The listed characters should be treated as invisible and zero-width * when creating textruns. */ static bool IsInvalidChar(uint8_t ch); static bool IsInvalidChar(char16_t ch); /** * Make a textrun for a given string. * If aText is not persistent (aFlags & TEXT_IS_PERSISTENT), the * textrun will copy it. * This calls FetchGlyphExtents on the textrun. */ virtual gfxTextRun *MakeTextRun(const char16_t *aString, uint32_t aLength, const Parameters *aParams, uint32_t aFlags, gfxMissingFontRecorder *aMFR); /** * Make a textrun for a given string. * If aText is not persistent (aFlags & TEXT_IS_PERSISTENT), the * textrun will copy it. * This calls FetchGlyphExtents on the textrun. */ virtual gfxTextRun *MakeTextRun(const uint8_t *aString, uint32_t aLength, const Parameters *aParams, uint32_t aFlags, gfxMissingFontRecorder *aMFR); /** * Textrun creation helper for clients that don't want to pass * a full Parameters record. */ template<typename T> gfxTextRun *MakeTextRun(const T *aString, uint32_t aLength, gfxContext *aRefContext, int32_t aAppUnitsPerDevUnit, uint32_t aFlags, gfxMissingFontRecorder *aMFR) { gfxTextRunFactory::Parameters params = { aRefContext, nullptr, nullptr, nullptr, 0, aAppUnitsPerDevUnit }; return MakeTextRun(aString, aLength, &params, aFlags, aMFR); } /** * Get the (possibly-cached) width of the hyphen character. * The aCtx and aAppUnitsPerDevUnit parameters will be used only if * needed to initialize the cached hyphen width; otherwise they are * ignored. */ gfxFloat GetHyphenWidth(gfxTextRun::PropertyProvider* aProvider); /** * Make a text run representing a single hyphen character. * This will use U+2010 HYPHEN if available in the first font, * otherwise fall back to U+002D HYPHEN-MINUS. * The caller is responsible for deleting the returned text run * when no longer required. */ gfxTextRun *MakeHyphenTextRun(gfxContext *aCtx, uint32_t aAppUnitsPerDevUnit); /** * Check whether a given font (specified by its gfxFontEntry) * is already in the fontgroup's list of actual fonts */ bool HasFont(const gfxFontEntry *aFontEntry); // This returns the preferred underline for this font group. // Some CJK fonts have wrong underline offset in its metrics. // If this group has such "bad" font, each platform's gfxFontGroup // initialized mUnderlineOffset. The value should be lower value of // first font's metrics and the bad font's metrics. Otherwise, this // returns from first font's metrics. enum { UNDERLINE_OFFSET_NOT_SET = INT16_MAX }; virtual gfxFloat GetUnderlineOffset(); virtual already_AddRefed<gfxFont> FindFontForChar(uint32_t ch, uint32_t prevCh, uint32_t aNextCh, int32_t aRunScript, gfxFont *aPrevMatchedFont, uint8_t *aMatchType); // search through pref fonts for a character, return nullptr if no matching pref font virtual already_AddRefed<gfxFont> WhichPrefFontSupportsChar(uint32_t aCh); already_AddRefed<gfxFont> WhichSystemFontSupportsChar(uint32_t aCh, uint32_t aNextCh, int32_t aRunScript); template<typename T> void ComputeRanges(nsTArray<gfxTextRange>& mRanges, const T *aString, uint32_t aLength, int32_t aRunScript, uint16_t aOrientation); gfxUserFontSet* GetUserFontSet(); // With downloadable fonts, the composition of the font group can change as fonts are downloaded // for each change in state of the user font set, the generation value is bumped to avoid picking up // previously created text runs in the text run word cache. For font groups based on stylesheets // with no @font-face rule, this always returns 0. uint64_t GetGeneration(); // generation of the latest fontset rebuild, 0 when no fontset present uint64_t GetRebuildGeneration(); // used when logging text performance gfxTextPerfMetrics *GetTextPerfMetrics() { return mTextPerf; } void SetTextPerfMetrics(gfxTextPerfMetrics *aTextPerf) { mTextPerf = aTextPerf; } // This will call UpdateUserFonts() if the user font set is changed. void SetUserFontSet(gfxUserFontSet *aUserFontSet); // If there is a user font set, check to see whether the font list or any // caches need updating. virtual void UpdateUserFonts(); // search for a specific userfont in the list of fonts bool ContainsUserFont(const gfxUserFontEntry* aUserFont); bool ShouldSkipDrawing() const { return mSkipDrawing; } class LazyReferenceContextGetter { public: virtual already_AddRefed<gfxContext> GetRefContext() = 0; }; // The gfxFontGroup keeps ownership of this textrun. // It is only guaranteed to exist until the next call to GetEllipsisTextRun // (which might use a different appUnitsPerDev value or flags) for the font // group, or until UpdateUserFonts is called, or the fontgroup is destroyed. // Get it/use it/forget it :) - don't keep a reference that might go stale. gfxTextRun* GetEllipsisTextRun(int32_t aAppUnitsPerDevPixel, uint32_t aFlags, LazyReferenceContextGetter& aRefContextGetter); // helper method for resolving generic font families static void ResolveGenericFontNames(mozilla::FontFamilyType aGenericType, nsIAtom *aLanguage, nsTArray<nsString>& aGenericFamilies); protected: class FamilyFace { public: FamilyFace() : mFamily(nullptr), mFontEntry(nullptr), mNeedsBold(false), mFontCreated(false), mLoading(false), mInvalid(false) { } FamilyFace(gfxFontFamily* aFamily, gfxFont* aFont) : mFamily(aFamily), mNeedsBold(false), mFontCreated(true), mLoading(false), mInvalid(false) { NS_ASSERTION(aFont, "font pointer must not be null"); NS_ASSERTION(!aFamily || aFamily->ContainsFace(aFont->GetFontEntry()), "font is not a member of the given family"); mFont = aFont; NS_ADDREF(aFont); } FamilyFace(gfxFontFamily* aFamily, gfxFontEntry* aFontEntry, bool aNeedsBold) : mFamily(aFamily), mNeedsBold(aNeedsBold), mFontCreated(false), mLoading(false), mInvalid(false) { NS_ASSERTION(aFontEntry, "font entry pointer must not be null"); NS_ASSERTION(!aFamily || aFamily->ContainsFace(aFontEntry), "font is not a member of the given family"); mFontEntry = aFontEntry; NS_ADDREF(aFontEntry); } FamilyFace(const FamilyFace& aOtherFamilyFace) : mFamily(aOtherFamilyFace.mFamily), mNeedsBold(aOtherFamilyFace.mNeedsBold), mFontCreated(aOtherFamilyFace.mFontCreated), mLoading(aOtherFamilyFace.mLoading), mInvalid(aOtherFamilyFace.mInvalid) { if (mFontCreated) { mFont = aOtherFamilyFace.mFont; NS_ADDREF(mFont); } else { mFontEntry = aOtherFamilyFace.mFontEntry; NS_IF_ADDREF(mFontEntry); } } ~FamilyFace() { if (mFontCreated) { NS_RELEASE(mFont); } else { NS_IF_RELEASE(mFontEntry); } } FamilyFace& operator=(const FamilyFace& aOther) { if (mFontCreated) { NS_RELEASE(mFont); } else { NS_IF_RELEASE(mFontEntry); } mFamily = aOther.mFamily; mNeedsBold = aOther.mNeedsBold; mFontCreated = aOther.mFontCreated; mLoading = aOther.mLoading; mInvalid = aOther.mInvalid; if (mFontCreated) { mFont = aOther.mFont; NS_ADDREF(mFont); } else { mFontEntry = aOther.mFontEntry; NS_IF_ADDREF(mFontEntry); } return *this; } gfxFontFamily* Family() const { return mFamily.get(); } gfxFont* Font() const { return mFontCreated ? mFont : nullptr; } gfxFontEntry* FontEntry() const { return mFontCreated ? mFont->GetFontEntry() : mFontEntry; } bool NeedsBold() const { return mNeedsBold; } bool IsUserFontContainer() const { return FontEntry()->mIsUserFontContainer; } bool IsLoading() const { return mLoading; } bool IsInvalid() const { return mInvalid; } void CheckState(bool& aSkipDrawing); void SetLoading(bool aIsLoading) { mLoading = aIsLoading; } void SetInvalid() { mInvalid = true; } void SetFont(gfxFont* aFont) { NS_ASSERTION(aFont, "font pointer must not be null"); NS_ADDREF(aFont); if (mFontCreated) { NS_RELEASE(mFont); } else { NS_IF_RELEASE(mFontEntry); } mFont = aFont; mFontCreated = true; mLoading = false; } bool EqualsUserFont(const gfxUserFontEntry* aUserFont) const; private: nsRefPtr<gfxFontFamily> mFamily; // either a font or a font entry exists union { gfxFont* mFont; gfxFontEntry* mFontEntry; }; bool mNeedsBold : 1; bool mFontCreated : 1; bool mLoading : 1; bool mInvalid : 1; }; // List of font families, either named or generic. // Generic names map to system pref fonts based on language. mozilla::FontFamilyList mFamilyList; // Fontlist containing a font entry for each family found. gfxFont objects // are created as needed and userfont loads are initiated when needed. // Code should be careful about addressing this array directly. nsTArray<FamilyFace> mFonts; nsRefPtr<gfxFont> mDefaultFont; gfxFontStyle mStyle; gfxFloat mUnderlineOffset; gfxFloat mHyphenWidth; nsRefPtr<gfxUserFontSet> mUserFontSet; uint64_t mCurrGeneration; // track the current user font set generation, rebuild font list if needed gfxTextPerfMetrics *mTextPerf; // Cache a textrun representing an ellipsis (useful for CSS text-overflow) // at a specific appUnitsPerDevPixel size and orientation nsAutoPtr<gfxTextRun> mCachedEllipsisTextRun; // cache the most recent pref font to avoid general pref font lookup nsRefPtr<gfxFontFamily> mLastPrefFamily; nsRefPtr<gfxFont> mLastPrefFont; eFontPrefLang mLastPrefLang; // lang group for last pref font eFontPrefLang mPageLang; bool mLastPrefFirstFont; // is this the first font in the list of pref fonts for this lang group? bool mSkipDrawing; // hide text while waiting for a font // download to complete (or fallback // timer to fire) // xxx - gfxPangoFontGroup skips UpdateUserFonts bool mSkipUpdateUserFonts; /** * Textrun creation short-cuts for special cases where we don't need to * call a font shaper to generate glyphs. */ gfxTextRun *MakeEmptyTextRun(const Parameters *aParams, uint32_t aFlags); gfxTextRun *MakeSpaceTextRun(const Parameters *aParams, uint32_t aFlags); gfxTextRun *MakeBlankTextRun(uint32_t aLength, const Parameters *aParams, uint32_t aFlags); // Initialize the list of fonts void BuildFontList(); // Get the font at index i within the fontlist. // Will initiate userfont load if not already loaded. // May return null if userfont not loaded or if font invalid virtual gfxFont* GetFontAt(int32_t i, uint32_t aCh = 0x20); // Whether there's a font loading for a given family in the fontlist // for a given character bool FontLoadingForFamily(gfxFontFamily* aFamily, uint32_t aCh) const; // will always return a font or force a shutdown gfxFont* GetDefaultFont(); // Init this font group's font metrics. If there no bad fonts, you don't need to call this. // But if there are one or more bad fonts which have bad underline offset, // you should call this with the *first* bad font. void InitMetricsForBadFont(gfxFont* aBadFont); // Set up the textrun glyphs for an entire text run: // find script runs, and then call InitScriptRun for each template<typename T> void InitTextRun(gfxContext *aContext, gfxTextRun *aTextRun, const T *aString, uint32_t aLength, gfxMissingFontRecorder *aMFR); // InitTextRun helper to handle a single script run, by finding font ranges // and calling each font's InitTextRun() as appropriate template<typename T> void InitScriptRun(gfxContext *aContext, gfxTextRun *aTextRun, const T *aString, uint32_t aScriptRunStart, uint32_t aScriptRunEnd, int32_t aRunScript, gfxMissingFontRecorder *aMFR); // Helper for font-matching: // When matching the italic case, allow use of the regular face // if it supports a character but the italic one doesn't. // Return null if regular face doesn't support aCh already_AddRefed<gfxFont> FindNonItalicFaceForChar(gfxFontFamily* aFamily, uint32_t aCh); // helper methods for looking up fonts // iterate over the fontlist, lookup names and expand generics void EnumerateFontList(nsIAtom *aLanguage, void *aClosure = nullptr); // expand a generic to a list of specific names based on prefs void FindGenericFonts(mozilla::FontFamilyType aGenericType, nsIAtom *aLanguage, void *aClosure); // lookup and add a font with a given name (i.e. *not* a generic!) virtual void FindPlatformFont(const nsAString& aName, bool aUseFontSet, void *aClosure); static nsILanguageAtomService* gLangService; }; // A "missing font recorder" is to be used during text-run creation to keep // a record of any scripts encountered for which font coverage was lacking; // when Flush() is called, it sends a notification that front-end code can use // to download fonts on demand (or whatever else it wants to do). #define GFX_MISSING_FONTS_NOTIFY_PREF "gfx.missing_fonts.notify" class gfxMissingFontRecorder { public: gfxMissingFontRecorder() { MOZ_COUNT_CTOR(gfxMissingFontRecorder); memset(&mMissingFonts, 0, sizeof(mMissingFonts)); } ~gfxMissingFontRecorder() { #ifdef DEBUG for (uint32_t i = 0; i < kNumScriptBitsWords; i++) { NS_ASSERTION(mMissingFonts[i] == 0, "failed to flush the missing-font recorder"); } #endif MOZ_COUNT_DTOR(gfxMissingFontRecorder); } // record this script code in our mMissingFonts bitset void RecordScript(int32_t aScriptCode) { mMissingFonts[uint32_t(aScriptCode) >> 5] |= (1 << (uint32_t(aScriptCode) & 0x1f)); } // send a notification of any missing-scripts that have been // recorded, and clear the mMissingFonts set for re-use void Flush(); // forget any missing-scripts that have been recorded up to now; // called before discarding a recorder we no longer care about void Clear() { memset(&mMissingFonts, 0, sizeof(mMissingFonts)); } private: // Number of 32-bit words needed for the missing-script flags static const uint32_t kNumScriptBitsWords = ((MOZ_NUM_SCRIPT_CODES + 31) / 32); uint32_t mMissingFonts[kNumScriptBitsWords]; }; #endif
84bf197e0adec2da4de7f094c42c0057b661db9f
e27d9e460c374473e692f58013ca692934347ef1
/drafts/quickSpectrogram_2/libraries/liblsl/external/lslboost/mpl/aux_/preprocessed/bcc_pre590/apply_fwd.hpp
2f758bb48e8e06aaaade76cc9dd92d5b83351f2a
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
thoughtworksarts/Dual_Brains
84a0edf69d95299021daf4af9311aed5724a2e84
a7a6586b91a280950693b427d8269bd68bf8a7ab
refs/heads/master
2021-09-18T15:50:51.397078
2018-07-16T23:20:18
2018-07-16T23:20:18
119,759,649
3
0
null
2018-07-16T23:14:34
2018-02-01T00:09:16
HTML
UTF-8
C++
false
false
1,031
hpp
// Copyright Aleksey Gurtovoy 2000-2004 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.lslboost.org/LICENSE_1_0.txt) // // *Preprocessed* version of the main "apply_fwd.hpp" header // -- DO NOT modify by hand! namespace lslboost { namespace mpl { template< typename F, typename T1 = na, typename T2 = na, typename T3 = na , typename T4 = na, typename T5 = na > struct apply; template< typename F > struct apply0; template< typename F, typename T1 > struct apply1; template< typename F, typename T1, typename T2 > struct apply2; template< typename F, typename T1, typename T2, typename T3 > struct apply3; template< typename F, typename T1, typename T2, typename T3, typename T4 > struct apply4; template< typename F, typename T1, typename T2, typename T3, typename T4 , typename T5 > struct apply5; }}
7716a0c33392e49366584de1db59466c15959579
4c6d32f5413c8c249f68fcf0104f8379ebeae682
/PriorityQueue/queue.h
64009a6536e6e0c62d2dc20b1f250d53b7073392
[]
no_license
kamilkow1123/algorithms
f91dcc6e4edb784694274676fcff58784d76e994
fdbaf13d9b07b526be38b487ab826265fe1248ed
refs/heads/main
2023-06-02T21:50:28.361351
2021-06-15T11:38:42
2021-06-15T11:38:42
365,211,220
0
0
null
null
null
null
UTF-8
C++
false
false
497
h
#ifndef _QUEUE_H_ #define _QUEUE_H_ struct Edge{ int vertexStart; //starting vertex of the edge int vertexEnd; //ending vertex of the edge int weight; //weight of the edge }; class Queue{ private: Edge *heap; //heap with the edges int heapPosition; public: Queue(int); //constructor ~Queue(); // destructor Edge front(); //get the edge from the heap's root void push(Edge); //add new edge to the heap void pop(); //remove the root from the heap }; #endif
22fea79c045d243a6a284efe4c9e10c256de402f
7c82ece01341a445b10f5cccd1ff7c8614e1c5a2
/TP1_Concurrency/source/gestionEntree.cpp
bb6d08b75a9e745a888eae76f1b90f869eb6bc73
[ "MIT" ]
permissive
PaulEmmanuelSotir/TPs_3IF
87116bcf91d7f871f77bef26e35684f02c5ece87
51e1b82837bd2e9e01fe84721f127c469f1f24a7
refs/heads/master
2021-06-01T15:55:23.452046
2016-05-24T13:54:53
2016-05-24T13:54:53
43,512,483
0
0
null
null
null
null
UTF-8
C++
false
false
5,427
cpp
/************************************************************************* Gestion entree - tache gerant les barrieres d'entree ---------------------------------------------------- debut : 18/03/2016 binome : B3330 *************************************************************************/ //-- Realisaion de la tache <GESTION_ENTREE> (fichier gestionEntree.cpp) - ///////////////////////////////////////////////////////////////// INCLUDE //-------------------------------------------------------- Include système #include <unordered_map> #include <sys/wait.h> #include <sys/sem.h> #include <unistd.h> #include <utility> #include <string> #include <ctime> //------------------------------------------------------ Include personnel #include "gestionEntree.h" #include "process_utils.h" #include "clavier.h" #include "Outils.h" /////////////////////////////////////////////////////////////////// PRIVE namespace { //------------------------------------------------ Variables statiques //! On utilise des variables statiques plutot que automatiques pour qu'elles //! soient accessibles depuis les handlers de signaux car ce sont des lambdas //! qui ne peuvent rien capturer de leur contexte pour qu'elles puissent être //! castés en pointeur de fonction C. ipc_id_t car_message_queue_id; ipc_id_t sem_id; shared_mem<parking> parking_state; shared_mem<waiting_cars> waiting; shared_mem<places> parking_places; std::unordered_map<pid_t, car_info> car_parking_tasks; //-------------------------------------------------- Fonctions privées void quit_entree() { // On retire les handlers des signaux SIGCHLD et SIGUSR2 unsubscribe_handler<SIGCHLD, SIGUSR2>(); // On quitte tout les processus garant des voitures for (const auto& parking_task : car_parking_tasks) { if (parking_task.first > 0) { kill(parking_task.first, SIGUSR2); waitpid(parking_task.first, nullptr, 0); } } // Detache 'parking_state' de la memoire partagée detach_shared_memory(parking_state.data); detach_shared_memory(waiting.data); detach_shared_memory(parking_places.data); // On notifie la tache mère de la fin pour qu'elle quitte les autres taches kill(getppid(), SIGCHLD); exit(EXIT_SUCCESS); } } ////////////////////////////////////////////////////////////////// PUBLIC //----------------------------------------------------- Fonctions publique pid_t ActiverPorte(TypeBarriere type) { // Creation du processus fils return fork([type]() { // Fonction lambda aidant a quitter en cas d'erreur auto quit_if_failed = [](bool condition) { if (!condition) quit_entree(); }; // On ajoute un handler pour le signal SIGUSR2 indiquant que la tache doit se terminer quit_if_failed(handle<SIGUSR2>([](signal_t sig) { quit_entree(); })); // Ouverture de la message queue utilisée pour recevoir les voitures quit_if_failed(open_message_queue(car_message_queue_id, 1)); // Récuperation des semaphores sem_id = semget(ftok(".", 3), 4U, 0600); quit_if_failed(sem_id != -1); // Ouvre les memoires partagées parking_state = get_shared_memory<parking>(4); quit_if_failed(parking_state.data != nullptr); waiting = get_shared_memory<waiting_cars>(5); quit_if_failed(waiting.data != nullptr); parking_places = get_shared_memory<places>(6); quit_if_failed(parking_places.data != nullptr); // On ajoute un handler pour le signal SIGCHLD indiquant qu'une voiture s'est garée quit_if_failed(handle<SIGCHLD>([](signal_t sig) { int status; pid_t chld = waitpid(-1, &status, WNOHANG); if (chld > 0 && WIFEXITED(status)) { // On affiche la place et on met à jour la memoire partagée auto car = car_parking_tasks[chld]; auto place_num = WEXITSTATUS(status); lock(sem_id, 0, [&car, place_num]() { parking_places.data->places[place_num - 1] = car; }); car_parking_tasks.erase(chld); AfficherPlace(WEXITSTATUS(status), (TypeUsager)car.user_type, car.car_number, car.heure_arrivee); } })); // Phase moteur while (true) { // On attend la reception d'un message de la tache clavier car_incomming_msg message; quit_if_failed(read_message(car_message_queue_id, type, message)); DessinerVoitureBarriere(type, message.type_usager); AfficherRequete(type, message.type_usager, time(nullptr)); bool is_full = false; unsigned int next_car_id = 0; do { quit_if_failed(lock(sem_id, 0, [&message, type, &is_full, &next_car_id]() { // On vérifie que le parking n'est pas (de nouveau) plein avant de laisser passer la voiture is_full = parking_state.data->is_full(); if (!is_full) { next_car_id = parking_state.data->next_car_id++; parking_state.data->car_count++; } else waiting.data->waiting_fences[type - 1] = { message.type_usager, time(nullptr) }; })); if (is_full) // On attend qu'une place se libère sem_pv(sem_id, type, -1); } while (is_full); lock(sem_id, 0, [type]() { waiting.data->waiting_fences[type - 1] = { AUCUN, 0 }; }); // La barrière s'ouvre et on gare la voiture pid_t garage_pid = GarerVoiture(type); quit_if_failed(garage_pid); car_parking_tasks.emplace(garage_pid, car_info{ next_car_id, message.type_usager, time(nullptr) }); sleep(1); // Temps pour avancer... Effacer(static_cast<TypeZone>(REQUETE_R1 + type - 1)); } }); }
3980cbf4a6718fe44cb23816c5e6d833463b032d
04a21f3cf123bb04d27291348a4796770f5bd60c
/features/nanostack/FEATURE_NANOSTACK/sal-stack-nanostack/test/nanostack/unittest/Bootstraps/network_lib/network_libtest.cpp
2ba544b68805aa2d97f4b683708d56645d7ea434
[ "BSD-3-Clause", "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-unknown-license-reference" ]
permissive
Wenchou01/mbed-os
f946b291aa54cc2356633ac466df5ffed626baa9
70e7b40468854d33431889a9cd415364c00a2501
refs/heads/master
2021-08-20T09:09:26.038479
2017-11-27T16:37:40
2017-11-27T16:37:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
880
cpp
/* * Copyright (c) 2016, Arm Limited and affiliates. * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "CppUTest/TestHarness.h" #include "test_network_lib.h" TEST_GROUP(network_lib) { void setup() { } void teardown() { } }; TEST(network_lib, test_nwk_ready) { CHECK(test_nwk_ready()); }
fca76263084837507261d4f4b531c4e191e0cb6b
7d64e03e403eca85248677d8dc72751c93940e48
/test/leveldb/TestTxn.cpp
e3cab20387ccc8dc0d59b5c78d8aa21bd37dcdb0
[ "Apache-2.0" ]
permissive
webosce/db8
a6f6ec64d3cb8653dc522ee7a3e8fad78fcc0203
994da8732319c6cafc59778eec5f82186f73b6ab
refs/heads/webosce
2023-05-13T15:18:39.562208
2018-08-23T08:51:14
2018-09-14T13:30:43
145,513,369
0
1
Apache-2.0
2023-04-26T02:43:57
2018-08-21T05:52:45
C++
UTF-8
C++
false
false
3,934
cpp
// Copyright (c) 2013-2018 LG Electronics, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // SPDX-License-Identifier: Apache-2.0 /**************************************************************** * @file TestTxn.cpp ****************************************************************/ #include "engine/leveldb/MojDbLevelTxn.h" #include "Runner.h" #include "TestTxn.h" TEST_F(TestTxn, visibility) { initSample(); ttxn.begin(*db); initTxnSampleA(ttxn); std::string val; EXPECT_TRUE( ttxn.Get("0", val).IsNotFound() ); AssertLdbOk( ttxn.Get("a", val) ); EXPECT_EQ( "txn-0", val ); EXPECT_TRUE( ttxn.Get("b", val).IsNotFound() ); AssertLdbOk( ttxn.Get("c", val) ); EXPECT_EQ( "txn-1", val ); EXPECT_TRUE( ttxn.Get("ca", val).IsNotFound() ); AssertLdbOk( ttxn.Get("d", val) ); EXPECT_EQ( "txn-2", val ); EXPECT_TRUE( ttxn.Get("da", val).IsNotFound() ); EXPECT_TRUE( ttxn.Get("e", val).IsNotFound() ); AssertLdbOk( ttxn.Get("f", val) ); EXPECT_EQ( "txn-3", val ); AssertLdbOk( ttxn.Get("g", val) ); EXPECT_EQ( "db-3", val ); AssertLdbOk( ttxn.Get("h", val) ); EXPECT_EQ( "txn-4", val ); EXPECT_TRUE( ttxn.Get("i", val).IsNotFound() ); } TEST_F(TestTxn, dbIsolation) { initSample(); ttxn.begin(*db); initTxnSampleA(ttxn); std::string val; leveldb::ReadOptions ro; EXPECT_TRUE( db->Get(ro, "a", &val).IsNotFound() ); AssertLdbOk( db->Get(ro, "b", &val) ); EXPECT_EQ( "db-0", val ); EXPECT_TRUE( db->Get(ro, "c", &val).IsNotFound() ); AssertLdbOk( db->Get(ro, "d", &val) ); EXPECT_EQ( "db-1", val ); AssertLdbOk( db->Get(ro, "e", &val) ); EXPECT_EQ( "db-2", val ); EXPECT_TRUE( db->Get(ro, "f", &val).IsNotFound() ); AssertLdbOk( db->Get(ro, "g", &val) ); EXPECT_EQ( "db-3", val ); EXPECT_TRUE( db->Get(ro, "h", &val).IsNotFound() ); } TEST_F(TestTxn, txnIsolation) { initSample(); ttxn.begin(*db); initTxnSampleA(ttxn); MojDbLevelTableTxn ttxn2; ttxn2.begin(*db); std::string val; EXPECT_TRUE( ttxn2.Get("a", val).IsNotFound() ); AssertLdbOk( ttxn2.Get("b", val) ); EXPECT_EQ( "db-0", val ); EXPECT_TRUE( ttxn2.Get("c", val).IsNotFound() ); AssertLdbOk( ttxn2.Get("d", val) ); EXPECT_EQ( "db-1", val ); AssertLdbOk( ttxn2.Get("e", val) ); EXPECT_EQ( "db-2", val ); EXPECT_TRUE( ttxn2.Get("f", val).IsNotFound() ); AssertLdbOk( ttxn2.Get("g", val) ); EXPECT_EQ( "db-3", val ); EXPECT_TRUE( ttxn2.Get("h", val).IsNotFound() ); } TEST_F(TestTxn, commitVisibility) { initSample(); ttxn.begin(*db); initTxnSampleA(ttxn); ttxn.commitImpl(); std::string val; leveldb::ReadOptions ro; AssertLdbOk( db->Get(ro, "a", &val) ); EXPECT_EQ( "txn-0", val ); EXPECT_TRUE( db->Get(ro, "b", &val).IsNotFound() ); AssertLdbOk( db->Get(ro, "d", &val) ); EXPECT_EQ( "txn-2", val ); } TEST_F(TestTxn, snapshotTransparency) { std::string val; leveldb::ReadOptions ro; ASSERT_TRUE( db->Get(ro, "b", &val).IsNotFound() ); ttxn.begin(*db); ASSERT_TRUE( ttxn.Get("b", val).IsNotFound() ); initSample(); AssertLdbOk( db->Get(ro, "b", &val) ); EXPECT_EQ( "db-0", val ); // XXX: do we actually shouldn't use snapshot here? AssertLdbOk( ttxn.Get("b", val) ); EXPECT_EQ( "db-0", val ); }
0a2ebffbedff46ca3e8a7937b930c6fc35385b49
bb531c652b5b5b3e7c52931a383e983521903ca6
/library/src/cpp/jni/jvm_class.hpp
1247020b5b68bb542a8fb502d26d2646833eab3f
[ "MIT" ]
permissive
little-adam/libgdx-oboe
589ef888b5fe085d362a11eb98ab3869227a2d02
41831ecaf5b329ad5722421196c7b9d34f445def
refs/heads/master
2023-06-21T07:29:14.470860
2021-07-13T12:38:02
2021-07-13T12:38:02
284,658,057
1
1
MIT
2020-08-03T09:28:38
2020-08-03T09:28:38
null
UTF-8
C++
false
false
8,183
hpp
#pragma once #include "jni.h" #include "jvm_signature.hpp" #include "jni_context.hpp" #include "jvm_object.hpp" #include "../utility/log.hpp" #include "../utility/hash.hpp" #include <memory> #include <string_view> #include <type_traits> #include <unordered_map> class jvm_class { public: jvm_class(std::string_view class_name) : m_class_name(class_name) , m_class_name_hash(std::hash<std::string_view>()(class_name)) { auto it = g_class_cache.find(m_class_name_hash); if(it != g_class_cache.end()) { m_class = it->second; } else { #ifdef REPORT_UNCACHED_JNI warn("jvm_class: usage of uncached jclass \"{}\"", class_name); #endif auto context = jni_context::acquire_thread(); m_class = jvm_object(context->FindClass(class_name.data())); } } jvm_class(jclass cls) : m_class(cls) { auto context = jni_context::acquire_thread(); jclass cls_class = context->GetObjectClass(m_class); jmethodID get_name = context->GetMethodID(cls_class, "getName", "()Ljava/lang/String;"); jstring name = static_cast<jstring>(context->CallObjectMethod(m_class, get_name)); m_class_name = std::string{context->GetStringUTFChars(name, NULL)}; m_class_name_hash = std::hash<std::string>()(m_class_name); context->DeleteLocalRef(name); } template <class... Args> jobject construct(Args... args) { auto context = jni_context::acquire_thread(); auto constructor = find_method<void(Args...)>("<init>"); return context->NewObject(m_class, constructor, args...); } template <class F> jmethodID find_method(std::string_view name) { auto it = g_method_cache.find(gen_method_hash<F>(m_class_name, name)); if(it != g_method_cache.end()) { return it->second; } else { #ifdef REPORT_UNCACHED_JNI warn("jvm_class: usage of uncached jmethodID \"{}\" (class: \"{}\")", name, m_class_name); #endif auto context = jni_context::acquire_thread(); return context->GetMethodID(m_class, name.data(), jvm_signature<F>()); } } template <class F> jfieldID find_field(std::string_view name) { auto it = g_field_cache.find(gen_field_hash(m_class_name, name)); if(it != g_field_cache.end()) { return it->second; } else { #ifdef REPORT_UNCACHED_JNI warn("jvm_class: usage of uncached jfieldID \"{}\" (class: \"{}\")", name, m_class_name); #endif auto context = jni_context::acquire_thread(); return context->GetFieldID(m_class, name.data(), jvm_signature<F>()); } } template <class F> auto get_field(jobject obj, std::string_view name) { auto context = jni_context::acquire_thread(); auto field = find_field<F>(name); if constexpr (std::is_same<F, int>::value) return context->GetIntField(obj, field); else if constexpr (std::is_same<F, bool>::value) return context->GetBooleanField(obj, field); else if constexpr (std::is_same<F, char>::value) return context->GetCharField(obj, field); else if constexpr (std::is_same<F, short>::value) return context->GetShortField(obj, field); else if constexpr (std::is_same<F, long>::value) return context->GetLongField(obj, field); else if constexpr (std::is_same<F, float>::value) return context->GetFloatField(obj, field); else if constexpr (std::is_same<F, double>::value) return context->GetDoubleField(obj, field); else return static_cast<F>(context->GetObjectField(obj, field)); } template <class F, class... Args> auto execute_method(jobject obj, std::string_view name, Args... args) { using return_type = typename std::invoke_result<F, Args...>::type; auto context = jni_context::acquire_thread(); auto method = find_method<F>(name); if constexpr (std::is_same<return_type, int>::value) { return context->CallIntMethod(obj, method, args...); } else if constexpr (std::is_same<return_type, void>::value) { return context->CallVoidMethod(obj, method, args...); } else if constexpr (std::is_same<return_type, bool>::value) { return context->CallBooleanMethod(obj, method, args...); } else if constexpr (std::is_same<return_type, char>::value) { return context->CallCharMethod(obj, method, args...); } else if constexpr (std::is_same<return_type, short>::value) { return context->CallShortMethod(obj, method, args...); } else if constexpr (std::is_same<return_type, long>::value) { return context->CallLongMethod(obj, method, args...); } else if constexpr (std::is_same<return_type, float>::value) { return context->CallFloatMethod(obj, method, args...); } else if constexpr (std::is_same<return_type, double>::value) { return context->CallDoubleMethod(obj, method, args...); } else { return static_cast<return_type>(context->CallObjectMethod(obj, method, args...)); } } static void cache_class(std::string_view class_name) { auto context = jni_context::acquire_thread(); g_class_cache[std::hash<std::string_view>()(class_name)] = jvm_object(context->FindClass(class_name.data())); } template <class F> static void cache_field(std::string_view class_name, std::string_view field_name) { auto context = jni_context::acquire_thread(); std::size_t class_hash = std::hash<std::string_view>()(class_name); auto it = g_class_cache.find(class_hash); if(it != g_class_cache.end()) { g_field_cache[gen_field_hash(class_name, field_name)] = context->GetFieldID(it->second, field_name.data(), jvm_signature<F>()); } else { warn("jvm_class: caching field \"{}\" with uncached class \"{}\". Skipping...", field_name, class_name); } } template <class F> static void cache_method(std::string_view class_name, std::string_view method_name) { auto context = jni_context::acquire_thread(); std::size_t class_hash = std::hash<std::string_view>()(class_name); auto it = g_class_cache.find(class_hash); if(it != g_class_cache.end()) { g_method_cache[gen_method_hash<F>(class_name, method_name)] = context->GetMethodID(it->second, method_name.data(), jvm_signature<F>()); } else { warn("jvm_class: caching method \"{}\" with uncached class \"{}\". Skipping...", method_name, class_name); } } using class_cache_map = std::unordered_map<std::size_t, jvm_object<jclass>>; using field_cache_map = std::unordered_map<std::size_t, jfieldID>; using method_cache_map = std::unordered_map<std::size_t, jmethodID>; private: static class_cache_map g_class_cache; static field_cache_map g_field_cache; static method_cache_map g_method_cache; inline static std::size_t gen_field_hash(std::string_view class_name, std::string_view field_name) { return merge_hash(class_name, field_name); } template <class F> inline static std::size_t gen_method_hash(std::string_view class_name, std::string_view method_name) { return merge_hash(class_name, method_name, jvm_signature<F>()); } jvm_object<jclass> m_class; std::string m_class_name; std::size_t m_class_name_hash; };
270ab8bc626b48648e48e18f9efe2e22d19ee2b3
0afe55a089c38ef8e102ca3be18f8d971b2286ff
/main/Nodes.h
0efeed9cf8a0821b366dd2f942abf00582613ad2
[]
no_license
alading241/Neural-Network-Development-Kit
2f349c13d8e5e74861ec087a154bc450b992bcd5
8806e784072cf02edd83e403b334e574309e8321
refs/heads/main
2023-06-10T14:51:20.731244
2021-07-12T10:32:38
2021-07-12T10:32:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,966
h
#pragma once #include <cstddef> // for NULL #include <Eigen/Dense> #include <Eigen/Core> #include <math.h> struct Node { Eigen::MatrixXd value; //MatrixXd is class and value is an object, different from the python version,(pointer) Eigen::MatrixXd grad; Eigen::MatrixXd sub_grad; bool require_grad; bool need_update; bool BN; bool dot; bool test; }; class Nodes { public: Nodes* last_right; Nodes* last_left; Nodes* next; Node node; Nodes(void) { //root = &node; last_right = NULL; last_left = NULL; next = NULL; node.require_grad = true; node.need_update = false; node.BN = false; node.dot = false; node.test = false; } virtual ~Nodes(void) {} virtual void output_val() { } virtual void compute_gradient() { } }; class Input : public Nodes { public: //Node * root; //template <typename mat> Input(Eigen::MatrixXd input) { node.value = input; } ~Input(void) {} void output_val() { } void compute_gradient() { } }; class Const : public Nodes { public: Const(const Eigen::MatrixXd X) { node.value = X; node.require_grad = false; } ~Const() { } void output_val() { } void compute_gradient() { } }; class Variable : public Nodes { public: Variable(Eigen::MatrixXd X) { node.value = X; node.need_update = true; } ~Variable() { } void output_val() { } void compute_gradient() { } }; class Add : public Nodes { public: Add(Nodes* left_node, Nodes* right_node) { //left_node: class.root last_left = left_node; last_right = right_node; last_left->next = this; last_right->next = this; } ~Add() { } void output_val() { node.value = Eigen::MatrixXd::Zero(last_left->node.value.rows(), last_left->node.value.cols()); if ((last_left->node.value.rows() == last_right->node.value.rows()) && (last_left->node.value.cols() == last_right->node.value.cols())) { node.value = last_left->node.value + last_right->node.value; } else if ((last_left->node.value.cols() == last_right->node.value.cols())) { for (int i = 0; i < last_left->node.value.rows(); i++) { node.value.row(i) = last_left->node.value.row(i) + last_right->node.value; } } } void compute_gradient() { if (last_left->node.require_grad == true) { last_left->node.sub_grad = Eigen::MatrixXd::Ones(last_left->node.value.rows(), last_left->node.value.cols()); } if (last_right->node.require_grad == true) { last_right->node.sub_grad = Eigen::MatrixXd::Ones(last_left->node.value.rows(), last_left->node.value.cols()); //there is a trick here! the same as above } } }; class Dot : public Nodes { public: Dot(Nodes* left_node, Nodes* right_node) { node.dot = true; last_left = left_node; last_right = right_node; last_left->next = this; last_right->next = this; } ~Dot() { } void output_val() { if (last_left->node.value.cols() == last_right->node.value.rows()) node.value = last_left->node.value * last_right->node.value; } void compute_gradient() { if (last_left->node.require_grad) last_left->node.sub_grad = last_right->node.value.transpose(); if (last_right->node.require_grad) last_right->node.sub_grad = last_left->node.value.transpose(); } }; class Minus : public Nodes { public: Minus(Nodes* left_node, Nodes* right_node) { //left_node: class.root last_left = left_node; last_right = right_node; last_left->next = this; last_right->next = this; } ~Minus() { } void output_val() { node.value = Eigen::MatrixXd::Zero(last_left->node.value.rows(), last_left->node.value.cols()); if ((last_left->node.value.rows() == last_right->node.value.rows()) && (last_left->node.value.cols() == last_right->node.value.cols())) { node.value = last_left->node.value - last_right->node.value; } else if ((last_left->node.value.cols() == last_right->node.value.cols())) { for (int i = 0; i < last_left->node.value.rows(); i++) { node.value.row(i) = last_left->node.value.row(i) - last_right->node.value; } } } void compute_gradient() { if (last_left->node.require_grad == true) { last_left->node.sub_grad = Eigen::MatrixXd::Ones(last_left->node.value.rows(), last_left->node.value.cols()); } if (last_right->node.require_grad == true) { last_right->node.sub_grad = -1 * Eigen::MatrixXd::Ones(last_right->node.value.rows(), last_right->node.value.cols()); } } }; class F_Norm : public Nodes { public: F_Norm(Nodes* left_node) { last_left = left_node; last_left->next = this; } ~F_Norm() { } void output_val() { node.value = Eigen::MatrixXd::Zero(1, 1); double sum = 0; int r = last_left->node.value.rows(); int c = last_left->node.value.cols(); for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { sum += pow(last_left->node.value(i, j), 2); } } node.value << sum / r; } void compute_gradient() { if (last_left->node.require_grad) last_left->node.sub_grad = last_left->node.value + last_left->node.value; } }; //activation function class Sigmoid : public Nodes { public: Sigmoid(Nodes* left_node) { last_left = left_node; node.value = last_left->node.value; left_node->next = this; } ~Sigmoid() { } void output_val() { node.value = 1 / (1 + exp(-1 * last_left->node.value.array())); } void compute_gradient() { if (last_left->node.require_grad) last_left->node.sub_grad = (1 / (1 + exp(-1 * last_left->node.value.array()))).cwiseProduct(1 - 1 / (1 + exp(-1 * last_left->node.value.array()))); } }; class ReLu : public Nodes { public: ReLu(Nodes* left_node) { last_left = left_node; node.value = last_left->node.value; left_node->next = this; } ~ReLu() { } void output_val() { node.value = (last_left->node.value.cwiseAbs() + last_left->node.value) / 2; } void compute_gradient() { if (last_left->node.require_grad) { int row_num = last_left->node.value.rows(); int col_num = last_left->node.value.cols(); last_left->node.sub_grad = Eigen::MatrixXd::Zero(row_num, col_num); for (int r = 0; r < row_num; r++) { for (int c = 0; c < col_num; c++) { if (last_left->node.value(r, c) > 0) last_left->node.sub_grad(r, c) = 1; } } } } }; class Tanh : public Nodes { public: double k; Tanh(Nodes* left_node) { last_left = left_node; node.value = last_left->node.value; left_node->next = this; k = 6; } ~Tanh() { } void output_val() { node.value = (k * last_left->node.value.array().exp() - (-1 * k * last_left->node.value.array()).exp()) / (k * last_left->node.value.array().exp() + (-1 * k * last_left->node.value.array()).exp() + 1e-10); } void compute_gradient() { if (last_left->node.require_grad) { last_left->node.sub_grad = k * (1 - ((k * last_left->node.value.array().exp() - (-1 * k * last_left->node.value.array()).exp()) / (k * last_left->node.value.array().exp() + (-1 * k * last_left->node.value.array()).exp() + 1e-10)).cwiseAbs2()); } } }; class Lee_Osc : public Nodes { private: void get_table(double Lee[1001][100]) { int N = 600; // n = no.of time step default is 1000 //parameter for tanh function int a1 = 5, a2 = 5, b1 = 1, b2 = 1, eu = 0, ev = 0, c = 1; // default is 5 // default is 5 //u threshold default is 0 //v threshold defalut is 0 //Decay constant double k = 500, e = 0.02; int x = 0; //x index of Lee() double u = 0.2, v = 0, w = 0, z = 0.2; //double Lee[1001][100]; double tempu, tempv, sim, sign; for (double i = -1; i <= 1.001; i += 0.002) { sign = (i == 0) ? 0 : ((i > 0) ? 1 : -1); sim = i + 0.02 * sign; for (int t = 0; t < N - 1; t++) { tempu = a1 * u - a2 * v + sim - eu; tempv = b1 * u - b2 * v - ev; u = (exp(s * tempu) - exp((-1) * s * tempu)) / (exp(s * tempu) + exp((-1) * s * tempu)); v = (exp(s * tempv) - exp((-1) * s * tempv)) / (exp(s * tempv) + exp((-1) * s * tempv)); w = (exp(s * sim) - exp((-1) * s * sim)) / (exp(s * sim) + exp((-1) * s * sim)); z = ((u - v) * exp(-1 * k * sim * sim) + c * w); if (t >= 499) { Lee[x][t - 499] = z; } } x += 1; } } public: double Lee[1001][100], s; Lee_Osc(Nodes* left_node) { last_left = left_node; node.value = last_left->node.value; left_node->next = this; s = 4; get_table(Lee); } ~Lee_Osc() { } void output_val() { int r = last_left->node.value.rows(), c = last_left->node.value.cols(); node.value = Eigen::MatrixXd::Zero(r, c); for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { if (last_left->node.value(i, j) > 1) { node.value(i, j) = 1; } else if (last_left->node.value(i, j) < -1) { node.value(i, j) = -1; } else { int row_ind = floor((last_left->node.value(i, j) - (-1)) / 0.002) + 0; int col_ind = (rand() % (99 - 0 + 1)) + 0; node.value(i, j) = Lee[row_ind][col_ind]; } } } } void compute_gradient() { if (last_left->node.require_grad) { last_left->node.sub_grad = s * (1 - ((s * last_left->node.value.array().exp() - (-1 * s * last_left->node.value.array()).exp()) / (s * last_left->node.value.array().exp() + (-1 * s * last_left->node.value.array()).exp() + 1e-10)).cwiseAbs2()); } } }; class Lee_Osc2 : public Nodes { private: Eigen::MatrixXd x_pre; Eigen::MatrixXd x_post; Eigen::MatrixXd u; Eigen::MatrixXd u_pre; Eigen::MatrixXd u_post; Eigen::MatrixXd v; Eigen::MatrixXd v_pre; Eigen::MatrixXd v_post; Eigen::MatrixXd f_pre; Eigen::MatrixXd f_post; Eigen::MatrixXd w_pre; Eigen::MatrixXd w_post; Eigen::MatrixXd decay_pre; Eigen::MatrixXd decay_post; double s, delta_x = 0.001, k = 500; int a1 = 5, a2 = 5, b1 = 1, b2 = 1, eu = 0, ev = 0, c = 1; public: Lee_Osc2(Nodes* left_node) { last_left = left_node; node.value = last_left->node.value; x_pre = node.value.array() - 0.001; //finite difference x_post = node.value.array() + 0.001; w_pre = ((s * x_pre).array().exp() - ((-1) * s * x_pre).array().exp()) / ((s * x_pre).array().exp() + ((-1) * s * x_pre).array().exp()); w_post = ((s * x_post).array().exp() - ((-1) * s * x_post).array().exp()) / ((s * x_post).array().exp() + ((-1) * s * x_post).array().exp()); decay_pre = (-1 * k * x_pre.cwiseAbs2()).array().exp(); decay_post = (-1 * k * x_post.cwiseAbs2()).array().exp(); u = Eigen::MatrixXd::Zero(node.value.rows(), node.value.cols()); u_pre = u; u_post = u; v = u; v_pre = u; v_post = u; left_node->next = this; s = 6; } ~Lee_Osc2() { } void output_val() { //int r = last_left->node.value.rows(), c = last_left->node.value.cols(); Eigen::MatrixXd tempu = (a1 * u - a2 * v + last_left->node.value).array() - eu; Eigen::MatrixXd tempu_pre = (a1 * u_pre - a2 * v_pre + x_pre).array() - eu; Eigen::MatrixXd tempu_post = (a1 * u_post - a2 * v_post + x_post).array() - eu; Eigen::MatrixXd tempv = (b1 * u - b2 * v).array() - ev; Eigen::MatrixXd tempv_pre = (b1 * u_pre - b2 * v_pre + x_pre).array() - ev; Eigen::MatrixXd tempv_post = (b1 * u_post - b2 * v_post + x_post).array() - ev; Eigen::MatrixXd w; u = ((s * tempu).array().exp() - ((-1) * s * tempu).array().exp()) / ((s * tempu).array().exp() + ((-1) * s * tempu).array().exp()); u_pre = ((s * tempu_pre).array().exp() - ((-1) * s * tempu_pre).array().exp()) / ((s * tempu_pre).array().exp() + ((-1) * s * tempu_pre).array().exp()); u_post = ((s * tempu_post).array().exp() - ((-1) * s * tempu_post).array().exp()) / ((s * tempu_post).array().exp() + ((-1) * s * tempu_post).array().exp()); v = ((s * tempv).array().exp() - ((-1) * s * tempv).array().exp()) / ((s * tempv).array().exp() + ((-1) * s * tempv).array().exp()); v_pre = ((s * tempv_pre).array().exp() - ((-1) * s * tempv_pre).array().exp()) / ((s * tempv_pre).array().exp() + ((-1) * s * tempv_pre).array().exp()); v_post = ((s * tempv_post).array().exp() - ((-1) * s * tempv_post).array().exp()) / ((s * tempv_post).array().exp() + ((-1) * s * tempv_post).array().exp()); w = ((s * last_left->node.value).array().exp() - ((-1) * s * last_left->node.value).array().exp()) / ((s * last_left->node.value).array().exp() + ((-1) * s * last_left->node.value).array().exp()); node.value = (u - v).cwiseProduct((-1 * k * last_left->node.value.cwiseAbs2())).array().exp(); node.value += c * w; } void compute_gradient() { if (last_left->node.require_grad) { f_pre = (u_pre - v_pre).cwiseProduct(decay_pre); f_pre += c * w_pre; f_post = (u_post - v_post).cwiseProduct(decay_post); f_post += c * w_post; last_left->node.sub_grad = (f_post - f_pre) / (2 * delta_x); } } };
670f6204ff36942e4c7bca792c0bec73d7999cc5
f5d87ed79a91f17cdf2aee7bea7c15f5b5258c05
/cuts/Application_Task.h
dd5b726924cfd8bffc592e7d9977317c32346301
[]
no_license
SEDS/CUTS
a4449214a894e2b47bdea42090fa6cfc56befac8
0ad462fadcd3adefd91735aef6d87952022db2b7
refs/heads/master
2020-04-06T06:57:35.710601
2016-08-16T19:37:34
2016-08-16T19:37:34
25,653,522
0
3
null
null
null
null
UTF-8
C++
false
false
1,237
h
// -*- C++ -*- //============================================================================= /** * @file Application_Task.h * * $Id$ * * @author James H. Hill */ //============================================================================= #ifndef _CUTS_APPLICATION_TASK_H_ #define _CUTS_APPLICATION_TASK_H_ #include "Active_Object.h" #include "ace/Task.h" /** * @class CUTS_Application_Task * * Base class for periodic event generators. */ class CUTS_Export CUTS_Application_Task : public ACE_Task_Base, public CUTS_Active_Object { public: /// Default constructor. CUTS_Application_Task (void); /// Destructor. ~CUTS_Application_Task (void); /// Activate the periodic event. virtual int activate (void); /// Deactivate the periodic event. virtual int deactivate (void); /// Activation state getter bool is_active (void) const; /// Set the number of threads used with the task is activated. void nthreads (int n); /// Get number of threads for activation. int nthreads (void) const; private: int nthreads_; /// Activation flag bool active_; }; #if defined (__CUTS_INLINE__) #include "Application_Task.inl" #endif #endif // !defined _CUTS_APPLICATION_TASK_H_
f5d086d8620e4fadde2fb19899aa2b3ff2b56aec
0c69111b211f81ae559935a00ba6c727c2a0509d
/maxRecSize/maxRecSize/stdafx.cpp
971fefa7a779db9c24e4b6582133110d6dace274
[]
no_license
jinghao666/liCodeGit
b2ff5a703e59e357b0b0fed681ce93c2f5d6308e
ee94469bd58d2931fe9749fcd8b6b6962a534085
refs/heads/master
2020-06-14T12:09:08.825452
2015-12-18T09:32:17
2015-12-18T09:32:17
null
0
0
null
null
null
null
GB18030
C++
false
false
261
cpp
// stdafx.cpp : 只包括标准包含文件的源文件 // maxRecSize.pch 将作为预编译头 // stdafx.obj 将包含预编译类型信息 #include "stdafx.h" // TODO: 在 STDAFX.H 中引用任何所需的附加头文件, //而不是在此文件中引用
8dea709fe75d22043642ff304c8f663542c7fb2b
782e8b221d2d106a15a17e60e8620c7fed278429
/cachelib/navy/bighash/BigHash.h
7714d461d2b7ba3957a8ab93c855cbb09741e04a
[ "Apache-2.0" ]
permissive
ilkerhalil/CacheLib
d02985bba68af40c036fc12411efe317487c50de
d131b686ac135ea873dc4bb62e9133858eaad238
refs/heads/main
2023-08-18T07:39:27.272731
2021-09-11T02:49:48
2021-09-11T02:50:55
405,455,233
1
0
Apache-2.0
2021-09-11T18:33:55
2021-09-11T18:33:54
null
UTF-8
C++
false
false
7,948
h
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <folly/SharedMutex.h> #include <chrono> #include <stdexcept> #include "cachelib/common/AtomicCounter.h" #include "cachelib/common/BloomFilter.h" #include "cachelib/navy/bighash/Bucket.h" #include "cachelib/navy/common/Buffer.h" #include "cachelib/navy/common/Device.h" #include "cachelib/navy/common/Hash.h" #include "cachelib/navy/common/SizeDistribution.h" #include "cachelib/navy/common/Types.h" #include "cachelib/navy/engine/Engine.h" namespace facebook { namespace cachelib { namespace navy { // BigHash is a small item flash-based cache engine. It divides the device into // a series of buckets. One can think of it as a on-device hash table. // // Each item is hashed to a bucket according to its key. There is no size class, // and each bucket is consist of various variable-sized items. When full, we // evict the items in their insertion order. An eviction call back is guaranteed // to be invoked once per item. We currently do not support removeCB. That is // coming as part of Navy eventually. // // Each read and write via BigHash happens in `bucketSize` granularity. This // means, you will read a full bucket even if your item is only 100 bytes. // It's also the same for writes. This makes BigHash inherently unsuitable for // large items that will also need large buckets (several KB and above). // // However, this design gives us the ability to forgo an in-memory index and // instead look up our items directly from disk. In practice, this means BigHash // is a flash engine optimized for small items. class BigHash final : public Engine { public: struct Config { uint32_t bucketSize{4 * 1024}; // The range of device that BigHash will access is guaranteed to be // within [baseOffset, baseOffset + cacheSize) uint64_t cacheBaseOffset{}; uint64_t cacheSize{}; Device* device{nullptr}; DestructorCallback destructorCb; // Optional bloom filter to reduce IO std::unique_ptr<BloomFilter> bloomFilter; uint64_t numBuckets() const { return cacheSize / bucketSize; } Config& validate(); }; // Contructor can throw std::exception if config is invalid. // // @param config config that was validated with Config::validate // // @throw std::invalid_argument on bad config explicit BigHash(Config&& config); BigHash(const BigHash&) = delete; BigHash& operator=(const BigHash&) = delete; ~BigHash() override = default; // Check if the key could exist in bighash. This can be used as a pre-check // to optimize cache lookups to avoid calling lookups in an async IO // environment. // // @param hk key to be checked // // @return false if the key definitely does not exist and true if it could. bool couldExist(HashedKey hk) override; // Look up a key in BigHash. On success, it will return Status::Ok and // populate "value" with the value found. User should pass in a null // Buffer as "value" as any existing storage will be freed. If not found, // it will return Status::NotFound. And of course, on error, it returns // DeviceError. Status lookup(HashedKey hk, Buffer& value) override; // Inserts key and value into BigHash. This will replace an existing // key if found. If it failed to write, it will return DeviceError. Status insert(HashedKey hk, BufferView value) override; // Removes an entry from BigHash if found. Ok on success, NotFound on miss, // and DeviceError on error. Status remove(HashedKey hk) override; // flush the device file void flush() override; // reset BigHash, this clears the bloom filter and all stats // data is invalidated even it is not physically removed. void reset() override; // serialize BigHash state to a RecordWriter void persist(RecordWriter& rw) override; // deserialize BigHash state from a RecordReader // @return true if recovery succeed, false o/w. bool recover(RecordReader& rr) override; // returns BigHash stats to the visitor void getCounters(const CounterVisitor& visitor) const override; // return the maximum allowed item size uint64_t getMaxItemSize() const override; // return how manu times a lookup is rejected by the bloom filter uint64_t bfRejectCount() const { return bfRejectCount_.get(); } private: class BucketId { public: explicit BucketId(uint32_t idx) : idx_{idx} {} bool operator==(const BucketId& rhs) const noexcept { return idx_ == rhs.idx_; } bool operator!=(const BucketId& rhs) const noexcept { return !(*this == rhs); } uint32_t index() const noexcept { return idx_; } private: uint32_t idx_; }; struct ValidConfigTag {}; BigHash(Config&& config, ValidConfigTag); Buffer readBucket(BucketId bid); bool writeBucket(BucketId bid, Buffer buffer); // The corresponding r/w bucket lock must be held during the entire // duration of the read and write operations. For example, during write, // if write lock is dropped after a bucket is read from device, user // must re-acquire the write lock and re-read the bucket from device // again to ensure they have the newest content. Otherwise, one thread // could overwrite another's writes. // // In short, just hold the lock during the entire operation! folly::SharedMutex& getMutex(BucketId bid) const { return mutex_[bid.index() & (kNumMutexes - 1)]; } BucketId getBucketId(HashedKey hk) const { return BucketId{static_cast<uint32_t>(hk.keyHash() % numBuckets_)}; } uint64_t getBucketOffset(BucketId bid) const { return cacheBaseOffset_ + bucketSize_ * bid.index(); } double bfFalsePositivePct() const; void bfRebuild(BucketId bid, const Bucket* bucket); bool bfReject(BucketId bid, uint64_t keyHash) const; // Use birthday paradox to estimate number of mutexes given number of parallel // queries and desired probability of lock collision. static constexpr size_t kNumMutexes = 16 * 1024; // Serialization format version. Never 0. Versions < 10 reserved for testing. static constexpr uint32_t kFormatVersion = 10; const DestructorCallback destructorCb_{}; const uint64_t bucketSize_{}; const uint64_t cacheBaseOffset_{}; const uint64_t numBuckets_{}; std::unique_ptr<BloomFilter> bloomFilter_; std::chrono::nanoseconds generationTime_{}; Device& device_; std::unique_ptr<folly::SharedMutex[]> mutex_{ new folly::SharedMutex[kNumMutexes]}; mutable AtomicCounter itemCount_; mutable AtomicCounter insertCount_; mutable AtomicCounter succInsertCount_; mutable AtomicCounter lookupCount_; mutable AtomicCounter succLookupCount_; mutable AtomicCounter removeCount_; mutable AtomicCounter succRemoveCount_; mutable AtomicCounter evictionCount_; mutable AtomicCounter logicalWrittenCount_; mutable AtomicCounter physicalWrittenCount_; mutable AtomicCounter ioErrorCount_; mutable AtomicCounter bfFalsePositiveCount_; mutable AtomicCounter bfProbeCount_; mutable AtomicCounter bfRebuildCount_; mutable AtomicCounter bfRejectCount_; mutable AtomicCounter checksumErrorCount_; mutable SizeDistribution sizeDist_; mutable AtomicCounter usedSizeBytes_; static_assert((kNumMutexes & (kNumMutexes - 1)) == 0, "number of mutexes must be power of two"); }; } // namespace navy } // namespace cachelib } // namespace facebook
6638cafcd0db651cfb01eb6b865f61723269f247
8cb3e7bba90795458b1401a3e2f69056730ff8fa
/src/externals/voronota/src/modescommon/sequence_utilities.h
5c8e112738899ff9c47fd241dd5ac78d0826bc0b
[ "MIT" ]
permissive
merkys/libvoronota-perl
e508c5f219b1a25a38af70f93e8225030391631a
19fea22db5f4e6dc141d9a28c20c9ad6e9d5d568
refs/heads/master
2021-08-07T04:17:28.400440
2017-11-07T13:50:03
2017-11-07T13:50:03
104,230,406
0
0
null
null
null
null
UTF-8
C++
false
false
3,811
h
#ifndef SEQUENCE_UTILITIES_H_ #define SEQUENCE_UTILITIES_H_ #include <fstream> #include <sstream> #include "../auxiliaries/chain_residue_atom_descriptor.h" #include "../auxiliaries/residue_letters_coding.h" #include "../auxiliaries/pairwise_sequence_alignment.h" #include "../auxiliaries/residue_atoms_reference.h" namespace { class SequenceUtilities { public: static std::string read_sequence_from_stream(std::istream& input) { std::string result; while(input.good()) { std::string line; std::getline(input, line); if(!line.empty() && line[0]!='>') { std::istringstream sinput(line); while(sinput.good()) { std::string token; sinput >> token; for(std::size_t i=0;i<token.size();i++) { const char c=token[i]; if(c>='A' && c<='Z') { result.append(1, c); } else if(c>='a' && c<='z') { result.append(1, c-('a'-'A')); } } } } } return result; } static std::string read_sequence_from_file(const std::string& filename) { if(!filename.empty()) { std::ifstream finput(filename.c_str(), std::ios::in); return read_sequence_from_stream(finput); } else { return std::string(); } } template<typename T> static std::string convert_residue_sequence_container_to_string(const T& residue_sequence_container) { std::string seq; for(typename T::const_iterator it=residue_sequence_container.begin();it!=residue_sequence_container.end();++it) { seq+=auxiliaries::ResidueLettersCoding::convert_residue_code_big_to_small(it->resName); } return seq; } static std::map<auxiliaries::ChainResidueAtomDescriptor, int> construct_sequence_mapping(const std::vector<auxiliaries::ChainResidueAtomDescriptor>& residue_sequence_vector, const std::string& reference_sequence, const std::string& ref_seq_alignment_output_filename) { std::map<auxiliaries::ChainResidueAtomDescriptor, int> result; if(!residue_sequence_vector.empty() && !reference_sequence.empty()) { const std::string seq=convert_residue_sequence_container_to_string(residue_sequence_vector); if(residue_sequence_vector.size()==seq.size()) { const std::vector< std::pair<int, int> >& alignment=auxiliaries::PairwiseSequenceAlignment::construct_sequence_alignment(reference_sequence, seq, auxiliaries::PairwiseSequenceAlignment::SimpleScorer(10, -10, -11, -1), false, 0); for(std::size_t i=0;i<alignment.size();i++) { const std::pair<int, int>& p=alignment[i]; if(p.first>=0 && p.second>=0) { result[residue_sequence_vector.at(p.second)]=(p.first+1); } } if(!ref_seq_alignment_output_filename.empty()) { std::ofstream foutput(ref_seq_alignment_output_filename.c_str(), std::ios::out); if(foutput.good()) { auxiliaries::PairwiseSequenceAlignment::print_sequence_alignment(reference_sequence, seq, alignment, foutput); } } } } return result; } static double calculate_sequence_identity(const std::string& seq_a, const std::string& seq_b) { const std::size_t max_seq_size=std::max(seq_a.size(), seq_b.size()); if(max_seq_size>0) { int matches=0.0; const std::vector< std::pair<int, int> >& alignment=auxiliaries::PairwiseSequenceAlignment::construct_sequence_alignment(seq_a, seq_b, auxiliaries::PairwiseSequenceAlignment::SimpleScorer(10, -10, -11, -1), false, 0); for(std::size_t i=0;i<alignment.size();i++) { const std::pair<int, int>& p=alignment[i]; if(p.first>=0 && p.first<static_cast<int>(seq_a.size()) && p.second>=0 && p.second<static_cast<int>(seq_b.size()) && seq_a[p.first]==seq_b[p.second]) { matches++; } } return (static_cast<double>(matches)/static_cast<double>(max_seq_size)); } return 0.0; } }; } #endif /* SEQUENCE_UTILITIES_H_ */
95b97e8202719ad3b8c6787c46d96608e85dccba
7a310d01d1a4361fd06b40a74a2afc8ddc23b4d3
/src/SearchDialog.h
f011565544f854f4e61ea27f8c4892f0785ccc58
[]
no_license
plus7/DonutG
b6fec6111d25b60f9a9ae5798e0ab21bb2fa28f6
2d204c36f366d6162eaf02f4b2e1b8bc7b403f6b
refs/heads/master
2020-06-01T15:30:31.747022
2010-08-21T18:51:01
2010-08-21T18:51:01
767,753
1
2
null
null
null
null
SHIFT_JIS
C++
false
false
2,567
h
/** * @file SearchDialog.h * @brief 検索ダイアログ. */ #pragma once #include "resource.h" #include "MtlWin.h" class CSearchHistoryDialog : public CDialogImpl<CSearchHistoryDialog> { int m_nRetCode; public: int m_bUseHiFunction; CString m_strKeyWord; SYSTEMTIME m_sysTimeStart; SYSTEMTIME m_sysTimeEnd; BOOL m_bCheckDate; public: CSearchHistoryDialog() : m_nRetCode(0) { //日付指定コントロールを試用するための初期化 INITCOMMONCONTROLSEX icex; icex.dwSize = sizeof ( INITCOMMONCONTROLSEX ); icex.dwICC = ICC_DATE_CLASSES ; InitCommonControlsEx(&icex); //IE5.5以降の履歴用インターフェイスが使えるかチェック //TODO: Gecko化 CComPtr<IUrlHistoryStg2> pHistory; HRESULT hr = CoCreateInstance(CLSID_CUrlHistory, NULL, CLSCTX_INPROC_SERVER, IID_IUrlHistoryStg2, (void **) &pHistory); if ( FAILED(hr) ) { m_bUseHiFunction = FALSE; } else { m_bUseHiFunction = TRUE; } } public: enum { IDD = IDD_DIALOG_SEARCHHISTORY }; BEGIN_MSG_MAP(CSearchHistoryDialog) MESSAGE_HANDLER ( WM_INITDIALOG , OnInitDialog ) COMMAND_ID_HANDLER ( IDC_BTN_SEARCH, OnSearch ) COMMAND_ID_HANDLER ( IDC_BTN_CANCEL, OnCancel ) END_MSG_MAP() private: LRESULT OnSearch(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL & /*bHandled*/) { _GetData(); m_nRetCode = 1; EndDialog(m_nRetCode); return 0; } LRESULT OnCancel(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL & /*bHandled*/) { m_nRetCode = 0; EndDialog(m_nRetCode); return 0; } LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL & /*bHandled*/) { if (m_bUseHiFunction == FALSE) { CDateTimePickerCtrl dateStart = GetDlgItem(IDC_DATETIMEPICKER1); CDateTimePickerCtrl dateEnd = GetDlgItem(IDC_DATETIMEPICKER2); CButton btnCheck = GetDlgItem(IDC_CHECK_DATE); dateStart.EnableWindow(FALSE); dateEnd.EnableWindow(FALSE); btnCheck.EnableWindow(FALSE); } return 0; } void _GetData() { CDateTimePickerCtrl dateStart = GetDlgItem(IDC_DATETIMEPICKER1); CDateTimePickerCtrl dateEnd = GetDlgItem(IDC_DATETIMEPICKER2); CButton btnCheck = GetDlgItem(IDC_CHECK_DATE); CEdit edit = GetDlgItem(IDC_EDIT_KEYWORD); dateStart.GetSystemTime(&m_sysTimeStart); dateStart.GetSystemTime(&m_sysTimeEnd); m_bCheckDate = btnCheck.GetCheck() != 0/*? TRUE : FALSE*/; m_strKeyWord = MtlGetWindowText(edit.m_hWnd); } };
37cacb0f4a31d7e08b93a03f21864422775ee09e
06e0aa85d3ec79d8770ba1fb978d681f353b31cd
/code-visualization/mainwindow.cpp
4fd57ec4cba83dbe9e734b1b807e0cf4d46c9a08
[]
no_license
karticsubr/FAS2016
b84e6cf5be4cc9e0e1659859181050db078d87a1
521d32f2a811f58c30c72abbdfbfb48b6eb1bcf6
refs/heads/master
2021-01-24T11:06:21.663493
2017-02-03T02:31:03
2017-02-03T02:31:03
51,309,085
0
0
null
null
null
null
UTF-8
C++
false
false
12,514
cpp
/*************************************************************************** ** ** ** QCustomPlot, an easy to use, modern plotting widget for Qt ** ** Copyright (C) 2011, 2012, 2013, 2014 Emanuel Eichhammer ** ** ** ** This program 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. ** ** ** ** 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 General Public License for more details. ** ** ** ** You should have received a copy of the GNU General Public License ** ** along with this program. If not, see http://www.gnu.org/licenses/. ** ** ** **************************************************************************** ** Author: Emanuel Eichhammer ** ** Website/Contact: http://www.qcustomplot.com/ ** ** Date: 07.04.14 ** ** Version: 1.2.1 ** ****************************************************************************/ /*** Edited by Gurprit Singh ***/ #include "mainwindow.h" #include "ui_mainwindow.h" #include <QDebug> #include <QDesktopWidget> #include <QScreen> #include <QMessageBox> #include <QMetaEnum> #include <QImage> #include <sstream> #include <iomanip> MainWindow::MainWindow(QString &outfile, std::vector<double> &data, std::string pattern, int N, int demoIndex, double ptRadius, bool gridVisualize, double *domain, QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); setupDemo(outfile, data, pattern, N, demoIndex, ptRadius, gridVisualize, domain); } void MainWindow::setupDemo(QString &outfile, std::vector<double> &data, std::string pattern, int N, int demoIndex, double ptRadius, bool gridVisualize, double* domain) { switch (demoIndex){ case 0: showPointsDemo(outfile, data, pattern, N, ui->customPlot, ptRadius, gridVisualize, domain); break; case 1: setupRadialSpectrumDemo(outfile, data, pattern, N, ui->customPlot, gridVisualize); break; } setWindowTitle("Plot: "+demoName); statusBar()->clearMessage(); currentDemoIndex = demoIndex; ui->customPlot->replot(); } void MainWindow::setupRadialSpectrumDemo(QString &outfile, std::vector<double> &data, std::string pattern, int N, QCustomPlot *customPlot, bool gridVisualize){ setGeometry(50, 50, 1024, 512); demoName = "radial-spectrum"; // generate some data: int dataSize = data.size() * 0.5; QVector<double> x(dataSize-1), y(dataSize-1); // initialize with entries 0..100 std::cerr << "datasize:" << N << std::endl; for (int i=1; i<dataSize; ++i) { //x[i-1] = data[2*i]*(1/(sqrt(2*nSamples))); if(pattern == "ccvt") x[i-1] = data[2*i]*(1/(0.875*sqrt(N))); else if(pattern == "poissondisk" || pattern == "dartthrowing") x[i-1] = data[2*i]*(1/(0.908*sqrt(N))); else if(pattern == "bnot" || pattern == "step") x[i-1] = data[2*i]*(1/(0.908*sqrt(N))); else if(pattern == "jitter") x[i-1] = data[2*i]*(1/(sqrt(N))); else if(pattern == "multijitter") x[i-1] = data[2*i]*(1/(sqrt(N))); else if(pattern == "uniformjitter") x[i-1] = data[2*i]*(1/(sqrt(N))); else if(pattern == "nrooks") x[i-1] = data[2*i]*(1/(sqrt(N))); else if(pattern == "random") x[i-1] = data[2*i]*(1/(sqrt(N))); else if(pattern == "regular") x[i-1] = data[2*i]*(1/(sqrt(N))); else if(pattern == "halton") x[i-1] = data[2*i]*(1/(sqrt(N))); else if(pattern == "hammerslay") x[i-1] = data[2*i]*(1/(0.55*sqrt(N))); else{ std::cerr << "Requested sampling pattern not available !!!" << std::endl; exit(-2); } y[i-1] = data[2*i+1]; } // create graph and assign data to it: customPlot->addGraph(); customPlot->graph(0)->setData(x, y); customPlot->graph(0)->setPen(QPen(QColor(120, 120, 220), 1)); customPlot->graph(0)->setBrush(QColor(20, 20, 220, 10)); customPlot->graph(0)->setChannelFillGraph(customPlot->graph(0)); customPlot->xAxis->setLabelFont(QFont( "Helvetica", 20)); customPlot->yAxis->setLabelFont(QFont( "Helvetica", 20)); // give the axes some labels: customPlot->xAxis->setLabel("Frequency"); customPlot->yAxis->setLabel("Power"); // set axes ranges, so we see all data: customPlot->rescaleAxes(true); customPlot->xAxis->setRange(0,4); //customPlot->xAxis->setRange(0,2.25); customPlot->xAxis->setAutoTickStep(false); customPlot->xAxis->setTickStep(1.0); customPlot->xAxis->setAutoSubTicks(false); customPlot->xAxis->grid()->setVisible(gridVisualize); customPlot->yAxis->setRange(0.0,2.0); customPlot->yAxis->setAutoTickStep(false); customPlot->yAxis->setTickStep(1.0); customPlot->yAxis->grid()->setVisible(gridVisualize); customPlot->setInteraction(QCP::iRangeDrag, true); customPlot->setInteraction(QCP::iRangeZoom, true); //std::cerr << outfile.toStdString() << std::endl; customPlot->savePdf(outfile,true, 512,256); } void MainWindow::showPointsDemo(QString &outfile, std::vector<double> &samples, std::string samplingpattern, int N, QCustomPlot *customPlot, double ptRadius, bool gridVisualize, double *domain){ setGeometry(50, 50, 768, 768); demoName = "Point set"; double minDomainX = domain[0]; double minDomainY = domain[1]; double maxDomainX = domain[2]; double maxDomainY = domain[3]; double maxRangeX = domain[2] - domain[0]; double maxRangeY = domain[3] - domain[1]; // generate some data: int dataSize = samples.size() * 0.5; QVector<double> x(dataSize), y(dataSize); // initialize with entries 0..100 customPlot->addGraph(); customPlot->graph()->setPen(QColor(85,107,47, 255)); customPlot->graph()->setLineStyle(QCPGraph::lsNone); customPlot->graph()->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssDisc, ptRadius)); for (int i=0; i<dataSize; ++i) { x[i] = samples[2*i+0]; y[i] = samples[2*i+1]; } double strataLength = 1.0; double subStrataLength = 1.0; // if(samplingpattern == "jitter" || samplingpattern == "uniformjitter" || samplingpattern == "regular"){ // strataLength = maxRangeX / sqrt(N); // subStrataLength = strataLength; // } // else if(samplingpattern == "multijitter" || samplingpattern == "nrooks"){ strataLength = maxRangeX / sqrt(N); subStrataLength = maxRangeX / (N); // } std::cerr << strataLength << " " << subStrataLength << " "<< sqrt(N) << " " << N << std::endl; customPlot->graph()->setData(x, y); customPlot->graph()->rescaleAxes(true); ///Overlay Dots at the center of the disc visualization of points customPlot->addGraph(); customPlot->graph(1)->setData(x, y); customPlot->graph(1)->rescaleAxes(true); customPlot->graph(1)->setPen(QColor(0,0,0, 255)); customPlot->graph(1)->setLineStyle(QCPGraph::lsNone); customPlot->graph(1)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssDisc, 0.5)); customPlot->xAxis->setRange(minDomainX,maxDomainX); QPen strataPen, subStrataPen; strataPen.setColor(Qt::black); subStrataPen.setColor(Qt::gray); subStrataPen.setStyle(Qt::DashLine); customPlot->xAxis->setRange(minDomainX,maxDomainX); customPlot->xAxis->grid()->setPen(strataPen); customPlot->xAxis->grid()->setSubGridPen(subStrataPen); customPlot->xAxis->setAutoTickStep(false); customPlot->xAxis->setAutoSubTicks(false); customPlot->xAxis->setTicks(false); customPlot->xAxis->setTickStep(strataLength); customPlot->xAxis->setSubTickCount(sqrt(N)-1); // customPlot->xAxis->setSubTickLength(subStrataLength);// customPlot->xAxis->grid()->setVisible(gridVisualize); customPlot->xAxis->grid()->setSubGridVisible(gridVisualize); customPlot->yAxis->setRange(minDomainY,maxDomainY); customPlot->yAxis->grid()->setPen(strataPen); customPlot->yAxis->grid()->setSubGridPen(subStrataPen); customPlot->yAxis->setAutoTickStep(false); customPlot->yAxis->setAutoSubTicks(false); customPlot->yAxis->setTicks(false); customPlot->yAxis->setTickStep(strataLength); customPlot->yAxis->setTickLength(strataLength); customPlot->yAxis->setSubTickCount(sqrt(N)-1); // customPlot->yAxis->setSubTickLength(subStrataLength);// customPlot->yAxis->grid()->setVisible(gridVisualize); customPlot->yAxis->grid()->setSubGridVisible(gridVisualize); customPlot->xAxis2->setRange(minDomainY,maxDomainY); customPlot->yAxis2->setRange(minDomainY,maxDomainY); customPlot->xAxis2->setAutoTickStep(false); customPlot->xAxis2->setAutoSubTicks(false); customPlot->xAxis2->setTicks(false); customPlot->yAxis2->setAutoTickStep(false); customPlot->yAxis2->setAutoSubTicks(false); customPlot->yAxis2->setTicks(false); customPlot->xAxis->setVisible(gridVisualize); customPlot->yAxis->setVisible(gridVisualize); customPlot->xAxis2->setVisible(gridVisualize); customPlot->yAxis2->setVisible(gridVisualize); // customPlot->xAxis2->grid()->setVisible(true); // customPlot->yAxis2->grid()->setVisible(true); // customPlot->xAxis2->grid()->setPen(strataPen); // customPlot->xAxis2->grid()->setSubGridPen(subStrataPen); // customPlot->xAxis2->setTickLength(strataLength); // customPlot->xAxis2->setSubTickLength(subStrataLength); // customPlot->xAxis2->grid()->setVisible(gridVisualize); // customPlot->xAxis2->grid()->setSubGridVisible(true); // customPlot->xAxis2->setTicks(false); // customPlot->yAxis2->grid()->setPen(strataPen); // customPlot->yAxis2->grid()->setSubGridPen(subStrataPen); // customPlot->yAxis2->setTickLength(strataLength); // customPlot->yAxis2->setSubTickLength(subStrataLength); // customPlot->yAxis2->grid()->setVisible(gridVisualize); // customPlot->yAxis2->grid()->setSubGridVisible(true); // customPlot->yAxis2->setTicks(false); // customPlot->xAxis->setAutoTickStep(false); // customPlot->xAxis->setTickStep(subStrataLength); // customPlot->xAxis->setVisible(gridVisualize); // customPlot->xAxis->grid()->setVisible(gridVisualize); //Make the top and right axes visible. // customPlot->xAxis2->setVisible(gridVisualize); // customPlot->xAxis2->setTicks(false); //customPlot->xAxis2->setRange(minDomainY,maxDomainY); //customPlot->xAxis2->setAutoTickStep(false); //customPlot->xAxis2->setTickStep(1.0); //customPlot->xAxis2->setTickLabels(false); // customPlot->yAxis->setAutoTickStep(false); // customPlot->yAxis->setTickStep(subStrataLength); // //customPlot->yAxis->setLabel("Real"); // customPlot->yAxis->setVisible(gridVisualize); // customPlot->yAxis->grid()->setVisible(gridVisualize); // customPlot->yAxis->setTickLabels(false); // customPlot->yAxis->setTicks(false); // customPlot->yAxis->setSelectedLabelColor(QColor(1,1,1)); // customPlot->yAxis2->setVisible(gridVisualize); // customPlot->yAxis2->setTicks(false); //// customPlot->yAxis2->setRange(0,range); //// customPlot->yAxis2->setAutoTickStep(false); //// //customPlot->yAxis2->setTickStep(1.0); //// customPlot->yAxis2->setTickLabels(false); customPlot->setInteraction(QCP::iRangeDrag, true); customPlot->setInteraction(QCP::iRangeZoom, true); customPlot->savePdf(outfile,true, 512,512); }
86ad016b5a5a1e5c8960c3e2478e23dd540d11c4
0f23651b08fd5a8ce21b9e78e39e61618996073b
/tools/clang/lib/Sema/SemaOpenMP.cpp
63ef808b3cc5f756a80bc85a68d1698a916be6f3
[ "NCSA" ]
permissive
arcosuc3m/clang-contracts
3983773f15872514f7b6ae72d7fea232864d7e3d
99446829e2cd96116e4dce9496f88cc7df1dbe80
refs/heads/master
2021-07-04T03:24:03.156444
2018-12-12T11:41:18
2018-12-12T12:56:08
118,155,058
31
1
null
null
null
null
UTF-8
C++
false
false
497,874
cpp
//===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// \file /// \brief This file implements semantic analysis for OpenMP directives and /// clauses. /// //===----------------------------------------------------------------------===// #include "TreeTransform.h" #include "clang/AST/ASTContext.h" #include "clang/AST/ASTMutationListener.h" #include "clang/AST/CXXInheritance.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclCXX.h" #include "clang/AST/DeclOpenMP.h" #include "clang/AST/StmtCXX.h" #include "clang/AST/StmtOpenMP.h" #include "clang/AST/StmtVisitor.h" #include "clang/Basic/OpenMPKinds.h" #include "clang/Sema/Initialization.h" #include "clang/Sema/Lookup.h" #include "clang/Sema/Scope.h" #include "clang/Sema/ScopeInfo.h" #include "clang/Sema/SemaInternal.h" #include "llvm/ADT/PointerEmbeddedInt.h" using namespace clang; //===----------------------------------------------------------------------===// // Stack of data-sharing attributes for variables //===----------------------------------------------------------------------===// static Expr *CheckMapClauseExpressionBase( Sema &SemaRef, Expr *E, OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents, OpenMPClauseKind CKind); namespace { /// \brief Default data sharing attributes, which can be applied to directive. enum DefaultDataSharingAttributes { DSA_unspecified = 0, /// \brief Data sharing attribute not specified. DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'. DSA_shared = 1 << 1 /// \brief Default data sharing attribute 'shared'. }; /// \brief Stack for tracking declarations used in OpenMP directives and /// clauses and their data-sharing attributes. class DSAStackTy final { public: struct DSAVarData final { OpenMPDirectiveKind DKind = OMPD_unknown; OpenMPClauseKind CKind = OMPC_unknown; Expr *RefExpr = nullptr; DeclRefExpr *PrivateCopy = nullptr; SourceLocation ImplicitDSALoc; DSAVarData() = default; DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, Expr *RefExpr, DeclRefExpr *PrivateCopy, SourceLocation ImplicitDSALoc) : DKind(DKind), CKind(CKind), RefExpr(RefExpr), PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc) {} }; typedef llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4> OperatorOffsetTy; private: struct DSAInfo final { OpenMPClauseKind Attributes = OMPC_unknown; /// Pointer to a reference expression and a flag which shows that the /// variable is marked as lastprivate(true) or not (false). llvm::PointerIntPair<Expr *, 1, bool> RefExpr; DeclRefExpr *PrivateCopy = nullptr; }; typedef llvm::DenseMap<ValueDecl *, DSAInfo> DeclSAMapTy; typedef llvm::DenseMap<ValueDecl *, Expr *> AlignedMapTy; typedef std::pair<unsigned, VarDecl *> LCDeclInfo; typedef llvm::DenseMap<ValueDecl *, LCDeclInfo> LoopControlVariablesMapTy; /// Struct that associates a component with the clause kind where they are /// found. struct MappedExprComponentTy { OMPClauseMappableExprCommon::MappableExprComponentLists Components; OpenMPClauseKind Kind = OMPC_unknown; }; typedef llvm::DenseMap<ValueDecl *, MappedExprComponentTy> MappedExprComponentsTy; typedef llvm::StringMap<std::pair<OMPCriticalDirective *, llvm::APSInt>> CriticalsWithHintsTy; typedef llvm::DenseMap<OMPDependClause *, OperatorOffsetTy> DoacrossDependMapTy; struct ReductionData { typedef llvm::PointerEmbeddedInt<BinaryOperatorKind, 16> BOKPtrType; SourceRange ReductionRange; llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp; ReductionData() = default; void set(BinaryOperatorKind BO, SourceRange RR) { ReductionRange = RR; ReductionOp = BO; } void set(const Expr *RefExpr, SourceRange RR) { ReductionRange = RR; ReductionOp = RefExpr; } }; typedef llvm::DenseMap<ValueDecl *, ReductionData> DeclReductionMapTy; struct SharingMapTy final { DeclSAMapTy SharingMap; DeclReductionMapTy ReductionMap; AlignedMapTy AlignedMap; MappedExprComponentsTy MappedExprComponents; LoopControlVariablesMapTy LCVMap; DefaultDataSharingAttributes DefaultAttr = DSA_unspecified; SourceLocation DefaultAttrLoc; OpenMPDirectiveKind Directive = OMPD_unknown; DeclarationNameInfo DirectiveName; Scope *CurScope = nullptr; SourceLocation ConstructLoc; /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to /// get the data (loop counters etc.) about enclosing loop-based construct. /// This data is required during codegen. DoacrossDependMapTy DoacrossDepends; /// \brief first argument (Expr *) contains optional argument of the /// 'ordered' clause, the second one is true if the regions has 'ordered' /// clause, false otherwise. llvm::PointerIntPair<Expr *, 1, bool> OrderedRegion; bool NowaitRegion = false; bool CancelRegion = false; unsigned AssociatedLoops = 1; SourceLocation InnerTeamsRegionLoc; /// Reference to the taskgroup task_reduction reference expression. Expr *TaskgroupReductionRef = nullptr; SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name, Scope *CurScope, SourceLocation Loc) : Directive(DKind), DirectiveName(Name), CurScope(CurScope), ConstructLoc(Loc) {} SharingMapTy() = default; }; typedef SmallVector<SharingMapTy, 4> StackTy; /// \brief Stack of used declaration and their data-sharing attributes. DeclSAMapTy Threadprivates; const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr; SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack; /// \brief true, if check for DSA must be from parent directive, false, if /// from current directive. OpenMPClauseKind ClauseKindMode = OMPC_unknown; Sema &SemaRef; bool ForceCapturing = false; CriticalsWithHintsTy Criticals; typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator; DSAVarData getDSA(StackTy::reverse_iterator &Iter, ValueDecl *D); /// \brief Checks if the variable is a local for OpenMP region. bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter); bool isStackEmpty() const { return Stack.empty() || Stack.back().second != CurrentNonCapturingFunctionScope || Stack.back().first.empty(); } public: explicit DSAStackTy(Sema &S) : SemaRef(S) {} bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; } void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; } bool isForceVarCapturing() const { return ForceCapturing; } void setForceVarCapturing(bool V) { ForceCapturing = V; } void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName, Scope *CurScope, SourceLocation Loc) { if (Stack.empty() || Stack.back().second != CurrentNonCapturingFunctionScope) Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope); Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc); Stack.back().first.back().DefaultAttrLoc = Loc; } void pop() { assert(!Stack.back().first.empty() && "Data-sharing attributes stack is empty!"); Stack.back().first.pop_back(); } /// Start new OpenMP region stack in new non-capturing function. void pushFunction() { const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction(); assert(!isa<CapturingScopeInfo>(CurFnScope)); CurrentNonCapturingFunctionScope = CurFnScope; } /// Pop region stack for non-capturing function. void popFunction(const FunctionScopeInfo *OldFSI) { if (!Stack.empty() && Stack.back().second == OldFSI) { assert(Stack.back().first.empty()); Stack.pop_back(); } CurrentNonCapturingFunctionScope = nullptr; for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) { if (!isa<CapturingScopeInfo>(FSI)) { CurrentNonCapturingFunctionScope = FSI; break; } } } void addCriticalWithHint(OMPCriticalDirective *D, llvm::APSInt Hint) { Criticals[D->getDirectiveName().getAsString()] = std::make_pair(D, Hint); } const std::pair<OMPCriticalDirective *, llvm::APSInt> getCriticalWithHint(const DeclarationNameInfo &Name) const { auto I = Criticals.find(Name.getAsString()); if (I != Criticals.end()) return I->second; return std::make_pair(nullptr, llvm::APSInt()); } /// \brief If 'aligned' declaration for given variable \a D was not seen yet, /// add it and return NULL; otherwise return previous occurrence's expression /// for diagnostics. Expr *addUniqueAligned(ValueDecl *D, Expr *NewDE); /// \brief Register specified variable as loop control variable. void addLoopControlVariable(ValueDecl *D, VarDecl *Capture); /// \brief Check if the specified variable is a loop control variable for /// current region. /// \return The index of the loop control variable in the list of associated /// for-loops (from outer to inner). LCDeclInfo isLoopControlVariable(ValueDecl *D); /// \brief Check if the specified variable is a loop control variable for /// parent region. /// \return The index of the loop control variable in the list of associated /// for-loops (from outer to inner). LCDeclInfo isParentLoopControlVariable(ValueDecl *D); /// \brief Get the loop control variable for the I-th loop (or nullptr) in /// parent directive. ValueDecl *getParentLoopControlVariable(unsigned I); /// \brief Adds explicit data sharing attribute to the specified declaration. void addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A, DeclRefExpr *PrivateCopy = nullptr); /// Adds additional information for the reduction items with the reduction id /// represented as an operator. void addTaskgroupReductionData(ValueDecl *D, SourceRange SR, BinaryOperatorKind BOK); /// Adds additional information for the reduction items with the reduction id /// represented as reduction identifier. void addTaskgroupReductionData(ValueDecl *D, SourceRange SR, const Expr *ReductionRef); /// Returns the location and reduction operation from the innermost parent /// region for the given \p D. DSAVarData getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK, Expr *&TaskgroupDescriptor); /// Returns the location and reduction operation from the innermost parent /// region for the given \p D. DSAVarData getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef, Expr *&TaskgroupDescriptor); /// Return reduction reference expression for the current taskgroup. Expr *getTaskgroupReductionRef() const { assert(Stack.back().first.back().Directive == OMPD_taskgroup && "taskgroup reference expression requested for non taskgroup " "directive."); return Stack.back().first.back().TaskgroupReductionRef; } /// Checks if the given \p VD declaration is actually a taskgroup reduction /// descriptor variable at the \p Level of OpenMP regions. bool isTaskgroupReductionRef(ValueDecl *VD, unsigned Level) const { return Stack.back().first[Level].TaskgroupReductionRef && cast<DeclRefExpr>(Stack.back().first[Level].TaskgroupReductionRef) ->getDecl() == VD; } /// \brief Returns data sharing attributes from top of the stack for the /// specified declaration. DSAVarData getTopDSA(ValueDecl *D, bool FromParent); /// \brief Returns data-sharing attributes for the specified declaration. DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent); /// \brief Checks if the specified variables has data-sharing attributes which /// match specified \a CPred predicate in any directive which matches \a DPred /// predicate. DSAVarData hasDSA(ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, bool FromParent); /// \brief Checks if the specified variables has data-sharing attributes which /// match specified \a CPred predicate in any innermost directive which /// matches \a DPred predicate. DSAVarData hasInnermostDSA(ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, bool FromParent); /// \brief Checks if the specified variables has explicit data-sharing /// attributes which match specified \a CPred predicate at the specified /// OpenMP region. bool hasExplicitDSA(ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, unsigned Level, bool NotLastprivate = false); /// \brief Returns true if the directive at level \Level matches in the /// specified \a DPred predicate. bool hasExplicitDirective( const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, unsigned Level); /// \brief Finds a directive which matches specified \a DPred predicate. bool hasDirective(const llvm::function_ref<bool(OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)> &DPred, bool FromParent); /// \brief Returns currently analyzed directive. OpenMPDirectiveKind getCurrentDirective() const { return isStackEmpty() ? OMPD_unknown : Stack.back().first.back().Directive; } /// \brief Returns parent directive. OpenMPDirectiveKind getParentDirective() const { if (isStackEmpty() || Stack.back().first.size() == 1) return OMPD_unknown; return std::next(Stack.back().first.rbegin())->Directive; } /// \brief Set default data sharing attribute to none. void setDefaultDSANone(SourceLocation Loc) { assert(!isStackEmpty()); Stack.back().first.back().DefaultAttr = DSA_none; Stack.back().first.back().DefaultAttrLoc = Loc; } /// \brief Set default data sharing attribute to shared. void setDefaultDSAShared(SourceLocation Loc) { assert(!isStackEmpty()); Stack.back().first.back().DefaultAttr = DSA_shared; Stack.back().first.back().DefaultAttrLoc = Loc; } DefaultDataSharingAttributes getDefaultDSA() const { return isStackEmpty() ? DSA_unspecified : Stack.back().first.back().DefaultAttr; } SourceLocation getDefaultDSALocation() const { return isStackEmpty() ? SourceLocation() : Stack.back().first.back().DefaultAttrLoc; } /// \brief Checks if the specified variable is a threadprivate. bool isThreadPrivate(VarDecl *D) { DSAVarData DVar = getTopDSA(D, false); return isOpenMPThreadPrivate(DVar.CKind); } /// \brief Marks current region as ordered (it has an 'ordered' clause). void setOrderedRegion(bool IsOrdered, Expr *Param) { assert(!isStackEmpty()); Stack.back().first.back().OrderedRegion.setInt(IsOrdered); Stack.back().first.back().OrderedRegion.setPointer(Param); } /// \brief Returns true, if parent region is ordered (has associated /// 'ordered' clause), false - otherwise. bool isParentOrderedRegion() const { if (isStackEmpty() || Stack.back().first.size() == 1) return false; return std::next(Stack.back().first.rbegin())->OrderedRegion.getInt(); } /// \brief Returns optional parameter for the ordered region. Expr *getParentOrderedRegionParam() const { if (isStackEmpty() || Stack.back().first.size() == 1) return nullptr; return std::next(Stack.back().first.rbegin())->OrderedRegion.getPointer(); } /// \brief Marks current region as nowait (it has a 'nowait' clause). void setNowaitRegion(bool IsNowait = true) { assert(!isStackEmpty()); Stack.back().first.back().NowaitRegion = IsNowait; } /// \brief Returns true, if parent region is nowait (has associated /// 'nowait' clause), false - otherwise. bool isParentNowaitRegion() const { if (isStackEmpty() || Stack.back().first.size() == 1) return false; return std::next(Stack.back().first.rbegin())->NowaitRegion; } /// \brief Marks parent region as cancel region. void setParentCancelRegion(bool Cancel = true) { if (!isStackEmpty() && Stack.back().first.size() > 1) { auto &StackElemRef = *std::next(Stack.back().first.rbegin()); StackElemRef.CancelRegion |= StackElemRef.CancelRegion || Cancel; } } /// \brief Return true if current region has inner cancel construct. bool isCancelRegion() const { return isStackEmpty() ? false : Stack.back().first.back().CancelRegion; } /// \brief Set collapse value for the region. void setAssociatedLoops(unsigned Val) { assert(!isStackEmpty()); Stack.back().first.back().AssociatedLoops = Val; } /// \brief Return collapse value for region. unsigned getAssociatedLoops() const { return isStackEmpty() ? 0 : Stack.back().first.back().AssociatedLoops; } /// \brief Marks current target region as one with closely nested teams /// region. void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) { if (!isStackEmpty() && Stack.back().first.size() > 1) { std::next(Stack.back().first.rbegin())->InnerTeamsRegionLoc = TeamsRegionLoc; } } /// \brief Returns true, if current region has closely nested teams region. bool hasInnerTeamsRegion() const { return getInnerTeamsRegionLoc().isValid(); } /// \brief Returns location of the nested teams region (if any). SourceLocation getInnerTeamsRegionLoc() const { return isStackEmpty() ? SourceLocation() : Stack.back().first.back().InnerTeamsRegionLoc; } Scope *getCurScope() const { return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope; } Scope *getCurScope() { return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope; } SourceLocation getConstructLoc() { return isStackEmpty() ? SourceLocation() : Stack.back().first.back().ConstructLoc; } /// Do the check specified in \a Check to all component lists and return true /// if any issue is found. bool checkMappableExprComponentListsForDecl( ValueDecl *VD, bool CurrentRegionOnly, const llvm::function_ref< bool(OMPClauseMappableExprCommon::MappableExprComponentListRef, OpenMPClauseKind)> &Check) { if (isStackEmpty()) return false; auto SI = Stack.back().first.rbegin(); auto SE = Stack.back().first.rend(); if (SI == SE) return false; if (CurrentRegionOnly) { SE = std::next(SI); } else { ++SI; } for (; SI != SE; ++SI) { auto MI = SI->MappedExprComponents.find(VD); if (MI != SI->MappedExprComponents.end()) for (auto &L : MI->second.Components) if (Check(L, MI->second.Kind)) return true; } return false; } /// Do the check specified in \a Check to all component lists at a given level /// and return true if any issue is found. bool checkMappableExprComponentListsForDeclAtLevel( ValueDecl *VD, unsigned Level, const llvm::function_ref< bool(OMPClauseMappableExprCommon::MappableExprComponentListRef, OpenMPClauseKind)> &Check) { if (isStackEmpty()) return false; auto StartI = Stack.back().first.begin(); auto EndI = Stack.back().first.end(); if (std::distance(StartI, EndI) <= (int)Level) return false; std::advance(StartI, Level); auto MI = StartI->MappedExprComponents.find(VD); if (MI != StartI->MappedExprComponents.end()) for (auto &L : MI->second.Components) if (Check(L, MI->second.Kind)) return true; return false; } /// Create a new mappable expression component list associated with a given /// declaration and initialize it with the provided list of components. void addMappableExpressionComponents( ValueDecl *VD, OMPClauseMappableExprCommon::MappableExprComponentListRef Components, OpenMPClauseKind WhereFoundClauseKind) { assert(!isStackEmpty() && "Not expecting to retrieve components from a empty stack!"); auto &MEC = Stack.back().first.back().MappedExprComponents[VD]; // Create new entry and append the new components there. MEC.Components.resize(MEC.Components.size() + 1); MEC.Components.back().append(Components.begin(), Components.end()); MEC.Kind = WhereFoundClauseKind; } unsigned getNestingLevel() const { assert(!isStackEmpty()); return Stack.back().first.size() - 1; } void addDoacrossDependClause(OMPDependClause *C, OperatorOffsetTy &OpsOffs) { assert(!isStackEmpty() && Stack.back().first.size() > 1); auto &StackElem = *std::next(Stack.back().first.rbegin()); assert(isOpenMPWorksharingDirective(StackElem.Directive)); StackElem.DoacrossDepends.insert({C, OpsOffs}); } llvm::iterator_range<DoacrossDependMapTy::const_iterator> getDoacrossDependClauses() const { assert(!isStackEmpty()); auto &StackElem = Stack.back().first.back(); if (isOpenMPWorksharingDirective(StackElem.Directive)) { auto &Ref = StackElem.DoacrossDepends; return llvm::make_range(Ref.begin(), Ref.end()); } return llvm::make_range(StackElem.DoacrossDepends.end(), StackElem.DoacrossDepends.end()); } }; bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) { return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) || isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown; } } // namespace static Expr *getExprAsWritten(Expr *E) { if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E)) E = ExprTemp->getSubExpr(); if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) E = MTE->GetTemporaryExpr(); while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E)) E = Binder->getSubExpr(); if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) E = ICE->getSubExprAsWritten(); return E->IgnoreParens(); } static ValueDecl *getCanonicalDecl(ValueDecl *D) { if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D)) if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) D = ME->getMemberDecl(); auto *VD = dyn_cast<VarDecl>(D); auto *FD = dyn_cast<FieldDecl>(D); if (VD != nullptr) { VD = VD->getCanonicalDecl(); D = VD; } else { assert(FD); FD = FD->getCanonicalDecl(); D = FD; } return D; } DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator &Iter, ValueDecl *D) { D = getCanonicalDecl(D); auto *VD = dyn_cast<VarDecl>(D); auto *FD = dyn_cast<FieldDecl>(D); DSAVarData DVar; if (isStackEmpty() || Iter == Stack.back().first.rend()) { // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced // in a region but not in construct] // File-scope or namespace-scope variables referenced in called routines // in the region are shared unless they appear in a threadprivate // directive. if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D)) DVar.CKind = OMPC_shared; // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced // in a region but not in construct] // Variables with static storage duration that are declared in called // routines in the region are shared. if (VD && VD->hasGlobalStorage()) DVar.CKind = OMPC_shared; // Non-static data members are shared by default. if (FD) DVar.CKind = OMPC_shared; return DVar; } // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced // in a Construct, C/C++, predetermined, p.1] // Variables with automatic storage duration that are declared in a scope // inside the construct are private. if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() && (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) { DVar.CKind = OMPC_private; return DVar; } DVar.DKind = Iter->Directive; // Explicitly specified attributes and local variables with predetermined // attributes. if (Iter->SharingMap.count(D)) { DVar.RefExpr = Iter->SharingMap[D].RefExpr.getPointer(); DVar.PrivateCopy = Iter->SharingMap[D].PrivateCopy; DVar.CKind = Iter->SharingMap[D].Attributes; DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; return DVar; } // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced // in a Construct, C/C++, implicitly determined, p.1] // In a parallel or task construct, the data-sharing attributes of these // variables are determined by the default clause, if present. switch (Iter->DefaultAttr) { case DSA_shared: DVar.CKind = OMPC_shared; DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; return DVar; case DSA_none: return DVar; case DSA_unspecified: // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced // in a Construct, implicitly determined, p.2] // In a parallel construct, if no default clause is present, these // variables are shared. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; if (isOpenMPParallelDirective(DVar.DKind) || isOpenMPTeamsDirective(DVar.DKind)) { DVar.CKind = OMPC_shared; return DVar; } // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced // in a Construct, implicitly determined, p.4] // In a task construct, if no default clause is present, a variable that in // the enclosing context is determined to be shared by all implicit tasks // bound to the current team is shared. if (isOpenMPTaskingDirective(DVar.DKind)) { DSAVarData DVarTemp; auto I = Iter, E = Stack.back().first.rend(); do { ++I; // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables // Referenced in a Construct, implicitly determined, p.6] // In a task construct, if no default clause is present, a variable // whose data-sharing attribute is not determined by the rules above is // firstprivate. DVarTemp = getDSA(I, D); if (DVarTemp.CKind != OMPC_shared) { DVar.RefExpr = nullptr; DVar.CKind = OMPC_firstprivate; return DVar; } } while (I != E && !isParallelOrTaskRegion(I->Directive)); DVar.CKind = (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared; return DVar; } } // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced // in a Construct, implicitly determined, p.3] // For constructs other than task, if no default clause is present, these // variables inherit their data-sharing attributes from the enclosing // context. return getDSA(++Iter, D); } Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) { assert(!isStackEmpty() && "Data sharing attributes stack is empty"); D = getCanonicalDecl(D); auto &StackElem = Stack.back().first.back(); auto It = StackElem.AlignedMap.find(D); if (It == StackElem.AlignedMap.end()) { assert(NewDE && "Unexpected nullptr expr to be added into aligned map"); StackElem.AlignedMap[D] = NewDE; return nullptr; } else { assert(It->second && "Unexpected nullptr expr in the aligned map"); return It->second; } return nullptr; } void DSAStackTy::addLoopControlVariable(ValueDecl *D, VarDecl *Capture) { assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); D = getCanonicalDecl(D); auto &StackElem = Stack.back().first.back(); StackElem.LCVMap.insert( {D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture)}); } DSAStackTy::LCDeclInfo DSAStackTy::isLoopControlVariable(ValueDecl *D) { assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); D = getCanonicalDecl(D); auto &StackElem = Stack.back().first.back(); auto It = StackElem.LCVMap.find(D); if (It != StackElem.LCVMap.end()) return It->second; return {0, nullptr}; } DSAStackTy::LCDeclInfo DSAStackTy::isParentLoopControlVariable(ValueDecl *D) { assert(!isStackEmpty() && Stack.back().first.size() > 1 && "Data-sharing attributes stack is empty"); D = getCanonicalDecl(D); auto &StackElem = *std::next(Stack.back().first.rbegin()); auto It = StackElem.LCVMap.find(D); if (It != StackElem.LCVMap.end()) return It->second; return {0, nullptr}; } ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) { assert(!isStackEmpty() && Stack.back().first.size() > 1 && "Data-sharing attributes stack is empty"); auto &StackElem = *std::next(Stack.back().first.rbegin()); if (StackElem.LCVMap.size() < I) return nullptr; for (auto &Pair : StackElem.LCVMap) if (Pair.second.first == I) return Pair.first; return nullptr; } void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A, DeclRefExpr *PrivateCopy) { D = getCanonicalDecl(D); if (A == OMPC_threadprivate) { auto &Data = Threadprivates[D]; Data.Attributes = A; Data.RefExpr.setPointer(E); Data.PrivateCopy = nullptr; } else { assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); auto &Data = Stack.back().first.back().SharingMap[D]; assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) || (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) || (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) || (isLoopControlVariable(D).first && A == OMPC_private)); if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) { Data.RefExpr.setInt(/*IntVal=*/true); return; } const bool IsLastprivate = A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate; Data.Attributes = A; Data.RefExpr.setPointerAndInt(E, IsLastprivate); Data.PrivateCopy = PrivateCopy; if (PrivateCopy) { auto &Data = Stack.back().first.back().SharingMap[PrivateCopy->getDecl()]; Data.Attributes = A; Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate); Data.PrivateCopy = nullptr; } } } /// \brief Build a variable declaration for OpenMP loop iteration variable. static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type, StringRef Name, const AttrVec *Attrs = nullptr) { DeclContext *DC = SemaRef.CurContext; IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name); TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc); VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None); if (Attrs) { for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end()); I != E; ++I) Decl->addAttr(*I); } Decl->setImplicit(); return Decl; } static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty, SourceLocation Loc, bool RefersToCapture = false) { D->setReferenced(); D->markUsed(S.Context); return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(), SourceLocation(), D, RefersToCapture, Loc, Ty, VK_LValue); } void DSAStackTy::addTaskgroupReductionData(ValueDecl *D, SourceRange SR, BinaryOperatorKind BOK) { D = getCanonicalDecl(D); assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); assert( Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction && "Additional reduction info may be specified only for reduction items."); auto &ReductionData = Stack.back().first.back().ReductionMap[D]; assert(ReductionData.ReductionRange.isInvalid() && Stack.back().first.back().Directive == OMPD_taskgroup && "Additional reduction info may be specified only once for reduction " "items."); ReductionData.set(BOK, SR); Expr *&TaskgroupReductionRef = Stack.back().first.back().TaskgroupReductionRef; if (!TaskgroupReductionRef) { auto *VD = buildVarDecl(SemaRef, SourceLocation(), SemaRef.Context.VoidPtrTy, ".task_red."); TaskgroupReductionRef = buildDeclRefExpr( SemaRef, VD, SemaRef.Context.VoidPtrTy, SourceLocation()); } } void DSAStackTy::addTaskgroupReductionData(ValueDecl *D, SourceRange SR, const Expr *ReductionRef) { D = getCanonicalDecl(D); assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); assert( Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction && "Additional reduction info may be specified only for reduction items."); auto &ReductionData = Stack.back().first.back().ReductionMap[D]; assert(ReductionData.ReductionRange.isInvalid() && Stack.back().first.back().Directive == OMPD_taskgroup && "Additional reduction info may be specified only once for reduction " "items."); ReductionData.set(ReductionRef, SR); Expr *&TaskgroupReductionRef = Stack.back().first.back().TaskgroupReductionRef; if (!TaskgroupReductionRef) { auto *VD = buildVarDecl(SemaRef, SourceLocation(), SemaRef.Context.VoidPtrTy, ".task_red."); TaskgroupReductionRef = buildDeclRefExpr( SemaRef, VD, SemaRef.Context.VoidPtrTy, SourceLocation()); } } DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK, Expr *&TaskgroupDescriptor) { D = getCanonicalDecl(D); assert(!isStackEmpty() && "Data-sharing attributes stack is empty."); if (Stack.back().first.empty()) return DSAVarData(); for (auto I = std::next(Stack.back().first.rbegin(), 1), E = Stack.back().first.rend(); I != E; std::advance(I, 1)) { auto &Data = I->SharingMap[D]; if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup) continue; auto &ReductionData = I->ReductionMap[D]; if (!ReductionData.ReductionOp || ReductionData.ReductionOp.is<const Expr *>()) return DSAVarData(); SR = ReductionData.ReductionRange; BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>(); assert(I->TaskgroupReductionRef && "taskgroup reduction reference " "expression for the descriptor is not " "set."); TaskgroupDescriptor = I->TaskgroupReductionRef; return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(), Data.PrivateCopy, I->DefaultAttrLoc); } return DSAVarData(); } DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef, Expr *&TaskgroupDescriptor) { D = getCanonicalDecl(D); assert(!isStackEmpty() && "Data-sharing attributes stack is empty."); if (Stack.back().first.empty()) return DSAVarData(); for (auto I = std::next(Stack.back().first.rbegin(), 1), E = Stack.back().first.rend(); I != E; std::advance(I, 1)) { auto &Data = I->SharingMap[D]; if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup) continue; auto &ReductionData = I->ReductionMap[D]; if (!ReductionData.ReductionOp || !ReductionData.ReductionOp.is<const Expr *>()) return DSAVarData(); SR = ReductionData.ReductionRange; ReductionRef = ReductionData.ReductionOp.get<const Expr *>(); assert(I->TaskgroupReductionRef && "taskgroup reduction reference " "expression for the descriptor is not " "set."); TaskgroupDescriptor = I->TaskgroupReductionRef; return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(), Data.PrivateCopy, I->DefaultAttrLoc); } return DSAVarData(); } bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) { D = D->getCanonicalDecl(); if (!isStackEmpty() && Stack.back().first.size() > 1) { reverse_iterator I = Iter, E = Stack.back().first.rend(); Scope *TopScope = nullptr; while (I != E && !isParallelOrTaskRegion(I->Directive)) ++I; if (I == E) return false; TopScope = I->CurScope ? I->CurScope->getParent() : nullptr; Scope *CurScope = getCurScope(); while (CurScope != TopScope && !CurScope->isDeclScope(D)) CurScope = CurScope->getParent(); return CurScope != TopScope; } return false; } DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) { D = getCanonicalDecl(D); DSAVarData DVar; // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced // in a Construct, C/C++, predetermined, p.1] // Variables appearing in threadprivate directives are threadprivate. auto *VD = dyn_cast<VarDecl>(D); if ((VD && VD->getTLSKind() != VarDecl::TLS_None && !(VD->hasAttr<OMPThreadPrivateDeclAttr>() && SemaRef.getLangOpts().OpenMPUseTLS && SemaRef.getASTContext().getTargetInfo().isTLSSupported())) || (VD && VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) { addDSA(D, buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation()), OMPC_threadprivate); } auto TI = Threadprivates.find(D); if (TI != Threadprivates.end()) { DVar.RefExpr = TI->getSecond().RefExpr.getPointer(); DVar.CKind = OMPC_threadprivate; return DVar; } if (isStackEmpty()) // Not in OpenMP execution region and top scope was already checked. return DVar; // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced // in a Construct, C/C++, predetermined, p.4] // Static data members are shared. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced // in a Construct, C/C++, predetermined, p.7] // Variables with static storage duration that are declared in a scope // inside the construct are shared. auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; }; if (VD && VD->isStaticDataMember()) { DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent); if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr) return DVar; DVar.CKind = OMPC_shared; return DVar; } QualType Type = D->getType().getNonReferenceType().getCanonicalType(); bool IsConstant = Type.isConstant(SemaRef.getASTContext()); Type = SemaRef.getASTContext().getBaseElementType(Type); // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced // in a Construct, C/C++, predetermined, p.6] // Variables with const qualified type having no mutable member are // shared. CXXRecordDecl *RD = SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr; if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD)) if (auto *CTD = CTSD->getSpecializedTemplate()) RD = CTD->getTemplatedDecl(); if (IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() && RD->hasMutableFields())) { // Variables with const-qualified type having no mutable member may be // listed in a firstprivate clause, even if they are static data members. DSAVarData DVarTemp = hasDSA( D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; }, MatchesAlways, FromParent); if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr) return DVar; DVar.CKind = OMPC_shared; return DVar; } // Explicitly specified attributes and local variables with predetermined // attributes. auto I = Stack.back().first.rbegin(); auto EndI = Stack.back().first.rend(); if (FromParent && I != EndI) std::advance(I, 1); if (I->SharingMap.count(D)) { DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer(); DVar.PrivateCopy = I->SharingMap[D].PrivateCopy; DVar.CKind = I->SharingMap[D].Attributes; DVar.ImplicitDSALoc = I->DefaultAttrLoc; DVar.DKind = I->Directive; } return DVar; } DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D, bool FromParent) { if (isStackEmpty()) { StackTy::reverse_iterator I; return getDSA(I, D); } D = getCanonicalDecl(D); auto StartI = Stack.back().first.rbegin(); auto EndI = Stack.back().first.rend(); if (FromParent && StartI != EndI) std::advance(StartI, 1); return getDSA(StartI, D); } DSAStackTy::DSAVarData DSAStackTy::hasDSA(ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, bool FromParent) { if (isStackEmpty()) return {}; D = getCanonicalDecl(D); auto I = Stack.back().first.rbegin(); auto EndI = Stack.back().first.rend(); if (FromParent && I != EndI) std::advance(I, 1); for (; I != EndI; std::advance(I, 1)) { if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive)) continue; auto NewI = I; DSAVarData DVar = getDSA(NewI, D); if (I == NewI && CPred(DVar.CKind)) return DVar; } return {}; } DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA( ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, bool FromParent) { if (isStackEmpty()) return {}; D = getCanonicalDecl(D); auto StartI = Stack.back().first.rbegin(); auto EndI = Stack.back().first.rend(); if (FromParent && StartI != EndI) std::advance(StartI, 1); if (StartI == EndI || !DPred(StartI->Directive)) return {}; auto NewI = StartI; DSAVarData DVar = getDSA(NewI, D); return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData(); } bool DSAStackTy::hasExplicitDSA( ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, unsigned Level, bool NotLastprivate) { if (CPred(ClauseKindMode)) return true; if (isStackEmpty()) return false; D = getCanonicalDecl(D); auto StartI = Stack.back().first.begin(); auto EndI = Stack.back().first.end(); if (std::distance(StartI, EndI) <= (int)Level) return false; std::advance(StartI, Level); return (StartI->SharingMap.count(D) > 0) && StartI->SharingMap[D].RefExpr.getPointer() && CPred(StartI->SharingMap[D].Attributes) && (!NotLastprivate || !StartI->SharingMap[D].RefExpr.getInt()); } bool DSAStackTy::hasExplicitDirective( const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, unsigned Level) { if (isStackEmpty()) return false; auto StartI = Stack.back().first.begin(); auto EndI = Stack.back().first.end(); if (std::distance(StartI, EndI) <= (int)Level) return false; std::advance(StartI, Level); return DPred(StartI->Directive); } bool DSAStackTy::hasDirective( const llvm::function_ref<bool(OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)> &DPred, bool FromParent) { // We look only in the enclosing region. if (isStackEmpty()) return false; auto StartI = std::next(Stack.back().first.rbegin()); auto EndI = Stack.back().first.rend(); if (FromParent && StartI != EndI) StartI = std::next(StartI); for (auto I = StartI, EE = EndI; I != EE; ++I) { if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc)) return true; } return false; } void Sema::InitDataSharingAttributesStack() { VarDataSharingAttributesStack = new DSAStackTy(*this); } #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack) void Sema::pushOpenMPFunctionRegion() { DSAStack->pushFunction(); } void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) { DSAStack->popFunction(OldFSI); } bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) { assert(LangOpts.OpenMP && "OpenMP is not allowed"); auto &Ctx = getASTContext(); bool IsByRef = true; // Find the directive that is associated with the provided scope. D = cast<ValueDecl>(D->getCanonicalDecl()); auto Ty = D->getType(); if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) { // This table summarizes how a given variable should be passed to the device // given its type and the clauses where it appears. This table is based on // the description in OpenMP 4.5 [2.10.4, target Construct] and // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses]. // // ========================================================================= // | type | defaultmap | pvt | first | is_device_ptr | map | res. | // | |(tofrom:scalar)| | pvt | | | | // ========================================================================= // | scl | | | | - | | bycopy| // | scl | | - | x | - | - | bycopy| // | scl | | x | - | - | - | null | // | scl | x | | | - | | byref | // | scl | x | - | x | - | - | bycopy| // | scl | x | x | - | - | - | null | // | scl | | - | - | - | x | byref | // | scl | x | - | - | - | x | byref | // // | agg | n.a. | | | - | | byref | // | agg | n.a. | - | x | - | - | byref | // | agg | n.a. | x | - | - | - | null | // | agg | n.a. | - | - | - | x | byref | // | agg | n.a. | - | - | - | x[] | byref | // // | ptr | n.a. | | | - | | bycopy| // | ptr | n.a. | - | x | - | - | bycopy| // | ptr | n.a. | x | - | - | - | null | // | ptr | n.a. | - | - | - | x | byref | // | ptr | n.a. | - | - | - | x[] | bycopy| // | ptr | n.a. | - | - | x | | bycopy| // | ptr | n.a. | - | - | x | x | bycopy| // | ptr | n.a. | - | - | x | x[] | bycopy| // ========================================================================= // Legend: // scl - scalar // ptr - pointer // agg - aggregate // x - applies // - - invalid in this combination // [] - mapped with an array section // byref - should be mapped by reference // byval - should be mapped by value // null - initialize a local variable to null on the device // // Observations: // - All scalar declarations that show up in a map clause have to be passed // by reference, because they may have been mapped in the enclosing data // environment. // - If the scalar value does not fit the size of uintptr, it has to be // passed by reference, regardless the result in the table above. // - For pointers mapped by value that have either an implicit map or an // array section, the runtime library may pass the NULL value to the // device instead of the value passed to it by the compiler. if (Ty->isReferenceType()) Ty = Ty->castAs<ReferenceType>()->getPointeeType(); // Locate map clauses and see if the variable being captured is referred to // in any of those clauses. Here we only care about variables, not fields, // because fields are part of aggregates. bool IsVariableUsedInMapClause = false; bool IsVariableAssociatedWithSection = false; DSAStack->checkMappableExprComponentListsForDeclAtLevel( D, Level, [&](OMPClauseMappableExprCommon::MappableExprComponentListRef MapExprComponents, OpenMPClauseKind WhereFoundClauseKind) { // Only the map clause information influences how a variable is // captured. E.g. is_device_ptr does not require changing the default // behavior. if (WhereFoundClauseKind != OMPC_map) return false; auto EI = MapExprComponents.rbegin(); auto EE = MapExprComponents.rend(); assert(EI != EE && "Invalid map expression!"); if (isa<DeclRefExpr>(EI->getAssociatedExpression())) IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D; ++EI; if (EI == EE) return false; if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) || isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) || isa<MemberExpr>(EI->getAssociatedExpression())) { IsVariableAssociatedWithSection = true; // There is nothing more we need to know about this variable. return true; } // Keep looking for more map info. return false; }); if (IsVariableUsedInMapClause) { // If variable is identified in a map clause it is always captured by // reference except if it is a pointer that is dereferenced somehow. IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection); } else { // By default, all the data that has a scalar type is mapped by copy. IsByRef = !Ty->isScalarType(); } } if (IsByRef && Ty.getNonReferenceType()->isScalarType()) { IsByRef = !DSAStack->hasExplicitDSA( D, [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; }, Level, /*NotLastprivate=*/true); } // When passing data by copy, we need to make sure it fits the uintptr size // and alignment, because the runtime library only deals with uintptr types. // If it does not fit the uintptr size, we need to pass the data by reference // instead. if (!IsByRef && (Ctx.getTypeSizeInChars(Ty) > Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) || Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) { IsByRef = true; } return IsByRef; } unsigned Sema::getOpenMPNestingLevel() const { assert(getLangOpts().OpenMP); return DSAStack->getNestingLevel(); } VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) { assert(LangOpts.OpenMP && "OpenMP is not allowed"); D = getCanonicalDecl(D); // If we are attempting to capture a global variable in a directive with // 'target' we return true so that this global is also mapped to the device. // // FIXME: If the declaration is enclosed in a 'declare target' directive, // then it should not be captured. Therefore, an extra check has to be // inserted here once support for 'declare target' is added. // auto *VD = dyn_cast<VarDecl>(D); if (VD && !VD->hasLocalStorage()) { if (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) && !DSAStack->isClauseParsingMode()) return VD; if (DSAStack->hasDirective( [](OpenMPDirectiveKind K, const DeclarationNameInfo &, SourceLocation) -> bool { return isOpenMPTargetExecutionDirective(K); }, false)) return VD; } if (DSAStack->getCurrentDirective() != OMPD_unknown && (!DSAStack->isClauseParsingMode() || DSAStack->getParentDirective() != OMPD_unknown)) { auto &&Info = DSAStack->isLoopControlVariable(D); if (Info.first || (VD && VD->hasLocalStorage() && isParallelOrTaskRegion(DSAStack->getCurrentDirective())) || (VD && DSAStack->isForceVarCapturing())) return VD ? VD : Info.second; auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode()); if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind)) return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl()); DVarPrivate = DSAStack->hasDSA( D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; }, DSAStack->isClauseParsingMode()); if (DVarPrivate.CKind != OMPC_unknown) return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl()); } return nullptr; } bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) { assert(LangOpts.OpenMP && "OpenMP is not allowed"); return DSAStack->hasExplicitDSA( D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; }, Level) || // Consider taskgroup reduction descriptor variable a private to avoid // possible capture in the region. (DSAStack->hasExplicitDirective( [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; }, Level) && DSAStack->isTaskgroupReductionRef(D, Level)); } void Sema::setOpenMPCaptureKind(FieldDecl *FD, ValueDecl *D, unsigned Level) { assert(LangOpts.OpenMP && "OpenMP is not allowed"); D = getCanonicalDecl(D); OpenMPClauseKind OMPC = OMPC_unknown; for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) { const unsigned NewLevel = I - 1; if (DSAStack->hasExplicitDSA(D, [&OMPC](const OpenMPClauseKind K) { if (isOpenMPPrivate(K)) { OMPC = K; return true; } return false; }, NewLevel)) break; if (DSAStack->checkMappableExprComponentListsForDeclAtLevel( D, NewLevel, [](OMPClauseMappableExprCommon::MappableExprComponentListRef, OpenMPClauseKind) { return true; })) { OMPC = OMPC_map; break; } if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, NewLevel)) { OMPC = OMPC_firstprivate; break; } } if (OMPC != OMPC_unknown) FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC)); } bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) { assert(LangOpts.OpenMP && "OpenMP is not allowed"); // Return true if the current level is no longer enclosed in a target region. auto *VD = dyn_cast<VarDecl>(D); return VD && !VD->hasLocalStorage() && DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level); } void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; } void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName, Scope *CurScope, SourceLocation Loc) { DSAStack->push(DKind, DirName, CurScope, Loc); PushExpressionEvaluationContext( ExpressionEvaluationContext::PotentiallyEvaluated); } void Sema::StartOpenMPClause(OpenMPClauseKind K) { DSAStack->setClauseParsingMode(K); } void Sema::EndOpenMPClause() { DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown); } void Sema::EndOpenMPDSABlock(Stmt *CurDirective) { // OpenMP [2.14.3.5, Restrictions, C/C++, p.1] // A variable of class type (or array thereof) that appears in a lastprivate // clause requires an accessible, unambiguous default constructor for the // class type, unless the list item is also specified in a firstprivate // clause. if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) { for (auto *C : D->clauses()) { if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) { SmallVector<Expr *, 8> PrivateCopies; for (auto *DE : Clause->varlists()) { if (DE->isValueDependent() || DE->isTypeDependent()) { PrivateCopies.push_back(nullptr); continue; } auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens()); VarDecl *VD = cast<VarDecl>(DRE->getDecl()); QualType Type = VD->getType().getNonReferenceType(); auto DVar = DSAStack->getTopDSA(VD, false); if (DVar.CKind == OMPC_lastprivate) { // Generate helper private variable and initialize it with the // default value. The address of the original variable is replaced // by the address of the new private variable in CodeGen. This new // variable is not added to IdResolver, so the code in the OpenMP // region uses original variable for proper diagnostics. auto *VDPrivate = buildVarDecl( *this, DE->getExprLoc(), Type.getUnqualifiedType(), VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr); ActOnUninitializedDecl(VDPrivate); if (VDPrivate->isInvalidDecl()) continue; PrivateCopies.push_back(buildDeclRefExpr( *this, VDPrivate, DE->getType(), DE->getExprLoc())); } else { // The variable is also a firstprivate, so initialization sequence // for private copy is generated already. PrivateCopies.push_back(nullptr); } } // Set initializers to private copies if no errors were found. if (PrivateCopies.size() == Clause->varlist_size()) Clause->setPrivateCopies(PrivateCopies); } } } DSAStack->pop(); DiscardCleanupsInEvaluationContext(); PopExpressionEvaluationContext(); } static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV, Expr *NumIterations, Sema &SemaRef, Scope *S, DSAStackTy *Stack); namespace { class VarDeclFilterCCC : public CorrectionCandidateCallback { private: Sema &SemaRef; public: explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {} bool ValidateCandidate(const TypoCorrection &Candidate) override { NamedDecl *ND = Candidate.getCorrectionDecl(); if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) { return VD->hasGlobalStorage() && SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(), SemaRef.getCurScope()); } return false; } }; class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback { private: Sema &SemaRef; public: explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {} bool ValidateCandidate(const TypoCorrection &Candidate) override { NamedDecl *ND = Candidate.getCorrectionDecl(); if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) { return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(), SemaRef.getCurScope()); } return false; } }; } // namespace ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope, CXXScopeSpec &ScopeSpec, const DeclarationNameInfo &Id) { LookupResult Lookup(*this, Id, LookupOrdinaryName); LookupParsedName(Lookup, CurScope, &ScopeSpec, true); if (Lookup.isAmbiguous()) return ExprError(); VarDecl *VD; if (!Lookup.isSingleResult()) { if (TypoCorrection Corrected = CorrectTypo( Id, LookupOrdinaryName, CurScope, nullptr, llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) { diagnoseTypo(Corrected, PDiag(Lookup.empty() ? diag::err_undeclared_var_use_suggest : diag::err_omp_expected_var_arg_suggest) << Id.getName()); VD = Corrected.getCorrectionDeclAs<VarDecl>(); } else { Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use : diag::err_omp_expected_var_arg) << Id.getName(); return ExprError(); } } else { if (!(VD = Lookup.getAsSingle<VarDecl>())) { Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName(); Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at); return ExprError(); } } Lookup.suppressDiagnostics(); // OpenMP [2.9.2, Syntax, C/C++] // Variables must be file-scope, namespace-scope, or static block-scope. if (!VD->hasGlobalStorage()) { Diag(Id.getLoc(), diag::err_omp_global_var_arg) << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal(); bool IsDecl = VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl : diag::note_defined_here) << VD; return ExprError(); } VarDecl *CanonicalVD = VD->getCanonicalDecl(); NamedDecl *ND = cast<NamedDecl>(CanonicalVD); // OpenMP [2.9.2, Restrictions, C/C++, p.2] // A threadprivate directive for file-scope variables must appear outside // any definition or declaration. if (CanonicalVD->getDeclContext()->isTranslationUnit() && !getCurLexicalContext()->isTranslationUnit()) { Diag(Id.getLoc(), diag::err_omp_var_scope) << getOpenMPDirectiveName(OMPD_threadprivate) << VD; bool IsDecl = VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl : diag::note_defined_here) << VD; return ExprError(); } // OpenMP [2.9.2, Restrictions, C/C++, p.3] // A threadprivate directive for static class member variables must appear // in the class definition, in the same scope in which the member // variables are declared. if (CanonicalVD->isStaticDataMember() && !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) { Diag(Id.getLoc(), diag::err_omp_var_scope) << getOpenMPDirectiveName(OMPD_threadprivate) << VD; bool IsDecl = VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl : diag::note_defined_here) << VD; return ExprError(); } // OpenMP [2.9.2, Restrictions, C/C++, p.4] // A threadprivate directive for namespace-scope variables must appear // outside any definition or declaration other than the namespace // definition itself. if (CanonicalVD->getDeclContext()->isNamespace() && (!getCurLexicalContext()->isFileContext() || !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) { Diag(Id.getLoc(), diag::err_omp_var_scope) << getOpenMPDirectiveName(OMPD_threadprivate) << VD; bool IsDecl = VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl : diag::note_defined_here) << VD; return ExprError(); } // OpenMP [2.9.2, Restrictions, C/C++, p.6] // A threadprivate directive for static block-scope variables must appear // in the scope of the variable and not in a nested scope. if (CanonicalVD->isStaticLocal() && CurScope && !isDeclInScope(ND, getCurLexicalContext(), CurScope)) { Diag(Id.getLoc(), diag::err_omp_var_scope) << getOpenMPDirectiveName(OMPD_threadprivate) << VD; bool IsDecl = VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl : diag::note_defined_here) << VD; return ExprError(); } // OpenMP [2.9.2, Restrictions, C/C++, p.2-6] // A threadprivate directive must lexically precede all references to any // of the variables in its list. if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) { Diag(Id.getLoc(), diag::err_omp_var_used) << getOpenMPDirectiveName(OMPD_threadprivate) << VD; return ExprError(); } QualType ExprType = VD->getType().getNonReferenceType(); return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(), SourceLocation(), VD, /*RefersToEnclosingVariableOrCapture=*/false, Id.getLoc(), ExprType, VK_LValue); } Sema::DeclGroupPtrTy Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc, ArrayRef<Expr *> VarList) { if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) { CurContext->addDecl(D); return DeclGroupPtrTy::make(DeclGroupRef(D)); } return nullptr; } namespace { class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> { Sema &SemaRef; public: bool VisitDeclRefExpr(const DeclRefExpr *E) { if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) { if (VD->hasLocalStorage()) { SemaRef.Diag(E->getLocStart(), diag::err_omp_local_var_in_threadprivate_init) << E->getSourceRange(); SemaRef.Diag(VD->getLocation(), diag::note_defined_here) << VD << VD->getSourceRange(); return true; } } return false; } bool VisitStmt(const Stmt *S) { for (auto Child : S->children()) { if (Child && Visit(Child)) return true; } return false; } explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {} }; } // namespace OMPThreadPrivateDecl * Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) { SmallVector<Expr *, 8> Vars; for (auto &RefExpr : VarList) { DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr); VarDecl *VD = cast<VarDecl>(DE->getDecl()); SourceLocation ILoc = DE->getExprLoc(); // Mark variable as used. VD->setReferenced(); VD->markUsed(Context); QualType QType = VD->getType(); if (QType->isDependentType() || QType->isInstantiationDependentType()) { // It will be analyzed later. Vars.push_back(DE); continue; } // OpenMP [2.9.2, Restrictions, C/C++, p.10] // A threadprivate variable must not have an incomplete type. if (RequireCompleteType(ILoc, VD->getType(), diag::err_omp_threadprivate_incomplete_type)) { continue; } // OpenMP [2.9.2, Restrictions, C/C++, p.10] // A threadprivate variable must not have a reference type. if (VD->getType()->isReferenceType()) { Diag(ILoc, diag::err_omp_ref_type_arg) << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType(); bool IsDecl = VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl : diag::note_defined_here) << VD; continue; } // Check if this is a TLS variable. If TLS is not being supported, produce // the corresponding diagnostic. if ((VD->getTLSKind() != VarDecl::TLS_None && !(VD->hasAttr<OMPThreadPrivateDeclAttr>() && getLangOpts().OpenMPUseTLS && getASTContext().getTargetInfo().isTLSSupported())) || (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) { Diag(ILoc, diag::err_omp_var_thread_local) << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1); bool IsDecl = VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl : diag::note_defined_here) << VD; continue; } // Check if initial value of threadprivate variable reference variable with // local storage (it is not supported by runtime). if (auto Init = VD->getAnyInitializer()) { LocalVarRefChecker Checker(*this); if (Checker.Visit(Init)) continue; } Vars.push_back(RefExpr); DSAStack->addDSA(VD, DE, OMPC_threadprivate); VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit( Context, SourceRange(Loc, Loc))); if (auto *ML = Context.getASTMutationListener()) ML->DeclarationMarkedOpenMPThreadPrivate(VD); } OMPThreadPrivateDecl *D = nullptr; if (!Vars.empty()) { D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc, Vars); D->setAccess(AS_public); } return D; } static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack, const ValueDecl *D, DSAStackTy::DSAVarData DVar, bool IsLoopIterVar = false) { if (DVar.RefExpr) { SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa) << getOpenMPClauseName(DVar.CKind); return; } enum { PDSA_StaticMemberShared, PDSA_StaticLocalVarShared, PDSA_LoopIterVarPrivate, PDSA_LoopIterVarLinear, PDSA_LoopIterVarLastprivate, PDSA_ConstVarShared, PDSA_GlobalVarShared, PDSA_TaskVarFirstprivate, PDSA_LocalVarPrivate, PDSA_Implicit } Reason = PDSA_Implicit; bool ReportHint = false; auto ReportLoc = D->getLocation(); auto *VD = dyn_cast<VarDecl>(D); if (IsLoopIterVar) { if (DVar.CKind == OMPC_private) Reason = PDSA_LoopIterVarPrivate; else if (DVar.CKind == OMPC_lastprivate) Reason = PDSA_LoopIterVarLastprivate; else Reason = PDSA_LoopIterVarLinear; } else if (isOpenMPTaskingDirective(DVar.DKind) && DVar.CKind == OMPC_firstprivate) { Reason = PDSA_TaskVarFirstprivate; ReportLoc = DVar.ImplicitDSALoc; } else if (VD && VD->isStaticLocal()) Reason = PDSA_StaticLocalVarShared; else if (VD && VD->isStaticDataMember()) Reason = PDSA_StaticMemberShared; else if (VD && VD->isFileVarDecl()) Reason = PDSA_GlobalVarShared; else if (D->getType().isConstant(SemaRef.getASTContext())) Reason = PDSA_ConstVarShared; else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) { ReportHint = true; Reason = PDSA_LocalVarPrivate; } if (Reason != PDSA_Implicit) { SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa) << Reason << ReportHint << getOpenMPDirectiveName(Stack->getCurrentDirective()); } else if (DVar.ImplicitDSALoc.isValid()) { SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa) << getOpenMPClauseName(DVar.CKind); } } namespace { class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> { DSAStackTy *Stack; Sema &SemaRef; bool ErrorFound; CapturedStmt *CS; llvm::SmallVector<Expr *, 8> ImplicitFirstprivate; llvm::SmallVector<Expr *, 8> ImplicitMap; llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA; llvm::DenseSet<ValueDecl *> ImplicitDeclarations; public: void VisitDeclRefExpr(DeclRefExpr *E) { if (E->isTypeDependent() || E->isValueDependent() || E->containsUnexpandedParameterPack() || E->isInstantiationDependent()) return; if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) { VD = VD->getCanonicalDecl(); // Skip internally declared variables. if (VD->isLocalVarDecl() && !CS->capturesVariable(VD)) return; auto DVar = Stack->getTopDSA(VD, false); // Check if the variable has explicit DSA set and stop analysis if it so. if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second) return; auto ELoc = E->getExprLoc(); auto DKind = Stack->getCurrentDirective(); // The default(none) clause requires that each variable that is referenced // in the construct, and does not have a predetermined data-sharing // attribute, must have its data-sharing attribute explicitly determined // by being listed in a data-sharing attribute clause. if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none && isParallelOrTaskRegion(DKind) && VarsWithInheritedDSA.count(VD) == 0) { VarsWithInheritedDSA[VD] = E; return; } if (isOpenMPTargetExecutionDirective(DKind) && !Stack->isLoopControlVariable(VD).first) { if (!Stack->checkMappableExprComponentListsForDecl( VD, /*CurrentRegionOnly=*/true, [](OMPClauseMappableExprCommon::MappableExprComponentListRef StackComponents, OpenMPClauseKind) { // Variable is used if it has been marked as an array, array // section or the variable iself. return StackComponents.size() == 1 || std::all_of( std::next(StackComponents.rbegin()), StackComponents.rend(), [](const OMPClauseMappableExprCommon:: MappableComponent &MC) { return MC.getAssociatedDeclaration() == nullptr && (isa<OMPArraySectionExpr>( MC.getAssociatedExpression()) || isa<ArraySubscriptExpr>( MC.getAssociatedExpression())); }); })) { bool CapturedByCopy = false; // By default lambdas are captured as firstprivates. if (const auto *RD = VD->getType().getNonReferenceType()->getAsCXXRecordDecl()) if (RD->isLambda()) CapturedByCopy = true; CapturedByCopy = CapturedByCopy || llvm::any_of( CS->captures(), [VD](const CapturedStmt::Capture &I) { return I.capturesVariableByCopy() && I.getCapturedVar()->getCanonicalDecl() == VD; }); if (CapturedByCopy) ImplicitFirstprivate.emplace_back(E); else ImplicitMap.emplace_back(E); return; } } // OpenMP [2.9.3.6, Restrictions, p.2] // A list item that appears in a reduction clause of the innermost // enclosing worksharing or parallel construct may not be accessed in an // explicit task. DVar = Stack->hasInnermostDSA( VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; }, [](OpenMPDirectiveKind K) -> bool { return isOpenMPParallelDirective(K) || isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K); }, /*FromParent=*/true); if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) { ErrorFound = true; SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task); ReportOriginalDSA(SemaRef, Stack, VD, DVar); return; } // Define implicit data-sharing attributes for task. DVar = Stack->getImplicitDSA(VD, false); if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared && !Stack->isLoopControlVariable(VD).first) ImplicitFirstprivate.push_back(E); } } void VisitMemberExpr(MemberExpr *E) { if (E->isTypeDependent() || E->isValueDependent() || E->containsUnexpandedParameterPack() || E->isInstantiationDependent()) return; auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); if (!FD) return; OpenMPDirectiveKind DKind = Stack->getCurrentDirective(); if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) { auto DVar = Stack->getTopDSA(FD, false); // Check if the variable has explicit DSA set and stop analysis if it // so. if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second) return; if (isOpenMPTargetExecutionDirective(DKind) && !Stack->isLoopControlVariable(FD).first && !Stack->checkMappableExprComponentListsForDecl( FD, /*CurrentRegionOnly=*/true, [](OMPClauseMappableExprCommon::MappableExprComponentListRef StackComponents, OpenMPClauseKind) { return isa<CXXThisExpr>( cast<MemberExpr>( StackComponents.back().getAssociatedExpression()) ->getBase() ->IgnoreParens()); })) { // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3] // A bit-field cannot appear in a map clause. // if (FD->isBitField()) { SemaRef.Diag(E->getMemberLoc(), diag::err_omp_bit_fields_forbidden_in_clause) << E->getSourceRange() << getOpenMPClauseName(OMPC_map); return; } ImplicitMap.emplace_back(E); return; } auto ELoc = E->getExprLoc(); // OpenMP [2.9.3.6, Restrictions, p.2] // A list item that appears in a reduction clause of the innermost // enclosing worksharing or parallel construct may not be accessed in // an explicit task. DVar = Stack->hasInnermostDSA( FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; }, [](OpenMPDirectiveKind K) -> bool { return isOpenMPParallelDirective(K) || isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K); }, /*FromParent=*/true); if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) { ErrorFound = true; SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task); ReportOriginalDSA(SemaRef, Stack, FD, DVar); return; } // Define implicit data-sharing attributes for task. DVar = Stack->getImplicitDSA(FD, false); if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared && !Stack->isLoopControlVariable(FD).first) ImplicitFirstprivate.push_back(E); return; } if (isOpenMPTargetExecutionDirective(DKind) && !FD->isBitField()) { OMPClauseMappableExprCommon::MappableExprComponentList CurComponents; CheckMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map); auto *VD = cast<ValueDecl>( CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl()); if (!Stack->checkMappableExprComponentListsForDecl( VD, /*CurrentRegionOnly=*/true, [&CurComponents]( OMPClauseMappableExprCommon::MappableExprComponentListRef StackComponents, OpenMPClauseKind) { auto CCI = CurComponents.rbegin(); auto CCE = CurComponents.rend(); for (const auto &SC : llvm::reverse(StackComponents)) { // Do both expressions have the same kind? if (CCI->getAssociatedExpression()->getStmtClass() != SC.getAssociatedExpression()->getStmtClass()) if (!(isa<OMPArraySectionExpr>( SC.getAssociatedExpression()) && isa<ArraySubscriptExpr>( CCI->getAssociatedExpression()))) return false; Decl *CCD = CCI->getAssociatedDeclaration(); Decl *SCD = SC.getAssociatedDeclaration(); CCD = CCD ? CCD->getCanonicalDecl() : nullptr; SCD = SCD ? SCD->getCanonicalDecl() : nullptr; if (SCD != CCD) return false; std::advance(CCI, 1); if (CCI == CCE) break; } return true; })) { Visit(E->getBase()); } } else Visit(E->getBase()); } void VisitOMPExecutableDirective(OMPExecutableDirective *S) { for (auto *C : S->clauses()) { // Skip analysis of arguments of implicitly defined firstprivate clause // for task|target directives. // Skip analysis of arguments of implicitly defined map clause for target // directives. if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) && C->isImplicit())) { for (auto *CC : C->children()) { if (CC) Visit(CC); } } } } void VisitStmt(Stmt *S) { for (auto *C : S->children()) { if (C && !isa<OMPExecutableDirective>(C)) Visit(C); } } bool isErrorFound() { return ErrorFound; } ArrayRef<Expr *> getImplicitFirstprivate() const { return ImplicitFirstprivate; } ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; } llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() { return VarsWithInheritedDSA; } DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS) : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {} }; } // namespace void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) { switch (DKind) { case OMPD_parallel: case OMPD_parallel_for: case OMPD_parallel_for_simd: case OMPD_parallel_sections: case OMPD_teams: case OMPD_teams_distribute: { QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); Sema::CapturedParamNameType Params[] = { std::make_pair(".global_tid.", KmpInt32PtrTy), std::make_pair(".bound_tid.", KmpInt32PtrTy), std::make_pair(StringRef(), QualType()) // __context with shared vars }; ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, Params); break; } case OMPD_target_teams: case OMPD_target_parallel: { Sema::CapturedParamNameType ParamsTarget[] = { std::make_pair(StringRef(), QualType()) // __context with shared vars }; // Start a captured region for 'target' with no implicit parameters. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, ParamsTarget); QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); Sema::CapturedParamNameType ParamsTeamsOrParallel[] = { std::make_pair(".global_tid.", KmpInt32PtrTy), std::make_pair(".bound_tid.", KmpInt32PtrTy), std::make_pair(StringRef(), QualType()) // __context with shared vars }; // Start a captured region for 'teams' or 'parallel'. Both regions have // the same implicit parameters. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, ParamsTeamsOrParallel); break; } case OMPD_simd: case OMPD_for: case OMPD_for_simd: case OMPD_sections: case OMPD_section: case OMPD_single: case OMPD_master: case OMPD_critical: case OMPD_taskgroup: case OMPD_distribute: case OMPD_ordered: case OMPD_atomic: case OMPD_target_data: case OMPD_target: case OMPD_target_parallel_for: case OMPD_target_parallel_for_simd: case OMPD_target_simd: { Sema::CapturedParamNameType Params[] = { std::make_pair(StringRef(), QualType()) // __context with shared vars }; ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, Params); break; } case OMPD_task: { QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()}; FunctionProtoType::ExtProtoInfo EPI; EPI.Variadic = true; QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); Sema::CapturedParamNameType Params[] = { std::make_pair(".global_tid.", KmpInt32Ty), std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)), std::make_pair(".privates.", Context.VoidPtrTy.withConst()), std::make_pair(".copy_fn.", Context.getPointerType(CopyFnType).withConst()), std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), std::make_pair(StringRef(), QualType()) // __context with shared vars }; ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, Params); // Mark this captured region as inlined, because we don't use outlined // function directly. getCurCapturedRegion()->TheCapturedDecl->addAttr( AlwaysInlineAttr::CreateImplicit( Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange())); break; } case OMPD_taskloop: case OMPD_taskloop_simd: { QualType KmpInt32Ty = Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1); QualType KmpUInt64Ty = Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0); QualType KmpInt64Ty = Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1); QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()}; FunctionProtoType::ExtProtoInfo EPI; EPI.Variadic = true; QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); Sema::CapturedParamNameType Params[] = { std::make_pair(".global_tid.", KmpInt32Ty), std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)), std::make_pair(".privates.", Context.VoidPtrTy.withConst().withRestrict()), std::make_pair( ".copy_fn.", Context.getPointerType(CopyFnType).withConst().withRestrict()), std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), std::make_pair(".lb.", KmpUInt64Ty), std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty), std::make_pair(".liter.", KmpInt32Ty), std::make_pair(".reductions.", Context.VoidPtrTy.withConst().withRestrict()), std::make_pair(StringRef(), QualType()) // __context with shared vars }; ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, Params); // Mark this captured region as inlined, because we don't use outlined // function directly. getCurCapturedRegion()->TheCapturedDecl->addAttr( AlwaysInlineAttr::CreateImplicit( Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange())); break; } case OMPD_distribute_parallel_for_simd: case OMPD_distribute_simd: case OMPD_distribute_parallel_for: case OMPD_teams_distribute_simd: case OMPD_teams_distribute_parallel_for_simd: case OMPD_teams_distribute_parallel_for: case OMPD_target_teams_distribute: case OMPD_target_teams_distribute_parallel_for: case OMPD_target_teams_distribute_parallel_for_simd: case OMPD_target_teams_distribute_simd: { QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); Sema::CapturedParamNameType Params[] = { std::make_pair(".global_tid.", KmpInt32PtrTy), std::make_pair(".bound_tid.", KmpInt32PtrTy), std::make_pair(".previous.lb.", Context.getSizeType()), std::make_pair(".previous.ub.", Context.getSizeType()), std::make_pair(StringRef(), QualType()) // __context with shared vars }; ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, Params); break; } case OMPD_threadprivate: case OMPD_taskyield: case OMPD_barrier: case OMPD_taskwait: case OMPD_cancellation_point: case OMPD_cancel: case OMPD_flush: case OMPD_target_enter_data: case OMPD_target_exit_data: case OMPD_declare_reduction: case OMPD_declare_simd: case OMPD_declare_target: case OMPD_end_declare_target: case OMPD_target_update: llvm_unreachable("OpenMP Directive is not allowed"); case OMPD_unknown: llvm_unreachable("Unknown OpenMP directive"); } } int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) { SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; getOpenMPCaptureRegions(CaptureRegions, DKind); return CaptureRegions.size(); } static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id, Expr *CaptureExpr, bool WithInit, bool AsExpression) { assert(CaptureExpr); ASTContext &C = S.getASTContext(); Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts(); QualType Ty = Init->getType(); if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) { if (S.getLangOpts().CPlusPlus) Ty = C.getLValueReferenceType(Ty); else { Ty = C.getPointerType(Ty); ExprResult Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init); if (!Res.isUsable()) return nullptr; Init = Res.get(); } WithInit = true; } auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty, CaptureExpr->getLocStart()); if (!WithInit) CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange())); S.CurContext->addHiddenDecl(CED); S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false); return CED; } static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr, bool WithInit) { OMPCapturedExprDecl *CD; if (auto *VD = S.IsOpenMPCapturedDecl(D)) CD = cast<OMPCapturedExprDecl>(VD); else CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit, /*AsExpression=*/false); return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(), CaptureExpr->getExprLoc()); } static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) { if (!Ref) { auto *CD = buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true); Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(), CaptureExpr->getExprLoc()); } ExprResult Res = Ref; if (!S.getLangOpts().CPlusPlus && CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() && Ref->getType()->isPointerType()) Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref); if (!Res.isUsable()) return ExprError(); return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get()); } namespace { // OpenMP directives parsed in this section are represented as a // CapturedStatement with an associated statement. If a syntax error // is detected during the parsing of the associated statement, the // compiler must abort processing and close the CapturedStatement. // // Combined directives such as 'target parallel' have more than one // nested CapturedStatements. This RAII ensures that we unwind out // of all the nested CapturedStatements when an error is found. class CaptureRegionUnwinderRAII { private: Sema &S; bool &ErrorFound; OpenMPDirectiveKind DKind; public: CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound, OpenMPDirectiveKind DKind) : S(S), ErrorFound(ErrorFound), DKind(DKind) {} ~CaptureRegionUnwinderRAII() { if (ErrorFound) { int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind); while (--ThisCaptureLevel >= 0) S.ActOnCapturedRegionError(); } } }; } // namespace StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses) { bool ErrorFound = false; CaptureRegionUnwinderRAII CaptureRegionUnwinder( *this, ErrorFound, DSAStack->getCurrentDirective()); if (!S.isUsable()) { ErrorFound = true; return StmtError(); } OMPOrderedClause *OC = nullptr; OMPScheduleClause *SC = nullptr; SmallVector<OMPLinearClause *, 4> LCs; SmallVector<OMPClauseWithPreInit *, 8> PICs; // This is required for proper codegen. for (auto *Clause : Clauses) { if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) && Clause->getClauseKind() == OMPC_in_reduction) { // Capture taskgroup task_reduction descriptors inside the tasking regions // with the corresponding in_reduction items. auto *IRC = cast<OMPInReductionClause>(Clause); for (auto *E : IRC->taskgroup_descriptors()) if (E) MarkDeclarationsReferencedInExpr(E); } if (isOpenMPPrivate(Clause->getClauseKind()) || Clause->getClauseKind() == OMPC_copyprivate || (getLangOpts().OpenMPUseTLS && getASTContext().getTargetInfo().isTLSSupported() && Clause->getClauseKind() == OMPC_copyin)) { DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin); // Mark all variables in private list clauses as used in inner region. for (auto *VarRef : Clause->children()) { if (auto *E = cast_or_null<Expr>(VarRef)) { MarkDeclarationsReferencedInExpr(E); } } DSAStack->setForceVarCapturing(/*V=*/false); } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) { if (auto *C = OMPClauseWithPreInit::get(Clause)) PICs.push_back(C); if (auto *C = OMPClauseWithPostUpdate::get(Clause)) { if (auto *E = C->getPostUpdateExpr()) MarkDeclarationsReferencedInExpr(E); } } if (Clause->getClauseKind() == OMPC_schedule) SC = cast<OMPScheduleClause>(Clause); else if (Clause->getClauseKind() == OMPC_ordered) OC = cast<OMPOrderedClause>(Clause); else if (Clause->getClauseKind() == OMPC_linear) LCs.push_back(cast<OMPLinearClause>(Clause)); } // OpenMP, 2.7.1 Loop Construct, Restrictions // The nonmonotonic modifier cannot be specified if an ordered clause is // specified. if (SC && (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic || SC->getSecondScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic) && OC) { Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? SC->getFirstScheduleModifierLoc() : SC->getSecondScheduleModifierLoc(), diag::err_omp_schedule_nonmonotonic_ordered) << SourceRange(OC->getLocStart(), OC->getLocEnd()); ErrorFound = true; } if (!LCs.empty() && OC && OC->getNumForLoops()) { for (auto *C : LCs) { Diag(C->getLocStart(), diag::err_omp_linear_ordered) << SourceRange(OC->getLocStart(), OC->getLocEnd()); } ErrorFound = true; } if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) && isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC && OC->getNumForLoops()) { Diag(OC->getLocStart(), diag::err_omp_ordered_simd) << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); ErrorFound = true; } if (ErrorFound) { return StmtError(); } StmtResult SR = S; SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective()); for (auto ThisCaptureRegion : llvm::reverse(CaptureRegions)) { // Mark all variables in private list clauses as used in inner region. // Required for proper codegen of combined directives. // TODO: add processing for other clauses. if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) { for (auto *C : PICs) { OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion(); // Find the particular capture region for the clause if the // directive is a combined one with multiple capture regions. // If the directive is not a combined one, the capture region // associated with the clause is OMPD_unknown and is generated // only once. if (CaptureRegion == ThisCaptureRegion || CaptureRegion == OMPD_unknown) { if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) { for (auto *D : DS->decls()) MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D)); } } } } SR = ActOnCapturedRegionEnd(SR.get()); } return SR; } static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion, OpenMPDirectiveKind CancelRegion, SourceLocation StartLoc) { // CancelRegion is only needed for cancel and cancellation_point. if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point) return false; if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for || CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup) return false; SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region) << getOpenMPDirectiveName(CancelRegion); return true; } static bool checkNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack, OpenMPDirectiveKind CurrentRegion, const DeclarationNameInfo &CurrentName, OpenMPDirectiveKind CancelRegion, SourceLocation StartLoc) { if (Stack->getCurScope()) { auto ParentRegion = Stack->getParentDirective(); auto OffendingRegion = ParentRegion; bool NestingProhibited = false; bool CloseNesting = true; bool OrphanSeen = false; enum { NoRecommend, ShouldBeInParallelRegion, ShouldBeInOrderedRegion, ShouldBeInTargetRegion, ShouldBeInTeamsRegion } Recommend = NoRecommend; if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) { // OpenMP [2.16, Nesting of Regions] // OpenMP constructs may not be nested inside a simd region. // OpenMP [2.8.1,simd Construct, Restrictions] // An ordered construct with the simd clause is the only OpenMP // construct that can appear in the simd region. // Allowing a SIMD construct nested in another SIMD construct is an // extension. The OpenMP 4.5 spec does not allow it. Issue a warning // message. SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd) ? diag::err_omp_prohibited_region_simd : diag::warn_omp_nesting_simd); return CurrentRegion != OMPD_simd; } if (ParentRegion == OMPD_atomic) { // OpenMP [2.16, Nesting of Regions] // OpenMP constructs may not be nested inside an atomic region. SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic); return true; } if (CurrentRegion == OMPD_section) { // OpenMP [2.7.2, sections Construct, Restrictions] // Orphaned section directives are prohibited. That is, the section // directives must appear within the sections construct and must not be // encountered elsewhere in the sections region. if (ParentRegion != OMPD_sections && ParentRegion != OMPD_parallel_sections) { SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive) << (ParentRegion != OMPD_unknown) << getOpenMPDirectiveName(ParentRegion); return true; } return false; } // Allow some constructs (except teams) to be orphaned (they could be // used in functions, called from OpenMP regions with the required // preconditions). if (ParentRegion == OMPD_unknown && !isOpenMPNestingTeamsDirective(CurrentRegion)) return false; if (CurrentRegion == OMPD_cancellation_point || CurrentRegion == OMPD_cancel) { // OpenMP [2.16, Nesting of Regions] // A cancellation point construct for which construct-type-clause is // taskgroup must be nested inside a task construct. A cancellation // point construct for which construct-type-clause is not taskgroup must // be closely nested inside an OpenMP construct that matches the type // specified in construct-type-clause. // A cancel construct for which construct-type-clause is taskgroup must be // nested inside a task construct. A cancel construct for which // construct-type-clause is not taskgroup must be closely nested inside an // OpenMP construct that matches the type specified in // construct-type-clause. NestingProhibited = !((CancelRegion == OMPD_parallel && (ParentRegion == OMPD_parallel || ParentRegion == OMPD_target_parallel)) || (CancelRegion == OMPD_for && (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for || ParentRegion == OMPD_target_parallel_for)) || (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) || (CancelRegion == OMPD_sections && (ParentRegion == OMPD_section || ParentRegion == OMPD_sections || ParentRegion == OMPD_parallel_sections))); } else if (CurrentRegion == OMPD_master) { // OpenMP [2.16, Nesting of Regions] // A master region may not be closely nested inside a worksharing, // atomic, or explicit task region. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || isOpenMPTaskingDirective(ParentRegion); } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) { // OpenMP [2.16, Nesting of Regions] // A critical region may not be nested (closely or otherwise) inside a // critical region with the same name. Note that this restriction is not // sufficient to prevent deadlock. SourceLocation PreviousCriticalLoc; bool DeadLock = Stack->hasDirective( [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K, const DeclarationNameInfo &DNI, SourceLocation Loc) -> bool { if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) { PreviousCriticalLoc = Loc; return true; } else return false; }, false /* skip top directive */); if (DeadLock) { SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_critical_same_name) << CurrentName.getName(); if (PreviousCriticalLoc.isValid()) SemaRef.Diag(PreviousCriticalLoc, diag::note_omp_previous_critical_region); return true; } } else if (CurrentRegion == OMPD_barrier) { // OpenMP [2.16, Nesting of Regions] // A barrier region may not be closely nested inside a worksharing, // explicit task, critical, ordered, atomic, or master region. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || isOpenMPTaskingDirective(ParentRegion) || ParentRegion == OMPD_master || ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered; } else if (isOpenMPWorksharingDirective(CurrentRegion) && !isOpenMPParallelDirective(CurrentRegion) && !isOpenMPTeamsDirective(CurrentRegion)) { // OpenMP [2.16, Nesting of Regions] // A worksharing region may not be closely nested inside a worksharing, // explicit task, critical, ordered, atomic, or master region. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || isOpenMPTaskingDirective(ParentRegion) || ParentRegion == OMPD_master || ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered; Recommend = ShouldBeInParallelRegion; } else if (CurrentRegion == OMPD_ordered) { // OpenMP [2.16, Nesting of Regions] // An ordered region may not be closely nested inside a critical, // atomic, or explicit task region. // An ordered region must be closely nested inside a loop region (or // parallel loop region) with an ordered clause. // OpenMP [2.8.1,simd Construct, Restrictions] // An ordered construct with the simd clause is the only OpenMP construct // that can appear in the simd region. NestingProhibited = ParentRegion == OMPD_critical || isOpenMPTaskingDirective(ParentRegion) || !(isOpenMPSimdDirective(ParentRegion) || Stack->isParentOrderedRegion()); Recommend = ShouldBeInOrderedRegion; } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) { // OpenMP [2.16, Nesting of Regions] // If specified, a teams construct must be contained within a target // construct. NestingProhibited = ParentRegion != OMPD_target; OrphanSeen = ParentRegion == OMPD_unknown; Recommend = ShouldBeInTargetRegion; Stack->setParentTeamsRegionLoc(Stack->getConstructLoc()); } if (!NestingProhibited && !isOpenMPTargetExecutionDirective(CurrentRegion) && !isOpenMPTargetDataManagementDirective(CurrentRegion) && (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) { // OpenMP [2.16, Nesting of Regions] // distribute, parallel, parallel sections, parallel workshare, and the // parallel loop and parallel loop SIMD constructs are the only OpenMP // constructs that can be closely nested in the teams region. NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) && !isOpenMPDistributeDirective(CurrentRegion); Recommend = ShouldBeInParallelRegion; } if (!NestingProhibited && isOpenMPNestingDistributeDirective(CurrentRegion)) { // OpenMP 4.5 [2.17 Nesting of Regions] // The region associated with the distribute construct must be strictly // nested inside a teams region NestingProhibited = (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams); Recommend = ShouldBeInTeamsRegion; } if (!NestingProhibited && (isOpenMPTargetExecutionDirective(CurrentRegion) || isOpenMPTargetDataManagementDirective(CurrentRegion))) { // OpenMP 4.5 [2.17 Nesting of Regions] // If a target, target update, target data, target enter data, or // target exit data construct is encountered during execution of a // target region, the behavior is unspecified. NestingProhibited = Stack->hasDirective( [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &, SourceLocation) -> bool { if (isOpenMPTargetExecutionDirective(K)) { OffendingRegion = K; return true; } else return false; }, false /* don't skip top directive */); CloseNesting = false; } if (NestingProhibited) { if (OrphanSeen) { SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive) << getOpenMPDirectiveName(CurrentRegion) << Recommend; } else { SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region) << CloseNesting << getOpenMPDirectiveName(OffendingRegion) << Recommend << getOpenMPDirectiveName(CurrentRegion); } return true; } } return false; } static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind, ArrayRef<OMPClause *> Clauses, ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) { bool ErrorFound = false; unsigned NamedModifiersNumber = 0; SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers( OMPD_unknown + 1); SmallVector<SourceLocation, 4> NameModifierLoc; for (const auto *C : Clauses) { if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) { // At most one if clause without a directive-name-modifier can appear on // the directive. OpenMPDirectiveKind CurNM = IC->getNameModifier(); if (FoundNameModifiers[CurNM]) { S.Diag(C->getLocStart(), diag::err_omp_more_one_clause) << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if) << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM); ErrorFound = true; } else if (CurNM != OMPD_unknown) { NameModifierLoc.push_back(IC->getNameModifierLoc()); ++NamedModifiersNumber; } FoundNameModifiers[CurNM] = IC; if (CurNM == OMPD_unknown) continue; // Check if the specified name modifier is allowed for the current // directive. // At most one if clause with the particular directive-name-modifier can // appear on the directive. bool MatchFound = false; for (auto NM : AllowedNameModifiers) { if (CurNM == NM) { MatchFound = true; break; } } if (!MatchFound) { S.Diag(IC->getNameModifierLoc(), diag::err_omp_wrong_if_directive_name_modifier) << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind); ErrorFound = true; } } } // If any if clause on the directive includes a directive-name-modifier then // all if clauses on the directive must include a directive-name-modifier. if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) { if (NamedModifiersNumber == AllowedNameModifiers.size()) { S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(), diag::err_omp_no_more_if_clause); } else { std::string Values; std::string Sep(", "); unsigned AllowedCnt = 0; unsigned TotalAllowedNum = AllowedNameModifiers.size() - NamedModifiersNumber; for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End; ++Cnt) { OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt]; if (!FoundNameModifiers[NM]) { Values += "'"; Values += getOpenMPDirectiveName(NM); Values += "'"; if (AllowedCnt + 2 == TotalAllowedNum) Values += " or "; else if (AllowedCnt + 1 != TotalAllowedNum) Values += Sep; ++AllowedCnt; } } S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(), diag::err_omp_unnamed_if_clause) << (TotalAllowedNum > 1) << Values; } for (auto Loc : NameModifierLoc) { S.Diag(Loc, diag::note_omp_previous_named_if_clause); } ErrorFound = true; } return ErrorFound; } StmtResult Sema::ActOnOpenMPExecutableDirective( OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName, OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { StmtResult Res = StmtError(); // First check CancelRegion which is then used in checkNestingOfRegions. if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) || checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion, StartLoc)) return StmtError(); llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit; llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA; bool ErrorFound = false; ClausesWithImplicit.append(Clauses.begin(), Clauses.end()); if (AStmt && !CurContext->isDependentContext()) { assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); // Check default data sharing attributes for referenced variables. DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt)); int ThisCaptureLevel = getOpenMPCaptureLevels(Kind); Stmt *S = AStmt; while (--ThisCaptureLevel >= 0) S = cast<CapturedStmt>(S)->getCapturedStmt(); DSAChecker.Visit(S); if (DSAChecker.isErrorFound()) return StmtError(); // Generate list of implicitly defined firstprivate variables. VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA(); SmallVector<Expr *, 4> ImplicitFirstprivates( DSAChecker.getImplicitFirstprivate().begin(), DSAChecker.getImplicitFirstprivate().end()); SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(), DSAChecker.getImplicitMap().end()); // Mark taskgroup task_reduction descriptors as implicitly firstprivate. for (auto *C : Clauses) { if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) { for (auto *E : IRC->taskgroup_descriptors()) if (E) ImplicitFirstprivates.emplace_back(E); } } if (!ImplicitFirstprivates.empty()) { if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause( ImplicitFirstprivates, SourceLocation(), SourceLocation(), SourceLocation())) { ClausesWithImplicit.push_back(Implicit); ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() != ImplicitFirstprivates.size(); } else ErrorFound = true; } if (!ImplicitMaps.empty()) { if (OMPClause *Implicit = ActOnOpenMPMapClause( OMPC_MAP_unknown, OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true, SourceLocation(), SourceLocation(), ImplicitMaps, SourceLocation(), SourceLocation(), SourceLocation())) { ClausesWithImplicit.emplace_back(Implicit); ErrorFound |= cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size(); } else ErrorFound = true; } } llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers; switch (Kind) { case OMPD_parallel: Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); AllowedNameModifiers.push_back(OMPD_parallel); break; case OMPD_simd: Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); break; case OMPD_for: Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); break; case OMPD_for_simd: Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); break; case OMPD_sections: Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); break; case OMPD_section: assert(ClausesWithImplicit.empty() && "No clauses are allowed for 'omp section' directive"); Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc); break; case OMPD_single: Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); break; case OMPD_master: assert(ClausesWithImplicit.empty() && "No clauses are allowed for 'omp master' directive"); Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc); break; case OMPD_critical: Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt, StartLoc, EndLoc); break; case OMPD_parallel_for: Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); AllowedNameModifiers.push_back(OMPD_parallel); break; case OMPD_parallel_for_simd: Res = ActOnOpenMPParallelForSimdDirective( ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); AllowedNameModifiers.push_back(OMPD_parallel); break; case OMPD_parallel_sections: Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); AllowedNameModifiers.push_back(OMPD_parallel); break; case OMPD_task: Res = ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); AllowedNameModifiers.push_back(OMPD_task); break; case OMPD_taskyield: assert(ClausesWithImplicit.empty() && "No clauses are allowed for 'omp taskyield' directive"); assert(AStmt == nullptr && "No associated statement allowed for 'omp taskyield' directive"); Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc); break; case OMPD_barrier: assert(ClausesWithImplicit.empty() && "No clauses are allowed for 'omp barrier' directive"); assert(AStmt == nullptr && "No associated statement allowed for 'omp barrier' directive"); Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc); break; case OMPD_taskwait: assert(ClausesWithImplicit.empty() && "No clauses are allowed for 'omp taskwait' directive"); assert(AStmt == nullptr && "No associated statement allowed for 'omp taskwait' directive"); Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc); break; case OMPD_taskgroup: Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); break; case OMPD_flush: assert(AStmt == nullptr && "No associated statement allowed for 'omp flush' directive"); Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc); break; case OMPD_ordered: Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); break; case OMPD_atomic: Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); break; case OMPD_teams: Res = ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); break; case OMPD_target: Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); AllowedNameModifiers.push_back(OMPD_target); break; case OMPD_target_parallel: Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); AllowedNameModifiers.push_back(OMPD_target); AllowedNameModifiers.push_back(OMPD_parallel); break; case OMPD_target_parallel_for: Res = ActOnOpenMPTargetParallelForDirective( ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); AllowedNameModifiers.push_back(OMPD_target); AllowedNameModifiers.push_back(OMPD_parallel); break; case OMPD_cancellation_point: assert(ClausesWithImplicit.empty() && "No clauses are allowed for 'omp cancellation point' directive"); assert(AStmt == nullptr && "No associated statement allowed for 'omp " "cancellation point' directive"); Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion); break; case OMPD_cancel: assert(AStmt == nullptr && "No associated statement allowed for 'omp cancel' directive"); Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc, CancelRegion); AllowedNameModifiers.push_back(OMPD_cancel); break; case OMPD_target_data: Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); AllowedNameModifiers.push_back(OMPD_target_data); break; case OMPD_target_enter_data: Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc, EndLoc); AllowedNameModifiers.push_back(OMPD_target_enter_data); break; case OMPD_target_exit_data: Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc, EndLoc); AllowedNameModifiers.push_back(OMPD_target_exit_data); break; case OMPD_taskloop: Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); AllowedNameModifiers.push_back(OMPD_taskloop); break; case OMPD_taskloop_simd: Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); AllowedNameModifiers.push_back(OMPD_taskloop); break; case OMPD_distribute: Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); break; case OMPD_target_update: assert(!AStmt && "Statement is not allowed for target update"); Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, EndLoc); AllowedNameModifiers.push_back(OMPD_target_update); break; case OMPD_distribute_parallel_for: Res = ActOnOpenMPDistributeParallelForDirective( ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); AllowedNameModifiers.push_back(OMPD_parallel); break; case OMPD_distribute_parallel_for_simd: Res = ActOnOpenMPDistributeParallelForSimdDirective( ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); AllowedNameModifiers.push_back(OMPD_parallel); break; case OMPD_distribute_simd: Res = ActOnOpenMPDistributeSimdDirective( ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); break; case OMPD_target_parallel_for_simd: Res = ActOnOpenMPTargetParallelForSimdDirective( ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); AllowedNameModifiers.push_back(OMPD_target); AllowedNameModifiers.push_back(OMPD_parallel); break; case OMPD_target_simd: Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); AllowedNameModifiers.push_back(OMPD_target); break; case OMPD_teams_distribute: Res = ActOnOpenMPTeamsDistributeDirective( ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); break; case OMPD_teams_distribute_simd: Res = ActOnOpenMPTeamsDistributeSimdDirective( ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); break; case OMPD_teams_distribute_parallel_for_simd: Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective( ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); AllowedNameModifiers.push_back(OMPD_parallel); break; case OMPD_teams_distribute_parallel_for: Res = ActOnOpenMPTeamsDistributeParallelForDirective( ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); AllowedNameModifiers.push_back(OMPD_parallel); break; case OMPD_target_teams: Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); AllowedNameModifiers.push_back(OMPD_target); break; case OMPD_target_teams_distribute: Res = ActOnOpenMPTargetTeamsDistributeDirective( ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); AllowedNameModifiers.push_back(OMPD_target); break; case OMPD_target_teams_distribute_parallel_for: Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective( ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); AllowedNameModifiers.push_back(OMPD_target); AllowedNameModifiers.push_back(OMPD_parallel); break; case OMPD_target_teams_distribute_parallel_for_simd: Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); AllowedNameModifiers.push_back(OMPD_target); AllowedNameModifiers.push_back(OMPD_parallel); break; case OMPD_target_teams_distribute_simd: Res = ActOnOpenMPTargetTeamsDistributeSimdDirective( ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); AllowedNameModifiers.push_back(OMPD_target); break; case OMPD_declare_target: case OMPD_end_declare_target: case OMPD_threadprivate: case OMPD_declare_reduction: case OMPD_declare_simd: llvm_unreachable("OpenMP Directive is not allowed"); case OMPD_unknown: llvm_unreachable("Unknown OpenMP directive"); } for (auto P : VarsWithInheritedDSA) { Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable) << P.first << P.second->getSourceRange(); } ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound; if (!AllowedNameModifiers.empty()) ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) || ErrorFound; if (ErrorFound) return StmtError(); return Res; } Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective( DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds, ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears, ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) { assert(Aligneds.size() == Alignments.size()); assert(Linears.size() == LinModifiers.size()); assert(Linears.size() == Steps.size()); if (!DG || DG.get().isNull()) return DeclGroupPtrTy(); if (!DG.get().isSingleDecl()) { Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd); return DG; } auto *ADecl = DG.get().getSingleDecl(); if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl)) ADecl = FTD->getTemplatedDecl(); auto *FD = dyn_cast<FunctionDecl>(ADecl); if (!FD) { Diag(ADecl->getLocation(), diag::err_omp_function_expected); return DeclGroupPtrTy(); } // OpenMP [2.8.2, declare simd construct, Description] // The parameter of the simdlen clause must be a constant positive integer // expression. ExprResult SL; if (Simdlen) SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen); // OpenMP [2.8.2, declare simd construct, Description] // The special this pointer can be used as if was one of the arguments to the // function in any of the linear, aligned, or uniform clauses. // The uniform clause declares one or more arguments to have an invariant // value for all concurrent invocations of the function in the execution of a // single SIMD loop. llvm::DenseMap<Decl *, Expr *> UniformedArgs; Expr *UniformedLinearThis = nullptr; for (auto *E : Uniforms) { E = E->IgnoreParenImpCasts(); if (auto *DRE = dyn_cast<DeclRefExpr>(E)) if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) if (FD->getNumParams() > PVD->getFunctionScopeIndex() && FD->getParamDecl(PVD->getFunctionScopeIndex()) ->getCanonicalDecl() == PVD->getCanonicalDecl()) { UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E)); continue; } if (isa<CXXThisExpr>(E)) { UniformedLinearThis = E; continue; } Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); } // OpenMP [2.8.2, declare simd construct, Description] // The aligned clause declares that the object to which each list item points // is aligned to the number of bytes expressed in the optional parameter of // the aligned clause. // The special this pointer can be used as if was one of the arguments to the // function in any of the linear, aligned, or uniform clauses. // The type of list items appearing in the aligned clause must be array, // pointer, reference to array, or reference to pointer. llvm::DenseMap<Decl *, Expr *> AlignedArgs; Expr *AlignedThis = nullptr; for (auto *E : Aligneds) { E = E->IgnoreParenImpCasts(); if (auto *DRE = dyn_cast<DeclRefExpr>(E)) if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { auto *CanonPVD = PVD->getCanonicalDecl(); if (FD->getNumParams() > PVD->getFunctionScopeIndex() && FD->getParamDecl(PVD->getFunctionScopeIndex()) ->getCanonicalDecl() == CanonPVD) { // OpenMP [2.8.1, simd construct, Restrictions] // A list-item cannot appear in more than one aligned clause. if (AlignedArgs.count(CanonPVD) > 0) { Diag(E->getExprLoc(), diag::err_omp_aligned_twice) << 1 << E->getSourceRange(); Diag(AlignedArgs[CanonPVD]->getExprLoc(), diag::note_omp_explicit_dsa) << getOpenMPClauseName(OMPC_aligned); continue; } AlignedArgs[CanonPVD] = E; QualType QTy = PVD->getType() .getNonReferenceType() .getUnqualifiedType() .getCanonicalType(); const Type *Ty = QTy.getTypePtrOrNull(); if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) { Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr) << QTy << getLangOpts().CPlusPlus << E->getSourceRange(); Diag(PVD->getLocation(), diag::note_previous_decl) << PVD; } continue; } } if (isa<CXXThisExpr>(E)) { if (AlignedThis) { Diag(E->getExprLoc(), diag::err_omp_aligned_twice) << 2 << E->getSourceRange(); Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa) << getOpenMPClauseName(OMPC_aligned); } AlignedThis = E; continue; } Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); } // The optional parameter of the aligned clause, alignment, must be a constant // positive integer expression. If no optional parameter is specified, // implementation-defined default alignments for SIMD instructions on the // target platforms are assumed. SmallVector<Expr *, 4> NewAligns; for (auto *E : Alignments) { ExprResult Align; if (E) Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned); NewAligns.push_back(Align.get()); } // OpenMP [2.8.2, declare simd construct, Description] // The linear clause declares one or more list items to be private to a SIMD // lane and to have a linear relationship with respect to the iteration space // of a loop. // The special this pointer can be used as if was one of the arguments to the // function in any of the linear, aligned, or uniform clauses. // When a linear-step expression is specified in a linear clause it must be // either a constant integer expression or an integer-typed parameter that is // specified in a uniform clause on the directive. llvm::DenseMap<Decl *, Expr *> LinearArgs; const bool IsUniformedThis = UniformedLinearThis != nullptr; auto MI = LinModifiers.begin(); for (auto *E : Linears) { auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI); ++MI; E = E->IgnoreParenImpCasts(); if (auto *DRE = dyn_cast<DeclRefExpr>(E)) if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { auto *CanonPVD = PVD->getCanonicalDecl(); if (FD->getNumParams() > PVD->getFunctionScopeIndex() && FD->getParamDecl(PVD->getFunctionScopeIndex()) ->getCanonicalDecl() == CanonPVD) { // OpenMP [2.15.3.7, linear Clause, Restrictions] // A list-item cannot appear in more than one linear clause. if (LinearArgs.count(CanonPVD) > 0) { Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) << getOpenMPClauseName(OMPC_linear) << getOpenMPClauseName(OMPC_linear) << E->getSourceRange(); Diag(LinearArgs[CanonPVD]->getExprLoc(), diag::note_omp_explicit_dsa) << getOpenMPClauseName(OMPC_linear); continue; } // Each argument can appear in at most one uniform or linear clause. if (UniformedArgs.count(CanonPVD) > 0) { Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) << getOpenMPClauseName(OMPC_linear) << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange(); Diag(UniformedArgs[CanonPVD]->getExprLoc(), diag::note_omp_explicit_dsa) << getOpenMPClauseName(OMPC_uniform); continue; } LinearArgs[CanonPVD] = E; if (E->isValueDependent() || E->isTypeDependent() || E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) continue; (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind, PVD->getOriginalType()); continue; } } if (isa<CXXThisExpr>(E)) { if (UniformedLinearThis) { Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) << getOpenMPClauseName(OMPC_linear) << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear) << E->getSourceRange(); Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa) << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear); continue; } UniformedLinearThis = E; if (E->isValueDependent() || E->isTypeDependent() || E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) continue; (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind, E->getType()); continue; } Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); } Expr *Step = nullptr; Expr *NewStep = nullptr; SmallVector<Expr *, 4> NewSteps; for (auto *E : Steps) { // Skip the same step expression, it was checked already. if (Step == E || !E) { NewSteps.push_back(E ? NewStep : nullptr); continue; } Step = E; if (auto *DRE = dyn_cast<DeclRefExpr>(Step)) if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { auto *CanonPVD = PVD->getCanonicalDecl(); if (UniformedArgs.count(CanonPVD) == 0) { Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param) << Step->getSourceRange(); } else if (E->isValueDependent() || E->isTypeDependent() || E->isInstantiationDependent() || E->containsUnexpandedParameterPack() || CanonPVD->getType()->hasIntegerRepresentation()) NewSteps.push_back(Step); else { Diag(Step->getExprLoc(), diag::err_omp_expected_int_param) << Step->getSourceRange(); } continue; } NewStep = Step; if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && !Step->isInstantiationDependent() && !Step->containsUnexpandedParameterPack()) { NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step) .get(); if (NewStep) NewStep = VerifyIntegerConstantExpression(NewStep).get(); } NewSteps.push_back(NewStep); } auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit( Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()), Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(), const_cast<Expr **>(NewAligns.data()), NewAligns.size(), const_cast<Expr **>(Linears.data()), Linears.size(), const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(), NewSteps.data(), NewSteps.size(), SR); ADecl->addAttr(NewAttr); return ConvertDeclToDeclGroup(ADecl); } StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { if (!AStmt) return StmtError(); CapturedStmt *CS = cast<CapturedStmt>(AStmt); // 1.2.2 OpenMP Language Terminology // Structured block - An executable statement with a single entry at the // top and a single exit at the bottom. // The point of exit cannot be a branch out of the structured block. // longjmp() and throw() must not violate the entry/exit criteria. CS->getCapturedDecl()->setNothrow(); getCurFunction()->setHasBranchProtectedScope(); return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion()); } namespace { /// \brief Helper class for checking canonical form of the OpenMP loops and /// extracting iteration space of each loop in the loop nest, that will be used /// for IR generation. class OpenMPIterationSpaceChecker { /// \brief Reference to Sema. Sema &SemaRef; /// \brief A location for diagnostics (when there is no some better location). SourceLocation DefaultLoc; /// \brief A location for diagnostics (when increment is not compatible). SourceLocation ConditionLoc; /// \brief A source location for referring to loop init later. SourceRange InitSrcRange; /// \brief A source location for referring to condition later. SourceRange ConditionSrcRange; /// \brief A source location for referring to increment later. SourceRange IncrementSrcRange; /// \brief Loop variable. ValueDecl *LCDecl = nullptr; /// \brief Reference to loop variable. Expr *LCRef = nullptr; /// \brief Lower bound (initializer for the var). Expr *LB = nullptr; /// \brief Upper bound. Expr *UB = nullptr; /// \brief Loop step (increment). Expr *Step = nullptr; /// \brief This flag is true when condition is one of: /// Var < UB /// Var <= UB /// UB > Var /// UB >= Var bool TestIsLessOp = false; /// \brief This flag is true when condition is strict ( < or > ). bool TestIsStrictOp = false; /// \brief This flag is true when step is subtracted on each iteration. bool SubtractStep = false; public: OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc) : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {} /// \brief Check init-expr for canonical loop form and save loop counter /// variable - #Var and its initialization value - #LB. bool CheckInit(Stmt *S, bool EmitDiags = true); /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags /// for less/greater and for strict/non-strict comparison. bool CheckCond(Expr *S); /// \brief Check incr-expr for canonical loop form and return true if it /// does not conform, otherwise save loop step (#Step). bool CheckInc(Expr *S); /// \brief Return the loop counter variable. ValueDecl *GetLoopDecl() const { return LCDecl; } /// \brief Return the reference expression to loop counter variable. Expr *GetLoopDeclRefExpr() const { return LCRef; } /// \brief Source range of the loop init. SourceRange GetInitSrcRange() const { return InitSrcRange; } /// \brief Source range of the loop condition. SourceRange GetConditionSrcRange() const { return ConditionSrcRange; } /// \brief Source range of the loop increment. SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; } /// \brief True if the step should be subtracted. bool ShouldSubtractStep() const { return SubtractStep; } /// \brief Build the expression to calculate the number of iterations. Expr * BuildNumIterations(Scope *S, const bool LimitedType, llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const; /// \brief Build the precondition expression for the loops. Expr *BuildPreCond(Scope *S, Expr *Cond, llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const; /// \brief Build reference expression to the counter be used for codegen. DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const; /// \brief Build reference expression to the private counter be used for /// codegen. Expr *BuildPrivateCounterVar() const; /// \brief Build initialization of the counter be used for codegen. Expr *BuildCounterInit() const; /// \brief Build step of the counter be used for codegen. Expr *BuildCounterStep() const; /// \brief Return true if any expression is dependent. bool Dependent() const; private: /// \brief Check the right-hand side of an assignment in the increment /// expression. bool CheckIncRHS(Expr *RHS); /// \brief Helper to set loop counter variable and its initializer. bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB); /// \brief Helper to set upper bound. bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR, SourceLocation SL); /// \brief Helper to set loop increment. bool SetStep(Expr *NewStep, bool Subtract); }; bool OpenMPIterationSpaceChecker::Dependent() const { if (!LCDecl) { assert(!LB && !UB && !Step); return false; } return LCDecl->getType()->isDependentType() || (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) || (Step && Step->isValueDependent()); } bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewLCRefExpr, Expr *NewLB) { // State consistency checking to ensure correct usage. assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr && UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp); if (!NewLCDecl || !NewLB) return true; LCDecl = getCanonicalDecl(NewLCDecl); LCRef = NewLCRefExpr; if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB)) if (const CXXConstructorDecl *Ctor = CE->getConstructor()) if ((Ctor->isCopyOrMoveConstructor() || Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) NewLB = CE->getArg(0)->IgnoreParenImpCasts(); LB = NewLB; return false; } bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR, SourceLocation SL) { // State consistency checking to ensure correct usage. assert(LCDecl != nullptr && LB != nullptr && UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp); if (!NewUB) return true; UB = NewUB; TestIsLessOp = LessOp; TestIsStrictOp = StrictOp; ConditionSrcRange = SR; ConditionLoc = SL; return false; } bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) { // State consistency checking to ensure correct usage. assert(LCDecl != nullptr && LB != nullptr && Step == nullptr); if (!NewStep) return true; if (!NewStep->isValueDependent()) { // Check that the step is integer expression. SourceLocation StepLoc = NewStep->getLocStart(); ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion( StepLoc, getExprAsWritten(NewStep)); if (Val.isInvalid()) return true; NewStep = Val.get(); // OpenMP [2.6, Canonical Loop Form, Restrictions] // If test-expr is of form var relational-op b and relational-op is < or // <= then incr-expr must cause var to increase on each iteration of the // loop. If test-expr is of form var relational-op b and relational-op is // > or >= then incr-expr must cause var to decrease on each iteration of // the loop. // If test-expr is of form b relational-op var and relational-op is < or // <= then incr-expr must cause var to decrease on each iteration of the // loop. If test-expr is of form b relational-op var and relational-op is // > or >= then incr-expr must cause var to increase on each iteration of // the loop. llvm::APSInt Result; bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context); bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation(); bool IsConstNeg = IsConstant && Result.isSigned() && (Subtract != Result.isNegative()); bool IsConstPos = IsConstant && Result.isSigned() && (Subtract == Result.isNegative()); bool IsConstZero = IsConstant && !Result.getBoolValue(); if (UB && (IsConstZero || (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract)) : (IsConstPos || (IsUnsigned && !Subtract))))) { SemaRef.Diag(NewStep->getExprLoc(), diag::err_omp_loop_incr_not_compatible) << LCDecl << TestIsLessOp << NewStep->getSourceRange(); SemaRef.Diag(ConditionLoc, diag::note_omp_loop_cond_requres_compatible_incr) << TestIsLessOp << ConditionSrcRange; return true; } if (TestIsLessOp == Subtract) { NewStep = SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep) .get(); Subtract = !Subtract; } } Step = NewStep; SubtractStep = Subtract; return false; } bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) { // Check init-expr for canonical loop form and save loop counter // variable - #Var and its initialization value - #LB. // OpenMP [2.6] Canonical loop form. init-expr may be one of the following: // var = lb // integer-type var = lb // random-access-iterator-type var = lb // pointer-type var = lb // if (!S) { if (EmitDiags) { SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init); } return true; } if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S)) if (!ExprTemp->cleanupsHaveSideEffects()) S = ExprTemp->getSubExpr(); InitSrcRange = S->getSourceRange(); if (Expr *E = dyn_cast<Expr>(S)) S = E->IgnoreParens(); if (auto *BO = dyn_cast<BinaryOperator>(S)) { if (BO->getOpcode() == BO_Assign) { auto *LHS = BO->getLHS()->IgnoreParens(); if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) { if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl())) if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS()); } if (auto *ME = dyn_cast<MemberExpr>(LHS)) { if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); } } } else if (auto *DS = dyn_cast<DeclStmt>(S)) { if (DS->isSingleDecl()) { if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) { if (Var->hasInit() && !Var->getType()->isReferenceType()) { // Accept non-canonical init form here but emit ext. warning. if (Var->getInitStyle() != VarDecl::CInit && EmitDiags) SemaRef.Diag(S->getLocStart(), diag::ext_omp_loop_not_canonical_init) << S->getSourceRange(); return SetLCDeclAndLB(Var, nullptr, Var->getInit()); } } } } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { if (CE->getOperator() == OO_Equal) { auto *LHS = CE->getArg(0); if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) { if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl())) if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1)); } if (auto *ME = dyn_cast<MemberExpr>(LHS)) { if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); } } } if (Dependent() || SemaRef.CurContext->isDependentContext()) return false; if (EmitDiags) { SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init) << S->getSourceRange(); } return true; } /// \brief Ignore parenthesizes, implicit casts, copy constructor and return the /// variable (which may be the loop variable) if possible. static const ValueDecl *GetInitLCDecl(Expr *E) { if (!E) return nullptr; E = getExprAsWritten(E); if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E)) if (const CXXConstructorDecl *Ctor = CE->getConstructor()) if ((Ctor->isCopyOrMoveConstructor() || Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) E = CE->getArg(0)->IgnoreParenImpCasts(); if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) { if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) return getCanonicalDecl(VD); } if (auto *ME = dyn_cast_or_null<MemberExpr>(E)) if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) return getCanonicalDecl(ME->getMemberDecl()); return nullptr; } bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) { // Check test-expr for canonical form, save upper-bound UB, flags for // less/greater and for strict/non-strict comparison. // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following: // var relational-op b // b relational-op var // if (!S) { SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl; return true; } S = getExprAsWritten(S); SourceLocation CondLoc = S->getLocStart(); if (auto *BO = dyn_cast<BinaryOperator>(S)) { if (BO->isRelationalOp()) { if (GetInitLCDecl(BO->getLHS()) == LCDecl) return SetUB(BO->getRHS(), (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE), (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT), BO->getSourceRange(), BO->getOperatorLoc()); if (GetInitLCDecl(BO->getRHS()) == LCDecl) return SetUB(BO->getLHS(), (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE), (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT), BO->getSourceRange(), BO->getOperatorLoc()); } } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { if (CE->getNumArgs() == 2) { auto Op = CE->getOperator(); switch (Op) { case OO_Greater: case OO_GreaterEqual: case OO_Less: case OO_LessEqual: if (GetInitLCDecl(CE->getArg(0)) == LCDecl) return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual, Op == OO_Less || Op == OO_Greater, CE->getSourceRange(), CE->getOperatorLoc()); if (GetInitLCDecl(CE->getArg(1)) == LCDecl) return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual, Op == OO_Less || Op == OO_Greater, CE->getSourceRange(), CE->getOperatorLoc()); break; default: break; } } } if (Dependent() || SemaRef.CurContext->isDependentContext()) return false; SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond) << S->getSourceRange() << LCDecl; return true; } bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) { // RHS of canonical loop form increment can be: // var + incr // incr + var // var - incr // RHS = RHS->IgnoreParenImpCasts(); if (auto *BO = dyn_cast<BinaryOperator>(RHS)) { if (BO->isAdditiveOp()) { bool IsAdd = BO->getOpcode() == BO_Add; if (GetInitLCDecl(BO->getLHS()) == LCDecl) return SetStep(BO->getRHS(), !IsAdd); if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl) return SetStep(BO->getLHS(), false); } } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) { bool IsAdd = CE->getOperator() == OO_Plus; if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) { if (GetInitLCDecl(CE->getArg(0)) == LCDecl) return SetStep(CE->getArg(1), !IsAdd); if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl) return SetStep(CE->getArg(0), false); } } if (Dependent() || SemaRef.CurContext->isDependentContext()) return false; SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr) << RHS->getSourceRange() << LCDecl; return true; } bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) { // Check incr-expr for canonical loop form and return true if it // does not conform. // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following: // ++var // var++ // --var // var-- // var += incr // var -= incr // var = var + incr // var = incr + var // var = var - incr // if (!S) { SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl; return true; } if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S)) if (!ExprTemp->cleanupsHaveSideEffects()) S = ExprTemp->getSubExpr(); IncrementSrcRange = S->getSourceRange(); S = S->IgnoreParens(); if (auto *UO = dyn_cast<UnaryOperator>(S)) { if (UO->isIncrementDecrementOp() && GetInitLCDecl(UO->getSubExpr()) == LCDecl) return SetStep(SemaRef .ActOnIntegerConstant(UO->getLocStart(), (UO->isDecrementOp() ? -1 : 1)) .get(), false); } else if (auto *BO = dyn_cast<BinaryOperator>(S)) { switch (BO->getOpcode()) { case BO_AddAssign: case BO_SubAssign: if (GetInitLCDecl(BO->getLHS()) == LCDecl) return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign); break; case BO_Assign: if (GetInitLCDecl(BO->getLHS()) == LCDecl) return CheckIncRHS(BO->getRHS()); break; default: break; } } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { switch (CE->getOperator()) { case OO_PlusPlus: case OO_MinusMinus: if (GetInitLCDecl(CE->getArg(0)) == LCDecl) return SetStep(SemaRef .ActOnIntegerConstant( CE->getLocStart(), ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)) .get(), false); break; case OO_PlusEqual: case OO_MinusEqual: if (GetInitLCDecl(CE->getArg(0)) == LCDecl) return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual); break; case OO_Equal: if (GetInitLCDecl(CE->getArg(0)) == LCDecl) return CheckIncRHS(CE->getArg(1)); break; default: break; } } if (Dependent() || SemaRef.CurContext->isDependentContext()) return false; SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr) << S->getSourceRange() << LCDecl; return true; } static ExprResult tryBuildCapture(Sema &SemaRef, Expr *Capture, llvm::MapVector<Expr *, DeclRefExpr *> &Captures) { if (SemaRef.CurContext->isDependentContext()) return ExprResult(Capture); if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects)) return SemaRef.PerformImplicitConversion( Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting, /*AllowExplicit=*/true); auto I = Captures.find(Capture); if (I != Captures.end()) return buildCapture(SemaRef, Capture, I->second); DeclRefExpr *Ref = nullptr; ExprResult Res = buildCapture(SemaRef, Capture, Ref); Captures[Capture] = Ref; return Res; } /// \brief Build the expression to calculate the number of iterations. Expr *OpenMPIterationSpaceChecker::BuildNumIterations( Scope *S, const bool LimitedType, llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const { ExprResult Diff; auto VarType = LCDecl->getType().getNonReferenceType(); if (VarType->isIntegerType() || VarType->isPointerType() || SemaRef.getLangOpts().CPlusPlus) { // Upper - Lower auto *UBExpr = TestIsLessOp ? UB : LB; auto *LBExpr = TestIsLessOp ? LB : UB; Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get(); Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get(); if (!Upper || !Lower) return nullptr; Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower); if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) { // BuildBinOp already emitted error, this one is to point user to upper // and lower bound, and to tell what is passed to 'operator-'. SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx) << Upper->getSourceRange() << Lower->getSourceRange(); return nullptr; } } if (!Diff.isUsable()) return nullptr; // Upper - Lower [- 1] if (TestIsStrictOp) Diff = SemaRef.BuildBinOp( S, DefaultLoc, BO_Sub, Diff.get(), SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); if (!Diff.isUsable()) return nullptr; // Upper - Lower [- 1] + Step auto NewStep = tryBuildCapture(SemaRef, Step, Captures); if (!NewStep.isUsable()) return nullptr; Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get()); if (!Diff.isUsable()) return nullptr; // Parentheses (for dumping/debugging purposes only). Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); if (!Diff.isUsable()) return nullptr; // (Upper - Lower [- 1] + Step) / Step Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get()); if (!Diff.isUsable()) return nullptr; // OpenMP runtime requires 32-bit or 64-bit loop variables. QualType Type = Diff.get()->getType(); auto &C = SemaRef.Context; bool UseVarType = VarType->hasIntegerRepresentation() && C.getTypeSize(Type) > C.getTypeSize(VarType); if (!Type->isIntegerType() || UseVarType) { unsigned NewSize = UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type); bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation() : Type->hasSignedIntegerRepresentation(); Type = C.getIntTypeForBitwidth(NewSize, IsSigned); if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) { Diff = SemaRef.PerformImplicitConversion( Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true); if (!Diff.isUsable()) return nullptr; } } if (LimitedType) { unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32; if (NewSize != C.getTypeSize(Type)) { if (NewSize < C.getTypeSize(Type)) { assert(NewSize == 64 && "incorrect loop var size"); SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var) << InitSrcRange << ConditionSrcRange; } QualType NewType = C.getIntTypeForBitwidth( NewSize, Type->hasSignedIntegerRepresentation() || C.getTypeSize(Type) < NewSize); if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) { Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType, Sema::AA_Converting, true); if (!Diff.isUsable()) return nullptr; } } } return Diff.get(); } Expr *OpenMPIterationSpaceChecker::BuildPreCond( Scope *S, Expr *Cond, llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const { // Try to build LB <op> UB, where <op> is <, >, <=, or >=. bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics(); SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true); auto NewLB = tryBuildCapture(SemaRef, LB, Captures); auto NewUB = tryBuildCapture(SemaRef, UB, Captures); if (!NewLB.isUsable() || !NewUB.isUsable()) return nullptr; auto CondExpr = SemaRef.BuildBinOp( S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE) : (TestIsStrictOp ? BO_GT : BO_GE), NewLB.get(), NewUB.get()); if (CondExpr.isUsable()) { if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(), SemaRef.Context.BoolTy)) CondExpr = SemaRef.PerformImplicitConversion( CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting, /*AllowExplicit=*/true); } SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress); // Otherwise use original loop conditon and evaluate it in runtime. return CondExpr.isUsable() ? CondExpr.get() : Cond; } /// \brief Build reference expression to the counter be used for codegen. DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar( llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const { auto *VD = dyn_cast<VarDecl>(LCDecl); if (!VD) { VD = SemaRef.IsOpenMPCapturedDecl(LCDecl); auto *Ref = buildDeclRefExpr( SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc); DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false); // If the loop control decl is explicitly marked as private, do not mark it // as captured again. if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr) Captures.insert(std::make_pair(LCRef, Ref)); return Ref; } return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc); } Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const { if (LCDecl && !LCDecl->isInvalidDecl()) { auto Type = LCDecl->getType().getNonReferenceType(); auto *PrivateVar = buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(), LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr); if (PrivateVar->isInvalidDecl()) return nullptr; return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc); } return nullptr; } /// \brief Build initialization of the counter to be used for codegen. Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; } /// \brief Build step of the counter be used for codegen. Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; } /// \brief Iteration space of a single for loop. struct LoopIterationSpace final { /// \brief Condition of the loop. Expr *PreCond = nullptr; /// \brief This expression calculates the number of iterations in the loop. /// It is always possible to calculate it before starting the loop. Expr *NumIterations = nullptr; /// \brief The loop counter variable. Expr *CounterVar = nullptr; /// \brief Private loop counter variable. Expr *PrivateCounterVar = nullptr; /// \brief This is initializer for the initial value of #CounterVar. Expr *CounterInit = nullptr; /// \brief This is step for the #CounterVar used to generate its update: /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration. Expr *CounterStep = nullptr; /// \brief Should step be subtracted? bool Subtract = false; /// \brief Source range of the loop init. SourceRange InitSrcRange; /// \brief Source range of the loop condition. SourceRange CondSrcRange; /// \brief Source range of the loop increment. SourceRange IncSrcRange; }; } // namespace void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) { assert(getLangOpts().OpenMP && "OpenMP is not active."); assert(Init && "Expected loop in canonical form."); unsigned AssociatedLoops = DSAStack->getAssociatedLoops(); if (AssociatedLoops > 0 && isOpenMPLoopDirective(DSAStack->getCurrentDirective())) { OpenMPIterationSpaceChecker ISC(*this, ForLoc); if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) { if (auto *D = ISC.GetLoopDecl()) { auto *VD = dyn_cast<VarDecl>(D); if (!VD) { if (auto *Private = IsOpenMPCapturedDecl(D)) VD = Private; else { auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(), /*WithInit=*/false); VD = cast<VarDecl>(Ref->getDecl()); } } DSAStack->addLoopControlVariable(D, VD); } } DSAStack->setAssociatedLoops(AssociatedLoops - 1); } } /// \brief Called on a for stmt to check and extract its iteration space /// for further processing (such as collapsing). static bool CheckOpenMPIterationSpace( OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA, unsigned CurrentNestedLoopCount, unsigned NestedLoopCount, Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr, llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA, LoopIterationSpace &ResultIterSpace, llvm::MapVector<Expr *, DeclRefExpr *> &Captures) { // OpenMP [2.6, Canonical Loop Form] // for (init-expr; test-expr; incr-expr) structured-block auto *For = dyn_cast_or_null<ForStmt>(S); if (!For) { SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for) << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr) << getOpenMPDirectiveName(DKind) << NestedLoopCount << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount; if (NestedLoopCount > 1) { if (CollapseLoopCountExpr && OrderedLoopCountExpr) SemaRef.Diag(DSA.getConstructLoc(), diag::note_omp_collapse_ordered_expr) << 2 << CollapseLoopCountExpr->getSourceRange() << OrderedLoopCountExpr->getSourceRange(); else if (CollapseLoopCountExpr) SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), diag::note_omp_collapse_ordered_expr) << 0 << CollapseLoopCountExpr->getSourceRange(); else SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), diag::note_omp_collapse_ordered_expr) << 1 << OrderedLoopCountExpr->getSourceRange(); } return true; } assert(For->getBody()); OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc()); // Check init. auto Init = For->getInit(); if (ISC.CheckInit(Init)) return true; bool HasErrors = false; // Check loop variable's type. if (auto *LCDecl = ISC.GetLoopDecl()) { auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr(); // OpenMP [2.6, Canonical Loop Form] // Var is one of the following: // A variable of signed or unsigned integer type. // For C++, a variable of a random access iterator type. // For C, a variable of a pointer type. auto VarType = LCDecl->getType().getNonReferenceType(); if (!VarType->isDependentType() && !VarType->isIntegerType() && !VarType->isPointerType() && !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) { SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type) << SemaRef.getLangOpts().CPlusPlus; HasErrors = true; } // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in // a Construct // The loop iteration variable(s) in the associated for-loop(s) of a for or // parallel for construct is (are) private. // The loop iteration variable in the associated for-loop of a simd // construct with just one associated for-loop is linear with a // constant-linear-step that is the increment of the associated for-loop. // Exclude loop var from the list of variables with implicitly defined data // sharing attributes. VarsWithImplicitDSA.erase(LCDecl); // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced // in a Construct, C/C++]. // The loop iteration variable in the associated for-loop of a simd // construct with just one associated for-loop may be listed in a linear // clause with a constant-linear-step that is the increment of the // associated for-loop. // The loop iteration variable(s) in the associated for-loop(s) of a for or // parallel for construct may be listed in a private or lastprivate clause. DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false); // If LoopVarRefExpr is nullptr it means the corresponding loop variable is // declared in the loop and it is predetermined as a private. auto PredeterminedCKind = isOpenMPSimdDirective(DKind) ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate) : OMPC_private; if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && DVar.CKind != PredeterminedCKind) || ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop || isOpenMPDistributeDirective(DKind)) && !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) && (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) { SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa) << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(PredeterminedCKind); if (DVar.RefExpr == nullptr) DVar.CKind = PredeterminedCKind; ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true); HasErrors = true; } else if (LoopDeclRefExpr != nullptr) { // Make the loop iteration variable private (for worksharing constructs), // linear (for simd directives with the only one associated loop) or // lastprivate (for simd directives with several collapsed or ordered // loops). if (DVar.CKind == OMPC_unknown) DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; }, /*FromParent=*/false); DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind); } assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars"); // Check test-expr. HasErrors |= ISC.CheckCond(For->getCond()); // Check incr-expr. HasErrors |= ISC.CheckInc(For->getInc()); } if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors) return HasErrors; // Build the loop's iteration space representation. ResultIterSpace.PreCond = ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures); ResultIterSpace.NumIterations = ISC.BuildNumIterations( DSA.getCurScope(), (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)), Captures); ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA); ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar(); ResultIterSpace.CounterInit = ISC.BuildCounterInit(); ResultIterSpace.CounterStep = ISC.BuildCounterStep(); ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange(); ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange(); ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange(); ResultIterSpace.Subtract = ISC.ShouldSubtractStep(); HasErrors |= (ResultIterSpace.PreCond == nullptr || ResultIterSpace.NumIterations == nullptr || ResultIterSpace.CounterVar == nullptr || ResultIterSpace.PrivateCounterVar == nullptr || ResultIterSpace.CounterInit == nullptr || ResultIterSpace.CounterStep == nullptr); return HasErrors; } /// \brief Build 'VarRef = Start. static ExprResult BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef, ExprResult Start, llvm::MapVector<Expr *, DeclRefExpr *> &Captures) { // Build 'VarRef = Start. auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures); if (!NewStart.isUsable()) return ExprError(); if (!SemaRef.Context.hasSameType(NewStart.get()->getType(), VarRef.get()->getType())) { NewStart = SemaRef.PerformImplicitConversion( NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting, /*AllowExplicit=*/true); if (!NewStart.isUsable()) return ExprError(); } auto Init = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); return Init; } /// \brief Build 'VarRef = Start + Iter * Step'. static ExprResult BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef, ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract, llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) { // Add parentheses (for debugging purposes only). Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get()); if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() || !Step.isUsable()) return ExprError(); ExprResult NewStep = Step; if (Captures) NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures); if (NewStep.isInvalid()) return ExprError(); ExprResult Update = SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get()); if (!Update.isUsable()) return ExprError(); // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or // 'VarRef = Start (+|-) Iter * Step'. ExprResult NewStart = Start; if (Captures) NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures); if (NewStart.isInvalid()) return ExprError(); // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'. ExprResult SavedUpdate = Update; ExprResult UpdateVal; if (VarRef.get()->getType()->isOverloadableType() || NewStart.get()->getType()->isOverloadableType() || Update.get()->getType()->isOverloadableType()) { bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics(); SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true); Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); if (Update.isUsable()) { UpdateVal = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign, VarRef.get(), SavedUpdate.get()); if (UpdateVal.isUsable()) { Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(), UpdateVal.get()); } } SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress); } // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'. if (!Update.isUsable() || !UpdateVal.isUsable()) { Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add, NewStart.get(), SavedUpdate.get()); if (!Update.isUsable()) return ExprError(); if (!SemaRef.Context.hasSameType(Update.get()->getType(), VarRef.get()->getType())) { Update = SemaRef.PerformImplicitConversion( Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true); if (!Update.isUsable()) return ExprError(); } Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get()); } return Update; } /// \brief Convert integer expression \a E to make it have at least \a Bits /// bits. static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) { if (E == nullptr) return ExprError(); auto &C = SemaRef.Context; QualType OldType = E->getType(); unsigned HasBits = C.getTypeSize(OldType); if (HasBits >= Bits) return ExprResult(E); // OK to convert to signed, because new type has more bits than old. QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true); return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting, true); } /// \brief Check if the given expression \a E is a constant integer that fits /// into \a Bits bits. static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) { if (E == nullptr) return false; llvm::APSInt Result; if (E->isIntegerConstantExpr(Result, SemaRef.Context)) return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits); return false; } /// Build preinits statement for the given declarations. static Stmt *buildPreInits(ASTContext &Context, SmallVectorImpl<Decl *> &PreInits) { if (!PreInits.empty()) { return new (Context) DeclStmt( DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()), SourceLocation(), SourceLocation()); } return nullptr; } /// Build preinits statement for the given declarations. static Stmt *buildPreInits(ASTContext &Context, llvm::MapVector<Expr *, DeclRefExpr *> &Captures) { if (!Captures.empty()) { SmallVector<Decl *, 16> PreInits; for (auto &Pair : Captures) PreInits.push_back(Pair.second->getDecl()); return buildPreInits(Context, PreInits); } return nullptr; } /// Build postupdate expression for the given list of postupdates expressions. static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) { Expr *PostUpdate = nullptr; if (!PostUpdates.empty()) { for (auto *E : PostUpdates) { Expr *ConvE = S.BuildCStyleCastExpr( E->getExprLoc(), S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy), E->getExprLoc(), E) .get(); PostUpdate = PostUpdate ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma, PostUpdate, ConvE) .get() : ConvE; } } return PostUpdate; } /// \brief Called on a for stmt to check itself and nested loops (if any). /// \return Returns 0 if one of the collapsed stmts is not canonical for loop, /// number of collapsed loops otherwise. static unsigned CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef, DSAStackTy &DSA, llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA, OMPLoopDirective::HelperExprs &Built) { unsigned NestedLoopCount = 1; if (CollapseLoopCountExpr) { // Found 'collapse' clause - calculate collapse number. llvm::APSInt Result; if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) NestedLoopCount = Result.getLimitedValue(); } if (OrderedLoopCountExpr) { // Found 'ordered' clause - calculate collapse number. llvm::APSInt Result; if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) { if (Result.getLimitedValue() < NestedLoopCount) { SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), diag::err_omp_wrong_ordered_loop_count) << OrderedLoopCountExpr->getSourceRange(); SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), diag::note_collapse_loop_count) << CollapseLoopCountExpr->getSourceRange(); } NestedLoopCount = Result.getLimitedValue(); } } // This is helper routine for loop directives (e.g., 'for', 'simd', // 'for simd', etc.). llvm::MapVector<Expr *, DeclRefExpr *> Captures; SmallVector<LoopIterationSpace, 4> IterSpaces; IterSpaces.resize(NestedLoopCount); Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true); for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) { if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount, CollapseLoopCountExpr, OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt], Captures)) return 0; // Move on to the next nested for loop, or to the loop body. // OpenMP [2.8.1, simd construct, Restrictions] // All loops associated with the construct must be perfectly nested; that // is, there must be no intervening code nor any OpenMP directive between // any two loops. CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers(); } Built.clear(/* size */ NestedLoopCount); if (SemaRef.CurContext->isDependentContext()) return NestedLoopCount; // An example of what is generated for the following code: // // #pragma omp simd collapse(2) ordered(2) // for (i = 0; i < NI; ++i) // for (k = 0; k < NK; ++k) // for (j = J0; j < NJ; j+=2) { // <loop body> // } // // We generate the code below. // Note: the loop body may be outlined in CodeGen. // Note: some counters may be C++ classes, operator- is used to find number of // iterations and operator+= to calculate counter value. // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32 // or i64 is currently supported). // // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2)) // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) { // .local.i = IV / ((NJ - J0 - 1 + 2) / 2); // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2; // // similar updates for vars in clauses (e.g. 'linear') // <loop body (using local i and j)> // } // i = NI; // assign final values of counters // j = NJ; // // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are // the iteration counts of the collapsed for loops. // Precondition tests if there is at least one iteration (all conditions are // true). auto PreCond = ExprResult(IterSpaces[0].PreCond); auto N0 = IterSpaces[0].NumIterations; ExprResult LastIteration32 = WidenIterationCount( 32 /* Bits */, SemaRef .PerformImplicitConversion( N0->IgnoreImpCasts(), N0->getType(), Sema::AA_Converting, /*AllowExplicit=*/true) .get(), SemaRef); ExprResult LastIteration64 = WidenIterationCount( 64 /* Bits */, SemaRef .PerformImplicitConversion( N0->IgnoreImpCasts(), N0->getType(), Sema::AA_Converting, /*AllowExplicit=*/true) .get(), SemaRef); if (!LastIteration32.isUsable() || !LastIteration64.isUsable()) return NestedLoopCount; auto &C = SemaRef.Context; bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32; Scope *CurScope = DSA.getCurScope(); for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) { if (PreCond.isUsable()) { PreCond = SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd, PreCond.get(), IterSpaces[Cnt].PreCond); } auto N = IterSpaces[Cnt].NumIterations; SourceLocation Loc = N->getExprLoc(); AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32; if (LastIteration32.isUsable()) LastIteration32 = SemaRef.BuildBinOp( CurScope, Loc, BO_Mul, LastIteration32.get(), SemaRef .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), Sema::AA_Converting, /*AllowExplicit=*/true) .get()); if (LastIteration64.isUsable()) LastIteration64 = SemaRef.BuildBinOp( CurScope, Loc, BO_Mul, LastIteration64.get(), SemaRef .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), Sema::AA_Converting, /*AllowExplicit=*/true) .get()); } // Choose either the 32-bit or 64-bit version. ExprResult LastIteration = LastIteration64; if (LastIteration32.isUsable() && C.getTypeSize(LastIteration32.get()->getType()) == 32 && (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 || FitsInto( 32 /* Bits */, LastIteration32.get()->getType()->hasSignedIntegerRepresentation(), LastIteration64.get(), SemaRef))) LastIteration = LastIteration32; QualType VType = LastIteration.get()->getType(); QualType RealVType = VType; QualType StrideVType = VType; if (isOpenMPTaskLoopDirective(DKind)) { VType = SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0); StrideVType = SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1); } if (!LastIteration.isUsable()) return 0; // Save the number of iterations. ExprResult NumIterations = LastIteration; { LastIteration = SemaRef.BuildBinOp( CurScope, LastIteration.get()->getExprLoc(), BO_Sub, LastIteration.get(), SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); if (!LastIteration.isUsable()) return 0; } // Calculate the last iteration number beforehand instead of doing this on // each iteration. Do not do this if the number of iterations may be kfold-ed. llvm::APSInt Result; bool IsConstant = LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context); ExprResult CalcLastIteration; if (!IsConstant) { ExprResult SaveRef = tryBuildCapture(SemaRef, LastIteration.get(), Captures); LastIteration = SaveRef; // Prepare SaveRef + 1. NumIterations = SemaRef.BuildBinOp( CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(), SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); if (!NumIterations.isUsable()) return 0; } SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin(); // Build variables passed into runtime, necessary for worksharing directives. ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB; if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)) { // Lower bound variable, initialized with zero. VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb"); LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc); SemaRef.AddInitializerToDecl(LBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), /*DirectInit*/ false); // Upper bound variable, initialized with last iteration number. VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub"); UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc); SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(), /*DirectInit*/ false); // A 32-bit variable-flag where runtime returns 1 for the last iteration. // This will be used to implement clause 'lastprivate'. QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true); VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last"); IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc); SemaRef.AddInitializerToDecl(ILDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), /*DirectInit*/ false); // Stride variable returned by runtime (we initialize it to 1 by default). VarDecl *STDecl = buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride"); ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc); SemaRef.AddInitializerToDecl(STDecl, SemaRef.ActOnIntegerConstant(InitLoc, 1).get(), /*DirectInit*/ false); // Build expression: UB = min(UB, LastIteration) // It is necessary for CodeGen of directives with static scheduling. ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT, UB.get(), LastIteration.get()); ExprResult CondOp = SemaRef.ActOnConditionalOp( InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get()); EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(), CondOp.get()); EUB = SemaRef.ActOnFinishFullExpr(EUB.get()); // If we have a combined directive that combines 'distribute', 'for' or // 'simd' we need to be able to access the bounds of the schedule of the // enclosing region. E.g. in 'distribute parallel for' the bounds obtained // by scheduling 'distribute' have to be passed to the schedule of 'for'. if (isOpenMPLoopBoundSharingDirective(DKind)) { // Lower bound variable, initialized with zero. VarDecl *CombLBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb"); CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc); SemaRef.AddInitializerToDecl( CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), /*DirectInit*/ false); // Upper bound variable, initialized with last iteration number. VarDecl *CombUBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub"); CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc); SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(), /*DirectInit*/ false); ExprResult CombIsUBGreater = SemaRef.BuildBinOp( CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get()); ExprResult CombCondOp = SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(), LastIteration.get(), CombUB.get()); CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(), CombCondOp.get()); CombEUB = SemaRef.ActOnFinishFullExpr(CombEUB.get()); auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl(); // We expect to have at least 2 more parameters than the 'parallel' // directive does - the lower and upper bounds of the previous schedule. assert(CD->getNumParams() >= 4 && "Unexpected number of parameters in loop combined directive"); // Set the proper type for the bounds given what we learned from the // enclosed loops. auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2); auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3); // Previous lower and upper bounds are obtained from the region // parameters. PrevLB = buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc); PrevUB = buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc); } } // Build the iteration variable and its initialization before loop. ExprResult IV; ExprResult Init, CombInit; { VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv"); IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc); Expr *RHS = (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)) ? LB.get() : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get(); Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS); Init = SemaRef.ActOnFinishFullExpr(Init.get()); if (isOpenMPLoopBoundSharingDirective(DKind)) { Expr *CombRHS = (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)) ? CombLB.get() : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get(); CombInit = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS); CombInit = SemaRef.ActOnFinishFullExpr(CombInit.get()); } } // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops. SourceLocation CondLoc; ExprResult Cond = (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)) ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get()) : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(), NumIterations.get()); ExprResult CombCond; if (isOpenMPLoopBoundSharingDirective(DKind)) { CombCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), CombUB.get()); } // Loop increment (IV = IV + 1) SourceLocation IncLoc; ExprResult Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(), SemaRef.ActOnIntegerConstant(IncLoc, 1).get()); if (!Inc.isUsable()) return 0; Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get()); Inc = SemaRef.ActOnFinishFullExpr(Inc.get()); if (!Inc.isUsable()) return 0; // Increments for worksharing loops (LB = LB + ST; UB = UB + ST). // Used for directives with static scheduling. // In combined construct, add combined version that use CombLB and CombUB // base variables for the update ExprResult NextLB, NextUB, CombNextLB, CombNextUB; if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)) { // LB + ST NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get()); if (!NextLB.isUsable()) return 0; // LB = LB + ST NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get()); NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get()); if (!NextLB.isUsable()) return 0; // UB + ST NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get()); if (!NextUB.isUsable()) return 0; // UB = UB + ST NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get()); NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get()); if (!NextUB.isUsable()) return 0; if (isOpenMPLoopBoundSharingDirective(DKind)) { CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get()); if (!NextLB.isUsable()) return 0; // LB = LB + ST CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(), CombNextLB.get()); CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get()); if (!CombNextLB.isUsable()) return 0; // UB + ST CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get()); if (!CombNextUB.isUsable()) return 0; // UB = UB + ST CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(), CombNextUB.get()); CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get()); if (!CombNextUB.isUsable()) return 0; } } // Create increment expression for distribute loop when combined in a same // directive with for as IV = IV + ST; ensure upper bound expression based // on PrevUB instead of NumIterations - used to implement 'for' when found // in combination with 'distribute', like in 'distribute parallel for' SourceLocation DistIncLoc; ExprResult DistCond, DistInc, PrevEUB; if (isOpenMPLoopBoundSharingDirective(DKind)) { DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get()); assert(DistCond.isUsable() && "distribute cond expr was not built"); DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get()); assert(DistInc.isUsable() && "distribute inc expr was not built"); DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(), DistInc.get()); DistInc = SemaRef.ActOnFinishFullExpr(DistInc.get()); assert(DistInc.isUsable() && "distribute inc expr was not built"); // Build expression: UB = min(UB, prevUB) for #for in composite or combined // construct SourceLocation DistEUBLoc; ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get()); ExprResult CondOp = SemaRef.ActOnConditionalOp( DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get()); PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(), CondOp.get()); PrevEUB = SemaRef.ActOnFinishFullExpr(PrevEUB.get()); } // Build updates and final values of the loop counters. bool HasErrors = false; Built.Counters.resize(NestedLoopCount); Built.Inits.resize(NestedLoopCount); Built.Updates.resize(NestedLoopCount); Built.Finals.resize(NestedLoopCount); SmallVector<Expr *, 4> LoopMultipliers; { ExprResult Div; // Go from inner nested loop to outer. for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) { LoopIterationSpace &IS = IterSpaces[Cnt]; SourceLocation UpdLoc = IS.IncSrcRange.getBegin(); // Build: Iter = (IV / Div) % IS.NumIters // where Div is product of previous iterations' IS.NumIters. ExprResult Iter; if (Div.isUsable()) { Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get()); } else { Iter = IV; assert((Cnt == (int)NestedLoopCount - 1) && "unusable div expected on first iteration only"); } if (Cnt != 0 && Iter.isUsable()) Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(), IS.NumIterations); if (!Iter.isUsable()) { HasErrors = true; break; } // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl()); auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(), /*RefersToCapture=*/true); ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Captures); if (!Init.isUsable()) { HasErrors = true; break; } ExprResult Update = BuildCounterUpdate( SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter, IS.CounterStep, IS.Subtract, &Captures); if (!Update.isUsable()) { HasErrors = true; break; } // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step ExprResult Final = BuildCounterUpdate( SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures); if (!Final.isUsable()) { HasErrors = true; break; } // Build Div for the next iteration: Div <- Div * IS.NumIters if (Cnt != 0) { if (Div.isUnset()) Div = IS.NumIterations; else Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(), IS.NumIterations); // Add parentheses (for debugging purposes only). if (Div.isUsable()) Div = tryBuildCapture(SemaRef, Div.get(), Captures); if (!Div.isUsable()) { HasErrors = true; break; } LoopMultipliers.push_back(Div.get()); } if (!Update.isUsable() || !Final.isUsable()) { HasErrors = true; break; } // Save results Built.Counters[Cnt] = IS.CounterVar; Built.PrivateCounters[Cnt] = IS.PrivateCounterVar; Built.Inits[Cnt] = Init.get(); Built.Updates[Cnt] = Update.get(); Built.Finals[Cnt] = Final.get(); } } if (HasErrors) return 0; // Save results Built.IterationVarRef = IV.get(); Built.LastIteration = LastIteration.get(); Built.NumIterations = NumIterations.get(); Built.CalcLastIteration = SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get(); Built.PreCond = PreCond.get(); Built.PreInits = buildPreInits(C, Captures); Built.Cond = Cond.get(); Built.Init = Init.get(); Built.Inc = Inc.get(); Built.LB = LB.get(); Built.UB = UB.get(); Built.IL = IL.get(); Built.ST = ST.get(); Built.EUB = EUB.get(); Built.NLB = NextLB.get(); Built.NUB = NextUB.get(); Built.PrevLB = PrevLB.get(); Built.PrevUB = PrevUB.get(); Built.DistInc = DistInc.get(); Built.PrevEUB = PrevEUB.get(); Built.DistCombinedFields.LB = CombLB.get(); Built.DistCombinedFields.UB = CombUB.get(); Built.DistCombinedFields.EUB = CombEUB.get(); Built.DistCombinedFields.Init = CombInit.get(); Built.DistCombinedFields.Cond = CombCond.get(); Built.DistCombinedFields.NLB = CombNextLB.get(); Built.DistCombinedFields.NUB = CombNextUB.get(); Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get(); // Fill data for doacross depend clauses. for (auto Pair : DSA.getDoacrossDependClauses()) { if (Pair.first->getDependencyKind() == OMPC_DEPEND_source) Pair.first->setCounterValue(CounterVal); else { if (NestedLoopCount != Pair.second.size() || NestedLoopCount != LoopMultipliers.size() + 1) { // Erroneous case - clause has some problems. Pair.first->setCounterValue(CounterVal); continue; } assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink); auto I = Pair.second.rbegin(); auto IS = IterSpaces.rbegin(); auto ILM = LoopMultipliers.rbegin(); Expr *UpCounterVal = CounterVal; Expr *Multiplier = nullptr; for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) { if (I->first) { assert(IS->CounterStep); Expr *NormalizedOffset = SemaRef .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div, I->first, IS->CounterStep) .get(); if (Multiplier) { NormalizedOffset = SemaRef .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul, NormalizedOffset, Multiplier) .get(); } assert(I->second == OO_Plus || I->second == OO_Minus); BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub; UpCounterVal = SemaRef .BuildBinOp(CurScope, I->first->getExprLoc(), BOK, UpCounterVal, NormalizedOffset) .get(); } Multiplier = *ILM; ++I; ++IS; ++ILM; } Pair.first->setCounterValue(UpCounterVal); } } return NestedLoopCount; } static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) { auto CollapseClauses = OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses); if (CollapseClauses.begin() != CollapseClauses.end()) return (*CollapseClauses.begin())->getNumForLoops(); return nullptr; } static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) { auto OrderedClauses = OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses); if (OrderedClauses.begin() != OrderedClauses.end()) return (*OrderedClauses.begin())->getNumForLoops(); return nullptr; } static bool checkSimdlenSafelenSpecified(Sema &S, const ArrayRef<OMPClause *> Clauses) { OMPSafelenClause *Safelen = nullptr; OMPSimdlenClause *Simdlen = nullptr; for (auto *Clause : Clauses) { if (Clause->getClauseKind() == OMPC_safelen) Safelen = cast<OMPSafelenClause>(Clause); else if (Clause->getClauseKind() == OMPC_simdlen) Simdlen = cast<OMPSimdlenClause>(Clause); if (Safelen && Simdlen) break; } if (Simdlen && Safelen) { llvm::APSInt SimdlenRes, SafelenRes; auto SimdlenLength = Simdlen->getSimdlen(); auto SafelenLength = Safelen->getSafelen(); if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() || SimdlenLength->isInstantiationDependent() || SimdlenLength->containsUnexpandedParameterPack()) return false; if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() || SafelenLength->isInstantiationDependent() || SafelenLength->containsUnexpandedParameterPack()) return false; SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context); SafelenLength->EvaluateAsInt(SafelenRes, S.Context); // OpenMP 4.5 [2.8.1, simd Construct, Restrictions] // If both simdlen and safelen clauses are specified, the value of the // simdlen parameter must be less than or equal to the value of the safelen // parameter. if (SimdlenRes > SafelenRes) { S.Diag(SimdlenLength->getExprLoc(), diag::err_omp_wrong_simdlen_safelen_values) << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange(); return true; } } return false; } StmtResult Sema::ActOnOpenMPSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { if (!AStmt) return StmtError(); assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); OMPLoopDirective::HelperExprs B; // In presence of clause 'collapse' or 'ordered' with number of loops, it will // define the nested loops number. unsigned NestedLoopCount = CheckOpenMPLoop( OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); if (NestedLoopCount == 0) return StmtError(); assert((CurContext->isDependentContext() || B.builtAll()) && "omp simd loop exprs were not built"); if (!CurContext->isDependentContext()) { // Finalize the clauses that need pre-built expressions for CodeGen. for (auto C : Clauses) { if (auto *LC = dyn_cast<OMPLinearClause>(C)) if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), B.NumIterations, *this, CurScope, DSAStack)) return StmtError(); } } if (checkSimdlenSafelenSpecified(*this, Clauses)) return StmtError(); getCurFunction()->setHasBranchProtectedScope(); return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); } StmtResult Sema::ActOnOpenMPForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { if (!AStmt) return StmtError(); assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); OMPLoopDirective::HelperExprs B; // In presence of clause 'collapse' or 'ordered' with number of loops, it will // define the nested loops number. unsigned NestedLoopCount = CheckOpenMPLoop( OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); if (NestedLoopCount == 0) return StmtError(); assert((CurContext->isDependentContext() || B.builtAll()) && "omp for loop exprs were not built"); if (!CurContext->isDependentContext()) { // Finalize the clauses that need pre-built expressions for CodeGen. for (auto C : Clauses) { if (auto *LC = dyn_cast<OMPLinearClause>(C)) if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), B.NumIterations, *this, CurScope, DSAStack)) return StmtError(); } } getCurFunction()->setHasBranchProtectedScope(); return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, DSAStack->isCancelRegion()); } StmtResult Sema::ActOnOpenMPForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { if (!AStmt) return StmtError(); assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); OMPLoopDirective::HelperExprs B; // In presence of clause 'collapse' or 'ordered' with number of loops, it will // define the nested loops number. unsigned NestedLoopCount = CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); if (NestedLoopCount == 0) return StmtError(); assert((CurContext->isDependentContext() || B.builtAll()) && "omp for simd loop exprs were not built"); if (!CurContext->isDependentContext()) { // Finalize the clauses that need pre-built expressions for CodeGen. for (auto C : Clauses) { if (auto *LC = dyn_cast<OMPLinearClause>(C)) if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), B.NumIterations, *this, CurScope, DSAStack)) return StmtError(); } } if (checkSimdlenSafelenSpecified(*this, Clauses)) return StmtError(); getCurFunction()->setHasBranchProtectedScope(); return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); } StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { if (!AStmt) return StmtError(); assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); auto BaseStmt = AStmt; while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) BaseStmt = CS->getCapturedStmt(); if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { auto S = C->children(); if (S.begin() == S.end()) return StmtError(); // All associated statements must be '#pragma omp section' except for // the first one. for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) { if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { if (SectionStmt) Diag(SectionStmt->getLocStart(), diag::err_omp_sections_substmt_not_section); return StmtError(); } cast<OMPSectionDirective>(SectionStmt) ->setHasCancel(DSAStack->isCancelRegion()); } } else { Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt); return StmtError(); } getCurFunction()->setHasBranchProtectedScope(); return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion()); } StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { if (!AStmt) return StmtError(); assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); getCurFunction()->setHasBranchProtectedScope(); DSAStack->setParentCancelRegion(DSAStack->isCancelRegion()); return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt, DSAStack->isCancelRegion()); } StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { if (!AStmt) return StmtError(); assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); getCurFunction()->setHasBranchProtectedScope(); // OpenMP [2.7.3, single Construct, Restrictions] // The copyprivate clause must not be used with the nowait clause. OMPClause *Nowait = nullptr; OMPClause *Copyprivate = nullptr; for (auto *Clause : Clauses) { if (Clause->getClauseKind() == OMPC_nowait) Nowait = Clause; else if (Clause->getClauseKind() == OMPC_copyprivate) Copyprivate = Clause; if (Copyprivate && Nowait) { Diag(Copyprivate->getLocStart(), diag::err_omp_single_copyprivate_with_nowait); Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here); return StmtError(); } } return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); } StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { if (!AStmt) return StmtError(); assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); getCurFunction()->setHasBranchProtectedScope(); return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt); } StmtResult Sema::ActOnOpenMPCriticalDirective( const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { if (!AStmt) return StmtError(); assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); bool ErrorFound = false; llvm::APSInt Hint; SourceLocation HintLoc; bool DependentHint = false; for (auto *C : Clauses) { if (C->getClauseKind() == OMPC_hint) { if (!DirName.getName()) { Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name); ErrorFound = true; } Expr *E = cast<OMPHintClause>(C)->getHint(); if (E->isTypeDependent() || E->isValueDependent() || E->isInstantiationDependent()) DependentHint = true; else { Hint = E->EvaluateKnownConstInt(Context); HintLoc = C->getLocStart(); } } } if (ErrorFound) return StmtError(); auto Pair = DSAStack->getCriticalWithHint(DirName); if (Pair.first && DirName.getName() && !DependentHint) { if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) { Diag(StartLoc, diag::err_omp_critical_with_hint); if (HintLoc.isValid()) { Diag(HintLoc, diag::note_omp_critical_hint_here) << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false); } else Diag(StartLoc, diag::note_omp_critical_no_hint) << 0; if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) { Diag(C->getLocStart(), diag::note_omp_critical_hint_here) << 1 << C->getHint()->EvaluateKnownConstInt(Context).toString( /*Radix=*/10, /*Signed=*/false); } else Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1; } } getCurFunction()->setHasBranchProtectedScope(); auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc, Clauses, AStmt); if (!Pair.first && DirName.getName() && !DependentHint) DSAStack->addCriticalWithHint(Dir, Hint); return Dir; } StmtResult Sema::ActOnOpenMPParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { if (!AStmt) return StmtError(); CapturedStmt *CS = cast<CapturedStmt>(AStmt); // 1.2.2 OpenMP Language Terminology // Structured block - An executable statement with a single entry at the // top and a single exit at the bottom. // The point of exit cannot be a branch out of the structured block. // longjmp() and throw() must not violate the entry/exit criteria. CS->getCapturedDecl()->setNothrow(); OMPLoopDirective::HelperExprs B; // In presence of clause 'collapse' or 'ordered' with number of loops, it will // define the nested loops number. unsigned NestedLoopCount = CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); if (NestedLoopCount == 0) return StmtError(); assert((CurContext->isDependentContext() || B.builtAll()) && "omp parallel for loop exprs were not built"); if (!CurContext->isDependentContext()) { // Finalize the clauses that need pre-built expressions for CodeGen. for (auto C : Clauses) { if (auto *LC = dyn_cast<OMPLinearClause>(C)) if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), B.NumIterations, *this, CurScope, DSAStack)) return StmtError(); } } getCurFunction()->setHasBranchProtectedScope(); return OMPParallelForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, DSAStack->isCancelRegion()); } StmtResult Sema::ActOnOpenMPParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { if (!AStmt) return StmtError(); CapturedStmt *CS = cast<CapturedStmt>(AStmt); // 1.2.2 OpenMP Language Terminology // Structured block - An executable statement with a single entry at the // top and a single exit at the bottom. // The point of exit cannot be a branch out of the structured block. // longjmp() and throw() must not violate the entry/exit criteria. CS->getCapturedDecl()->setNothrow(); OMPLoopDirective::HelperExprs B; // In presence of clause 'collapse' or 'ordered' with number of loops, it will // define the nested loops number. unsigned NestedLoopCount = CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); if (NestedLoopCount == 0) return StmtError(); if (!CurContext->isDependentContext()) { // Finalize the clauses that need pre-built expressions for CodeGen. for (auto C : Clauses) { if (auto *LC = dyn_cast<OMPLinearClause>(C)) if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), B.NumIterations, *this, CurScope, DSAStack)) return StmtError(); } } if (checkSimdlenSafelenSpecified(*this, Clauses)) return StmtError(); getCurFunction()->setHasBranchProtectedScope(); return OMPParallelForSimdDirective::Create( Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); } StmtResult Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { if (!AStmt) return StmtError(); assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); auto BaseStmt = AStmt; while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) BaseStmt = CS->getCapturedStmt(); if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { auto S = C->children(); if (S.begin() == S.end()) return StmtError(); // All associated statements must be '#pragma omp section' except for // the first one. for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) { if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { if (SectionStmt) Diag(SectionStmt->getLocStart(), diag::err_omp_parallel_sections_substmt_not_section); return StmtError(); } cast<OMPSectionDirective>(SectionStmt) ->setHasCancel(DSAStack->isCancelRegion()); } } else { Diag(AStmt->getLocStart(), diag::err_omp_parallel_sections_not_compound_stmt); return StmtError(); } getCurFunction()->setHasBranchProtectedScope(); return OMPParallelSectionsDirective::Create( Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion()); } StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { if (!AStmt) return StmtError(); auto *CS = cast<CapturedStmt>(AStmt); // 1.2.2 OpenMP Language Terminology // Structured block - An executable statement with a single entry at the // top and a single exit at the bottom. // The point of exit cannot be a branch out of the structured block. // longjmp() and throw() must not violate the entry/exit criteria. CS->getCapturedDecl()->setNothrow(); getCurFunction()->setHasBranchProtectedScope(); return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion()); } StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc, SourceLocation EndLoc) { return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc); } StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc, SourceLocation EndLoc) { return OMPBarrierDirective::Create(Context, StartLoc, EndLoc); } StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc, SourceLocation EndLoc) { return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc); } StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { if (!AStmt) return StmtError(); assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); getCurFunction()->setHasBranchProtectedScope(); return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->getTaskgroupReductionRef()); } StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc) { assert(Clauses.size() <= 1 && "Extra clauses in flush directive"); return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses); } StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { OMPClause *DependFound = nullptr; OMPClause *DependSourceClause = nullptr; OMPClause *DependSinkClause = nullptr; bool ErrorFound = false; OMPThreadsClause *TC = nullptr; OMPSIMDClause *SC = nullptr; for (auto *C : Clauses) { if (auto *DC = dyn_cast<OMPDependClause>(C)) { DependFound = C; if (DC->getDependencyKind() == OMPC_DEPEND_source) { if (DependSourceClause) { Diag(C->getLocStart(), diag::err_omp_more_one_clause) << getOpenMPDirectiveName(OMPD_ordered) << getOpenMPClauseName(OMPC_depend) << 2; ErrorFound = true; } else DependSourceClause = C; if (DependSinkClause) { Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed) << 0; ErrorFound = true; } } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) { if (DependSourceClause) { Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed) << 1; ErrorFound = true; } DependSinkClause = C; } } else if (C->getClauseKind() == OMPC_threads) TC = cast<OMPThreadsClause>(C); else if (C->getClauseKind() == OMPC_simd) SC = cast<OMPSIMDClause>(C); } if (!ErrorFound && !SC && isOpenMPSimdDirective(DSAStack->getParentDirective())) { // OpenMP [2.8.1,simd Construct, Restrictions] // An ordered construct with the simd clause is the only OpenMP construct // that can appear in the simd region. Diag(StartLoc, diag::err_omp_prohibited_region_simd); ErrorFound = true; } else if (DependFound && (TC || SC)) { Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd) << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind()); ErrorFound = true; } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) { Diag(DependFound->getLocStart(), diag::err_omp_ordered_directive_without_param); ErrorFound = true; } else if (TC || Clauses.empty()) { if (auto *Param = DSAStack->getParentOrderedRegionParam()) { SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc; Diag(ErrLoc, diag::err_omp_ordered_directive_with_param) << (TC != nullptr); Diag(Param->getLocStart(), diag::note_omp_ordered_param); ErrorFound = true; } } if ((!AStmt && !DependFound) || ErrorFound) return StmtError(); if (AStmt) { assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); getCurFunction()->setHasBranchProtectedScope(); } return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); } namespace { /// \brief Helper class for checking expression in 'omp atomic [update]' /// construct. class OpenMPAtomicUpdateChecker { /// \brief Error results for atomic update expressions. enum ExprAnalysisErrorCode { /// \brief A statement is not an expression statement. NotAnExpression, /// \brief Expression is not builtin binary or unary operation. NotABinaryOrUnaryExpression, /// \brief Unary operation is not post-/pre- increment/decrement operation. NotAnUnaryIncDecExpression, /// \brief An expression is not of scalar type. NotAScalarType, /// \brief A binary operation is not an assignment operation. NotAnAssignmentOp, /// \brief RHS part of the binary operation is not a binary expression. NotABinaryExpression, /// \brief RHS part is not additive/multiplicative/shift/biwise binary /// expression. NotABinaryOperator, /// \brief RHS binary operation does not have reference to the updated LHS /// part. NotAnUpdateExpression, /// \brief No errors is found. NoError }; /// \brief Reference to Sema. Sema &SemaRef; /// \brief A location for note diagnostics (when error is found). SourceLocation NoteLoc; /// \brief 'x' lvalue part of the source atomic expression. Expr *X; /// \brief 'expr' rvalue part of the source atomic expression. Expr *E; /// \brief Helper expression of the form /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. Expr *UpdateExpr; /// \brief Is 'x' a LHS in a RHS part of full update expression. It is /// important for non-associative operations. bool IsXLHSInRHSPart; BinaryOperatorKind Op; SourceLocation OpLoc; /// \brief true if the source expression is a postfix unary operation, false /// if it is a prefix unary operation. bool IsPostfixUpdate; public: OpenMPAtomicUpdateChecker(Sema &SemaRef) : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr), IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {} /// \brief Check specified statement that it is suitable for 'atomic update' /// constructs and extract 'x', 'expr' and Operation from the original /// expression. If DiagId and NoteId == 0, then only check is performed /// without error notification. /// \param DiagId Diagnostic which should be emitted if error is found. /// \param NoteId Diagnostic note for the main error message. /// \return true if statement is not an update expression, false otherwise. bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0); /// \brief Return the 'x' lvalue part of the source atomic expression. Expr *getX() const { return X; } /// \brief Return the 'expr' rvalue part of the source atomic expression. Expr *getExpr() const { return E; } /// \brief Return the update expression used in calculation of the updated /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. Expr *getUpdateExpr() const { return UpdateExpr; } /// \brief Return true if 'x' is LHS in RHS part of full update expression, /// false otherwise. bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; } /// \brief true if the source expression is a postfix unary operation, false /// if it is a prefix unary operation. bool isPostfixUpdate() const { return IsPostfixUpdate; } private: bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0, unsigned NoteId = 0); }; } // namespace bool OpenMPAtomicUpdateChecker::checkBinaryOperation( BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) { ExprAnalysisErrorCode ErrorFound = NoError; SourceLocation ErrorLoc, NoteLoc; SourceRange ErrorRange, NoteRange; // Allowed constructs are: // x = x binop expr; // x = expr binop x; if (AtomicBinOp->getOpcode() == BO_Assign) { X = AtomicBinOp->getLHS(); if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>( AtomicBinOp->getRHS()->IgnoreParenImpCasts())) { if (AtomicInnerBinOp->isMultiplicativeOp() || AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() || AtomicInnerBinOp->isBitwiseOp()) { Op = AtomicInnerBinOp->getOpcode(); OpLoc = AtomicInnerBinOp->getOperatorLoc(); auto *LHS = AtomicInnerBinOp->getLHS(); auto *RHS = AtomicInnerBinOp->getRHS(); llvm::FoldingSetNodeID XId, LHSId, RHSId; X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(), /*Canonical=*/true); LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(), /*Canonical=*/true); RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(), /*Canonical=*/true); if (XId == LHSId) { E = RHS; IsXLHSInRHSPart = true; } else if (XId == RHSId) { E = LHS; IsXLHSInRHSPart = false; } else { ErrorLoc = AtomicInnerBinOp->getExprLoc(); ErrorRange = AtomicInnerBinOp->getSourceRange(); NoteLoc = X->getExprLoc(); NoteRange = X->getSourceRange(); ErrorFound = NotAnUpdateExpression; } } else { ErrorLoc = AtomicInnerBinOp->getExprLoc(); ErrorRange = AtomicInnerBinOp->getSourceRange(); NoteLoc = AtomicInnerBinOp->getOperatorLoc(); NoteRange = SourceRange(NoteLoc, NoteLoc); ErrorFound = NotABinaryOperator; } } else { NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc(); NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange(); ErrorFound = NotABinaryExpression; } } else { ErrorLoc = AtomicBinOp->getExprLoc(); ErrorRange = AtomicBinOp->getSourceRange(); NoteLoc = AtomicBinOp->getOperatorLoc(); NoteRange = SourceRange(NoteLoc, NoteLoc); ErrorFound = NotAnAssignmentOp; } if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) { SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange; SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange; return true; } else if (SemaRef.CurContext->isDependentContext()) E = X = UpdateExpr = nullptr; return ErrorFound != NoError; } bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId, unsigned NoteId) { ExprAnalysisErrorCode ErrorFound = NoError; SourceLocation ErrorLoc, NoteLoc; SourceRange ErrorRange, NoteRange; // Allowed constructs are: // x++; // x--; // ++x; // --x; // x binop= expr; // x = x binop expr; // x = expr binop x; if (auto *AtomicBody = dyn_cast<Expr>(S)) { AtomicBody = AtomicBody->IgnoreParenImpCasts(); if (AtomicBody->getType()->isScalarType() || AtomicBody->isInstantiationDependent()) { if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>( AtomicBody->IgnoreParenImpCasts())) { // Check for Compound Assignment Operation Op = BinaryOperator::getOpForCompoundAssignment( AtomicCompAssignOp->getOpcode()); OpLoc = AtomicCompAssignOp->getOperatorLoc(); E = AtomicCompAssignOp->getRHS(); X = AtomicCompAssignOp->getLHS()->IgnoreParens(); IsXLHSInRHSPart = true; } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>( AtomicBody->IgnoreParenImpCasts())) { // Check for Binary Operation if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId)) return true; } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>( AtomicBody->IgnoreParenImpCasts())) { // Check for Unary Operation if (AtomicUnaryOp->isIncrementDecrementOp()) { IsPostfixUpdate = AtomicUnaryOp->isPostfix(); Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub; OpLoc = AtomicUnaryOp->getOperatorLoc(); X = AtomicUnaryOp->getSubExpr()->IgnoreParens(); E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get(); IsXLHSInRHSPart = true; } else { ErrorFound = NotAnUnaryIncDecExpression; ErrorLoc = AtomicUnaryOp->getExprLoc(); ErrorRange = AtomicUnaryOp->getSourceRange(); NoteLoc = AtomicUnaryOp->getOperatorLoc(); NoteRange = SourceRange(NoteLoc, NoteLoc); } } else if (!AtomicBody->isInstantiationDependent()) { ErrorFound = NotABinaryOrUnaryExpression; NoteLoc = ErrorLoc = AtomicBody->getExprLoc(); NoteRange = ErrorRange = AtomicBody->getSourceRange(); } } else { ErrorFound = NotAScalarType; NoteLoc = ErrorLoc = AtomicBody->getLocStart(); NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); } } else { ErrorFound = NotAnExpression; NoteLoc = ErrorLoc = S->getLocStart(); NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); } if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) { SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange; SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange; return true; } else if (SemaRef.CurContext->isDependentContext()) E = X = UpdateExpr = nullptr; if (ErrorFound == NoError && E && X) { // Build an update expression of form 'OpaqueValueExpr(x) binop // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression. auto *OVEX = new (SemaRef.getASTContext()) OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue); auto *OVEExpr = new (SemaRef.getASTContext()) OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue); auto Update = SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr, IsXLHSInRHSPart ? OVEExpr : OVEX); if (Update.isInvalid()) return true; Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(), Sema::AA_Casting); if (Update.isInvalid()) return true; UpdateExpr = Update.get(); } return ErrorFound != NoError; } StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { if (!AStmt) return StmtError(); auto *CS = cast<CapturedStmt>(AStmt); // 1.2.2 OpenMP Language Terminology // Structured block - An executable statement with a single entry at the // top and a single exit at the bottom. // The point of exit cannot be a branch out of the structured block. // longjmp() and throw() must not violate the entry/exit criteria. OpenMPClauseKind AtomicKind = OMPC_unknown; SourceLocation AtomicKindLoc; for (auto *C : Clauses) { if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write || C->getClauseKind() == OMPC_update || C->getClauseKind() == OMPC_capture) { if (AtomicKind != OMPC_unknown) { Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses) << SourceRange(C->getLocStart(), C->getLocEnd()); Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause) << getOpenMPClauseName(AtomicKind); } else { AtomicKind = C->getClauseKind(); AtomicKindLoc = C->getLocStart(); } } } auto Body = CS->getCapturedStmt(); if (auto *EWC = dyn_cast<ExprWithCleanups>(Body)) Body = EWC->getSubExpr(); Expr *X = nullptr; Expr *V = nullptr; Expr *E = nullptr; Expr *UE = nullptr; bool IsXLHSInRHSPart = false; bool IsPostfixUpdate = false; // OpenMP [2.12.6, atomic Construct] // In the next expressions: // * x and v (as applicable) are both l-value expressions with scalar type. // * During the execution of an atomic region, multiple syntactic // occurrences of x must designate the same storage location. // * Neither of v and expr (as applicable) may access the storage location // designated by x. // * Neither of x and expr (as applicable) may access the storage location // designated by v. // * expr is an expression with scalar type. // * binop is one of +, *, -, /, &, ^, |, <<, or >>. // * binop, binop=, ++, and -- are not overloaded operators. // * The expression x binop expr must be numerically equivalent to x binop // (expr). This requirement is satisfied if the operators in expr have // precedence greater than binop, or by using parentheses around expr or // subexpressions of expr. // * The expression expr binop x must be numerically equivalent to (expr) // binop x. This requirement is satisfied if the operators in expr have // precedence equal to or greater than binop, or by using parentheses around // expr or subexpressions of expr. // * For forms that allow multiple occurrences of x, the number of times // that x is evaluated is unspecified. if (AtomicKind == OMPC_read) { enum { NotAnExpression, NotAnAssignmentOp, NotAScalarType, NotAnLValue, NoError } ErrorFound = NoError; SourceLocation ErrorLoc, NoteLoc; SourceRange ErrorRange, NoteRange; // If clause is read: // v = x; if (auto *AtomicBody = dyn_cast<Expr>(Body)) { auto *AtomicBinOp = dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { X = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); V = AtomicBinOp->getLHS()->IgnoreParenImpCasts(); if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && (V->isInstantiationDependent() || V->getType()->isScalarType())) { if (!X->isLValue() || !V->isLValue()) { auto NotLValueExpr = X->isLValue() ? V : X; ErrorFound = NotAnLValue; ErrorLoc = AtomicBinOp->getExprLoc(); ErrorRange = AtomicBinOp->getSourceRange(); NoteLoc = NotLValueExpr->getExprLoc(); NoteRange = NotLValueExpr->getSourceRange(); } } else if (!X->isInstantiationDependent() || !V->isInstantiationDependent()) { auto NotScalarExpr = (X->isInstantiationDependent() || X->getType()->isScalarType()) ? V : X; ErrorFound = NotAScalarType; ErrorLoc = AtomicBinOp->getExprLoc(); ErrorRange = AtomicBinOp->getSourceRange(); NoteLoc = NotScalarExpr->getExprLoc(); NoteRange = NotScalarExpr->getSourceRange(); } } else if (!AtomicBody->isInstantiationDependent()) { ErrorFound = NotAnAssignmentOp; ErrorLoc = AtomicBody->getExprLoc(); ErrorRange = AtomicBody->getSourceRange(); NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() : AtomicBody->getExprLoc(); NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() : AtomicBody->getSourceRange(); } } else { ErrorFound = NotAnExpression; NoteLoc = ErrorLoc = Body->getLocStart(); NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); } if (ErrorFound != NoError) { Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement) << ErrorRange; Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound << NoteRange; return StmtError(); } else if (CurContext->isDependentContext()) V = X = nullptr; } else if (AtomicKind == OMPC_write) { enum { NotAnExpression, NotAnAssignmentOp, NotAScalarType, NotAnLValue, NoError } ErrorFound = NoError; SourceLocation ErrorLoc, NoteLoc; SourceRange ErrorRange, NoteRange; // If clause is write: // x = expr; if (auto *AtomicBody = dyn_cast<Expr>(Body)) { auto *AtomicBinOp = dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { X = AtomicBinOp->getLHS(); E = AtomicBinOp->getRHS(); if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && (E->isInstantiationDependent() || E->getType()->isScalarType())) { if (!X->isLValue()) { ErrorFound = NotAnLValue; ErrorLoc = AtomicBinOp->getExprLoc(); ErrorRange = AtomicBinOp->getSourceRange(); NoteLoc = X->getExprLoc(); NoteRange = X->getSourceRange(); } } else if (!X->isInstantiationDependent() || !E->isInstantiationDependent()) { auto NotScalarExpr = (X->isInstantiationDependent() || X->getType()->isScalarType()) ? E : X; ErrorFound = NotAScalarType; ErrorLoc = AtomicBinOp->getExprLoc(); ErrorRange = AtomicBinOp->getSourceRange(); NoteLoc = NotScalarExpr->getExprLoc(); NoteRange = NotScalarExpr->getSourceRange(); } } else if (!AtomicBody->isInstantiationDependent()) { ErrorFound = NotAnAssignmentOp; ErrorLoc = AtomicBody->getExprLoc(); ErrorRange = AtomicBody->getSourceRange(); NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() : AtomicBody->getExprLoc(); NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() : AtomicBody->getSourceRange(); } } else { ErrorFound = NotAnExpression; NoteLoc = ErrorLoc = Body->getLocStart(); NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); } if (ErrorFound != NoError) { Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement) << ErrorRange; Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound << NoteRange; return StmtError(); } else if (CurContext->isDependentContext()) E = X = nullptr; } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) { // If clause is update: // x++; // x--; // ++x; // --x; // x binop= expr; // x = x binop expr; // x = expr binop x; OpenMPAtomicUpdateChecker Checker(*this); if (Checker.checkStatement( Body, (AtomicKind == OMPC_update) ? diag::err_omp_atomic_update_not_expression_statement : diag::err_omp_atomic_not_expression_statement, diag::note_omp_atomic_update)) return StmtError(); if (!CurContext->isDependentContext()) { E = Checker.getExpr(); X = Checker.getX(); UE = Checker.getUpdateExpr(); IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); } } else if (AtomicKind == OMPC_capture) { enum { NotAnAssignmentOp, NotACompoundStatement, NotTwoSubstatements, NotASpecificExpression, NoError } ErrorFound = NoError; SourceLocation ErrorLoc, NoteLoc; SourceRange ErrorRange, NoteRange; if (auto *AtomicBody = dyn_cast<Expr>(Body)) { // If clause is a capture: // v = x++; // v = x--; // v = ++x; // v = --x; // v = x binop= expr; // v = x = x binop expr; // v = x = expr binop x; auto *AtomicBinOp = dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { V = AtomicBinOp->getLHS(); Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); OpenMPAtomicUpdateChecker Checker(*this); if (Checker.checkStatement( Body, diag::err_omp_atomic_capture_not_expression_statement, diag::note_omp_atomic_update)) return StmtError(); E = Checker.getExpr(); X = Checker.getX(); UE = Checker.getUpdateExpr(); IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); IsPostfixUpdate = Checker.isPostfixUpdate(); } else if (!AtomicBody->isInstantiationDependent()) { ErrorLoc = AtomicBody->getExprLoc(); ErrorRange = AtomicBody->getSourceRange(); NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() : AtomicBody->getExprLoc(); NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() : AtomicBody->getSourceRange(); ErrorFound = NotAnAssignmentOp; } if (ErrorFound != NoError) { Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement) << ErrorRange; Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange; return StmtError(); } else if (CurContext->isDependentContext()) { UE = V = E = X = nullptr; } } else { // If clause is a capture: // { v = x; x = expr; } // { v = x; x++; } // { v = x; x--; } // { v = x; ++x; } // { v = x; --x; } // { v = x; x binop= expr; } // { v = x; x = x binop expr; } // { v = x; x = expr binop x; } // { x++; v = x; } // { x--; v = x; } // { ++x; v = x; } // { --x; v = x; } // { x binop= expr; v = x; } // { x = x binop expr; v = x; } // { x = expr binop x; v = x; } if (auto *CS = dyn_cast<CompoundStmt>(Body)) { // Check that this is { expr1; expr2; } if (CS->size() == 2) { auto *First = CS->body_front(); auto *Second = CS->body_back(); if (auto *EWC = dyn_cast<ExprWithCleanups>(First)) First = EWC->getSubExpr()->IgnoreParenImpCasts(); if (auto *EWC = dyn_cast<ExprWithCleanups>(Second)) Second = EWC->getSubExpr()->IgnoreParenImpCasts(); // Need to find what subexpression is 'v' and what is 'x'. OpenMPAtomicUpdateChecker Checker(*this); bool IsUpdateExprFound = !Checker.checkStatement(Second); BinaryOperator *BinOp = nullptr; if (IsUpdateExprFound) { BinOp = dyn_cast<BinaryOperator>(First); IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign; } if (IsUpdateExprFound && !CurContext->isDependentContext()) { // { v = x; x++; } // { v = x; x--; } // { v = x; ++x; } // { v = x; --x; } // { v = x; x binop= expr; } // { v = x; x = x binop expr; } // { v = x; x = expr binop x; } // Check that the first expression has form v = x. auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts(); llvm::FoldingSetNodeID XId, PossibleXId; Checker.getX()->Profile(XId, Context, /*Canonical=*/true); PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true); IsUpdateExprFound = XId == PossibleXId; if (IsUpdateExprFound) { V = BinOp->getLHS(); X = Checker.getX(); E = Checker.getExpr(); UE = Checker.getUpdateExpr(); IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); IsPostfixUpdate = true; } } if (!IsUpdateExprFound) { IsUpdateExprFound = !Checker.checkStatement(First); BinOp = nullptr; if (IsUpdateExprFound) { BinOp = dyn_cast<BinaryOperator>(Second); IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign; } if (IsUpdateExprFound && !CurContext->isDependentContext()) { // { x++; v = x; } // { x--; v = x; } // { ++x; v = x; } // { --x; v = x; } // { x binop= expr; v = x; } // { x = x binop expr; v = x; } // { x = expr binop x; v = x; } // Check that the second expression has form v = x. auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts(); llvm::FoldingSetNodeID XId, PossibleXId; Checker.getX()->Profile(XId, Context, /*Canonical=*/true); PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true); IsUpdateExprFound = XId == PossibleXId; if (IsUpdateExprFound) { V = BinOp->getLHS(); X = Checker.getX(); E = Checker.getExpr(); UE = Checker.getUpdateExpr(); IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); IsPostfixUpdate = false; } } } if (!IsUpdateExprFound) { // { v = x; x = expr; } auto *FirstExpr = dyn_cast<Expr>(First); auto *SecondExpr = dyn_cast<Expr>(Second); if (!FirstExpr || !SecondExpr || !(FirstExpr->isInstantiationDependent() || SecondExpr->isInstantiationDependent())) { auto *FirstBinOp = dyn_cast<BinaryOperator>(First); if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) { ErrorFound = NotAnAssignmentOp; NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc() : First->getLocStart(); NoteRange = ErrorRange = FirstBinOp ? FirstBinOp->getSourceRange() : SourceRange(ErrorLoc, ErrorLoc); } else { auto *SecondBinOp = dyn_cast<BinaryOperator>(Second); if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) { ErrorFound = NotAnAssignmentOp; NoteLoc = ErrorLoc = SecondBinOp ? SecondBinOp->getOperatorLoc() : Second->getLocStart(); NoteRange = ErrorRange = SecondBinOp ? SecondBinOp->getSourceRange() : SourceRange(ErrorLoc, ErrorLoc); } else { auto *PossibleXRHSInFirst = FirstBinOp->getRHS()->IgnoreParenImpCasts(); auto *PossibleXLHSInSecond = SecondBinOp->getLHS()->IgnoreParenImpCasts(); llvm::FoldingSetNodeID X1Id, X2Id; PossibleXRHSInFirst->Profile(X1Id, Context, /*Canonical=*/true); PossibleXLHSInSecond->Profile(X2Id, Context, /*Canonical=*/true); IsUpdateExprFound = X1Id == X2Id; if (IsUpdateExprFound) { V = FirstBinOp->getLHS(); X = SecondBinOp->getLHS(); E = SecondBinOp->getRHS(); UE = nullptr; IsXLHSInRHSPart = false; IsPostfixUpdate = true; } else { ErrorFound = NotASpecificExpression; ErrorLoc = FirstBinOp->getExprLoc(); ErrorRange = FirstBinOp->getSourceRange(); NoteLoc = SecondBinOp->getLHS()->getExprLoc(); NoteRange = SecondBinOp->getRHS()->getSourceRange(); } } } } } } else { NoteLoc = ErrorLoc = Body->getLocStart(); NoteRange = ErrorRange = SourceRange(Body->getLocStart(), Body->getLocStart()); ErrorFound = NotTwoSubstatements; } } else { NoteLoc = ErrorLoc = Body->getLocStart(); NoteRange = ErrorRange = SourceRange(Body->getLocStart(), Body->getLocStart()); ErrorFound = NotACompoundStatement; } if (ErrorFound != NoError) { Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement) << ErrorRange; Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange; return StmtError(); } else if (CurContext->isDependentContext()) { UE = V = E = X = nullptr; } } } getCurFunction()->setHasBranchProtectedScope(); return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, X, V, E, UE, IsXLHSInRHSPart, IsPostfixUpdate); } StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { if (!AStmt) return StmtError(); CapturedStmt *CS = cast<CapturedStmt>(AStmt); // 1.2.2 OpenMP Language Terminology // Structured block - An executable statement with a single entry at the // top and a single exit at the bottom. // The point of exit cannot be a branch out of the structured block. // longjmp() and throw() must not violate the entry/exit criteria. CS->getCapturedDecl()->setNothrow(); // OpenMP [2.16, Nesting of Regions] // If specified, a teams construct must be contained within a target // construct. That target construct must contain no statements or directives // outside of the teams construct. if (DSAStack->hasInnerTeamsRegion()) { auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true); bool OMPTeamsFound = true; if (auto *CS = dyn_cast<CompoundStmt>(S)) { auto I = CS->body_begin(); while (I != CS->body_end()) { auto *OED = dyn_cast<OMPExecutableDirective>(*I); if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) { OMPTeamsFound = false; break; } ++I; } assert(I != CS->body_end() && "Not found statement"); S = *I; } else { auto *OED = dyn_cast<OMPExecutableDirective>(S); OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind()); } if (!OMPTeamsFound) { Diag(StartLoc, diag::err_omp_target_contains_not_only_teams); Diag(DSAStack->getInnerTeamsRegionLoc(), diag::note_omp_nested_teams_construct_here); Diag(S->getLocStart(), diag::note_omp_nested_statement_here) << isa<OMPExecutableDirective>(S); return StmtError(); } } getCurFunction()->setHasBranchProtectedScope(); return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); } StmtResult Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { if (!AStmt) return StmtError(); CapturedStmt *CS = cast<CapturedStmt>(AStmt); // 1.2.2 OpenMP Language Terminology // Structured block - An executable statement with a single entry at the // top and a single exit at the bottom. // The point of exit cannot be a branch out of the structured block. // longjmp() and throw() must not violate the entry/exit criteria. CS->getCapturedDecl()->setNothrow(); getCurFunction()->setHasBranchProtectedScope(); return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); } StmtResult Sema::ActOnOpenMPTargetParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { if (!AStmt) return StmtError(); CapturedStmt *CS = cast<CapturedStmt>(AStmt); // 1.2.2 OpenMP Language Terminology // Structured block - An executable statement with a single entry at the // top and a single exit at the bottom. // The point of exit cannot be a branch out of the structured block. // longjmp() and throw() must not violate the entry/exit criteria. CS->getCapturedDecl()->setNothrow(); OMPLoopDirective::HelperExprs B; // In presence of clause 'collapse' or 'ordered' with number of loops, it will // define the nested loops number. unsigned NestedLoopCount = CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); if (NestedLoopCount == 0) return StmtError(); assert((CurContext->isDependentContext() || B.builtAll()) && "omp target parallel for loop exprs were not built"); if (!CurContext->isDependentContext()) { // Finalize the clauses that need pre-built expressions for CodeGen. for (auto C : Clauses) { if (auto *LC = dyn_cast<OMPLinearClause>(C)) if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), B.NumIterations, *this, CurScope, DSAStack)) return StmtError(); } } getCurFunction()->setHasBranchProtectedScope(); return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, DSAStack->isCancelRegion()); } /// Check for existence of a map clause in the list of clauses. static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K) { return llvm::any_of( Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; }); } template <typename... Params> static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K, const Params... ClauseTypes) { return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...); } StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { if (!AStmt) return StmtError(); assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); // OpenMP [2.10.1, Restrictions, p. 97] // At least one map clause must appear on the directive. if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) { Diag(StartLoc, diag::err_omp_no_clause_for_directive) << "'map' or 'use_device_ptr'" << getOpenMPDirectiveName(OMPD_target_data); return StmtError(); } getCurFunction()->setHasBranchProtectedScope(); return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); } StmtResult Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc) { // OpenMP [2.10.2, Restrictions, p. 99] // At least one map clause must appear on the directive. if (!hasClauses(Clauses, OMPC_map)) { Diag(StartLoc, diag::err_omp_no_clause_for_directive) << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data); return StmtError(); } return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses); } StmtResult Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc) { // OpenMP [2.10.3, Restrictions, p. 102] // At least one map clause must appear on the directive. if (!hasClauses(Clauses, OMPC_map)) { Diag(StartLoc, diag::err_omp_no_clause_for_directive) << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data); return StmtError(); } return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses); } StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc) { if (!hasClauses(Clauses, OMPC_to, OMPC_from)) { Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required); return StmtError(); } return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses); } StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { if (!AStmt) return StmtError(); CapturedStmt *CS = cast<CapturedStmt>(AStmt); // 1.2.2 OpenMP Language Terminology // Structured block - An executable statement with a single entry at the // top and a single exit at the bottom. // The point of exit cannot be a branch out of the structured block. // longjmp() and throw() must not violate the entry/exit criteria. CS->getCapturedDecl()->setNothrow(); getCurFunction()->setHasBranchProtectedScope(); return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); } StmtResult Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc, SourceLocation EndLoc, OpenMPDirectiveKind CancelRegion) { if (DSAStack->isParentNowaitRegion()) { Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0; return StmtError(); } if (DSAStack->isParentOrderedRegion()) { Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0; return StmtError(); } return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc, CancelRegion); } StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc, OpenMPDirectiveKind CancelRegion) { if (DSAStack->isParentNowaitRegion()) { Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1; return StmtError(); } if (DSAStack->isParentOrderedRegion()) { Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1; return StmtError(); } DSAStack->setParentCancelRegion(/*Cancel=*/true); return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses, CancelRegion); } static bool checkGrainsizeNumTasksClauses(Sema &S, ArrayRef<OMPClause *> Clauses) { OMPClause *PrevClause = nullptr; bool ErrorFound = false; for (auto *C : Clauses) { if (C->getClauseKind() == OMPC_grainsize || C->getClauseKind() == OMPC_num_tasks) { if (!PrevClause) PrevClause = C; else if (PrevClause->getClauseKind() != C->getClauseKind()) { S.Diag(C->getLocStart(), diag::err_omp_grainsize_num_tasks_mutually_exclusive) << getOpenMPClauseName(C->getClauseKind()) << getOpenMPClauseName(PrevClause->getClauseKind()); S.Diag(PrevClause->getLocStart(), diag::note_omp_previous_grainsize_num_tasks) << getOpenMPClauseName(PrevClause->getClauseKind()); ErrorFound = true; } } } return ErrorFound; } static bool checkReductionClauseWithNogroup(Sema &S, ArrayRef<OMPClause *> Clauses) { OMPClause *ReductionClause = nullptr; OMPClause *NogroupClause = nullptr; for (auto *C : Clauses) { if (C->getClauseKind() == OMPC_reduction) { ReductionClause = C; if (NogroupClause) break; continue; } if (C->getClauseKind() == OMPC_nogroup) { NogroupClause = C; if (ReductionClause) break; continue; } } if (ReductionClause && NogroupClause) { S.Diag(ReductionClause->getLocStart(), diag::err_omp_reduction_with_nogroup) << SourceRange(NogroupClause->getLocStart(), NogroupClause->getLocEnd()); return true; } return false; } StmtResult Sema::ActOnOpenMPTaskLoopDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { if (!AStmt) return StmtError(); assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); OMPLoopDirective::HelperExprs B; // In presence of clause 'collapse' or 'ordered' with number of loops, it will // define the nested loops number. unsigned NestedLoopCount = CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses), /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); if (NestedLoopCount == 0) return StmtError(); assert((CurContext->isDependentContext() || B.builtAll()) && "omp for loop exprs were not built"); // OpenMP, [2.9.2 taskloop Construct, Restrictions] // The grainsize clause and num_tasks clause are mutually exclusive and may // not appear on the same taskloop directive. if (checkGrainsizeNumTasksClauses(*this, Clauses)) return StmtError(); // OpenMP, [2.9.2 taskloop Construct, Restrictions] // If a reduction clause is present on the taskloop directive, the nogroup // clause must not be specified. if (checkReductionClauseWithNogroup(*this, Clauses)) return StmtError(); getCurFunction()->setHasBranchProtectedScope(); return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); } StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { if (!AStmt) return StmtError(); assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); OMPLoopDirective::HelperExprs B; // In presence of clause 'collapse' or 'ordered' with number of loops, it will // define the nested loops number. unsigned NestedLoopCount = CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses), /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); if (NestedLoopCount == 0) return StmtError(); assert((CurContext->isDependentContext() || B.builtAll()) && "omp for loop exprs were not built"); if (!CurContext->isDependentContext()) { // Finalize the clauses that need pre-built expressions for CodeGen. for (auto C : Clauses) { if (auto *LC = dyn_cast<OMPLinearClause>(C)) if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), B.NumIterations, *this, CurScope, DSAStack)) return StmtError(); } } // OpenMP, [2.9.2 taskloop Construct, Restrictions] // The grainsize clause and num_tasks clause are mutually exclusive and may // not appear on the same taskloop directive. if (checkGrainsizeNumTasksClauses(*this, Clauses)) return StmtError(); // OpenMP, [2.9.2 taskloop Construct, Restrictions] // If a reduction clause is present on the taskloop directive, the nogroup // clause must not be specified. if (checkReductionClauseWithNogroup(*this, Clauses)) return StmtError(); getCurFunction()->setHasBranchProtectedScope(); return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); } StmtResult Sema::ActOnOpenMPDistributeDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { if (!AStmt) return StmtError(); assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); OMPLoopDirective::HelperExprs B; // In presence of clause 'collapse' with number of loops, it will // define the nested loops number. unsigned NestedLoopCount = CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses), nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); if (NestedLoopCount == 0) return StmtError(); assert((CurContext->isDependentContext() || B.builtAll()) && "omp for loop exprs were not built"); getCurFunction()->setHasBranchProtectedScope(); return OMPDistributeDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); } StmtResult Sema::ActOnOpenMPDistributeParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { if (!AStmt) return StmtError(); CapturedStmt *CS = cast<CapturedStmt>(AStmt); // 1.2.2 OpenMP Language Terminology // Structured block - An executable statement with a single entry at the // top and a single exit at the bottom. // The point of exit cannot be a branch out of the structured block. // longjmp() and throw() must not violate the entry/exit criteria. CS->getCapturedDecl()->setNothrow(); OMPLoopDirective::HelperExprs B; // In presence of clause 'collapse' with number of loops, it will // define the nested loops number. unsigned NestedLoopCount = CheckOpenMPLoop( OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses), nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); if (NestedLoopCount == 0) return StmtError(); assert((CurContext->isDependentContext() || B.builtAll()) && "omp for loop exprs were not built"); getCurFunction()->setHasBranchProtectedScope(); return OMPDistributeParallelForDirective::Create( Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); } StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { if (!AStmt) return StmtError(); CapturedStmt *CS = cast<CapturedStmt>(AStmt); // 1.2.2 OpenMP Language Terminology // Structured block - An executable statement with a single entry at the // top and a single exit at the bottom. // The point of exit cannot be a branch out of the structured block. // longjmp() and throw() must not violate the entry/exit criteria. CS->getCapturedDecl()->setNothrow(); OMPLoopDirective::HelperExprs B; // In presence of clause 'collapse' with number of loops, it will // define the nested loops number. unsigned NestedLoopCount = CheckOpenMPLoop( OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses), nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); if (NestedLoopCount == 0) return StmtError(); assert((CurContext->isDependentContext() || B.builtAll()) && "omp for loop exprs were not built"); if (checkSimdlenSafelenSpecified(*this, Clauses)) return StmtError(); getCurFunction()->setHasBranchProtectedScope(); return OMPDistributeParallelForSimdDirective::Create( Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); } StmtResult Sema::ActOnOpenMPDistributeSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { if (!AStmt) return StmtError(); CapturedStmt *CS = cast<CapturedStmt>(AStmt); // 1.2.2 OpenMP Language Terminology // Structured block - An executable statement with a single entry at the // top and a single exit at the bottom. // The point of exit cannot be a branch out of the structured block. // longjmp() and throw() must not violate the entry/exit criteria. CS->getCapturedDecl()->setNothrow(); OMPLoopDirective::HelperExprs B; // In presence of clause 'collapse' with number of loops, it will // define the nested loops number. unsigned NestedLoopCount = CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses), nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); if (NestedLoopCount == 0) return StmtError(); assert((CurContext->isDependentContext() || B.builtAll()) && "omp for loop exprs were not built"); if (checkSimdlenSafelenSpecified(*this, Clauses)) return StmtError(); getCurFunction()->setHasBranchProtectedScope(); return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); } StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { if (!AStmt) return StmtError(); CapturedStmt *CS = cast<CapturedStmt>(AStmt); // 1.2.2 OpenMP Language Terminology // Structured block - An executable statement with a single entry at the // top and a single exit at the bottom. // The point of exit cannot be a branch out of the structured block. // longjmp() and throw() must not violate the entry/exit criteria. CS->getCapturedDecl()->setNothrow(); OMPLoopDirective::HelperExprs B; // In presence of clause 'collapse' or 'ordered' with number of loops, it will // define the nested loops number. unsigned NestedLoopCount = CheckOpenMPLoop( OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); if (NestedLoopCount == 0) return StmtError(); assert((CurContext->isDependentContext() || B.builtAll()) && "omp target parallel for simd loop exprs were not built"); if (!CurContext->isDependentContext()) { // Finalize the clauses that need pre-built expressions for CodeGen. for (auto C : Clauses) { if (auto *LC = dyn_cast<OMPLinearClause>(C)) if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), B.NumIterations, *this, CurScope, DSAStack)) return StmtError(); } } if (checkSimdlenSafelenSpecified(*this, Clauses)) return StmtError(); getCurFunction()->setHasBranchProtectedScope(); return OMPTargetParallelForSimdDirective::Create( Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); } StmtResult Sema::ActOnOpenMPTargetSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { if (!AStmt) return StmtError(); CapturedStmt *CS = cast<CapturedStmt>(AStmt); // 1.2.2 OpenMP Language Terminology // Structured block - An executable statement with a single entry at the // top and a single exit at the bottom. // The point of exit cannot be a branch out of the structured block. // longjmp() and throw() must not violate the entry/exit criteria. CS->getCapturedDecl()->setNothrow(); OMPLoopDirective::HelperExprs B; // In presence of clause 'collapse' with number of loops, it will define the // nested loops number. unsigned NestedLoopCount = CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); if (NestedLoopCount == 0) return StmtError(); assert((CurContext->isDependentContext() || B.builtAll()) && "omp target simd loop exprs were not built"); if (!CurContext->isDependentContext()) { // Finalize the clauses that need pre-built expressions for CodeGen. for (auto C : Clauses) { if (auto *LC = dyn_cast<OMPLinearClause>(C)) if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), B.NumIterations, *this, CurScope, DSAStack)) return StmtError(); } } if (checkSimdlenSafelenSpecified(*this, Clauses)) return StmtError(); getCurFunction()->setHasBranchProtectedScope(); return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); } StmtResult Sema::ActOnOpenMPTeamsDistributeDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { if (!AStmt) return StmtError(); CapturedStmt *CS = cast<CapturedStmt>(AStmt); // 1.2.2 OpenMP Language Terminology // Structured block - An executable statement with a single entry at the // top and a single exit at the bottom. // The point of exit cannot be a branch out of the structured block. // longjmp() and throw() must not violate the entry/exit criteria. CS->getCapturedDecl()->setNothrow(); OMPLoopDirective::HelperExprs B; // In presence of clause 'collapse' with number of loops, it will // define the nested loops number. unsigned NestedLoopCount = CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses), nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); if (NestedLoopCount == 0) return StmtError(); assert((CurContext->isDependentContext() || B.builtAll()) && "omp teams distribute loop exprs were not built"); getCurFunction()->setHasBranchProtectedScope(); return OMPTeamsDistributeDirective::Create( Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); } StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { if (!AStmt) return StmtError(); CapturedStmt *CS = cast<CapturedStmt>(AStmt); // 1.2.2 OpenMP Language Terminology // Structured block - An executable statement with a single entry at the // top and a single exit at the bottom. // The point of exit cannot be a branch out of the structured block. // longjmp() and throw() must not violate the entry/exit criteria. CS->getCapturedDecl()->setNothrow(); OMPLoopDirective::HelperExprs B; // In presence of clause 'collapse' with number of loops, it will // define the nested loops number. unsigned NestedLoopCount = CheckOpenMPLoop( OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses), nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); if (NestedLoopCount == 0) return StmtError(); assert((CurContext->isDependentContext() || B.builtAll()) && "omp teams distribute simd loop exprs were not built"); if (!CurContext->isDependentContext()) { // Finalize the clauses that need pre-built expressions for CodeGen. for (auto C : Clauses) { if (auto *LC = dyn_cast<OMPLinearClause>(C)) if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), B.NumIterations, *this, CurScope, DSAStack)) return StmtError(); } } if (checkSimdlenSafelenSpecified(*this, Clauses)) return StmtError(); getCurFunction()->setHasBranchProtectedScope(); return OMPTeamsDistributeSimdDirective::Create( Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); } StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { if (!AStmt) return StmtError(); CapturedStmt *CS = cast<CapturedStmt>(AStmt); // 1.2.2 OpenMP Language Terminology // Structured block - An executable statement with a single entry at the // top and a single exit at the bottom. // The point of exit cannot be a branch out of the structured block. // longjmp() and throw() must not violate the entry/exit criteria. CS->getCapturedDecl()->setNothrow(); OMPLoopDirective::HelperExprs B; // In presence of clause 'collapse' with number of loops, it will // define the nested loops number. auto NestedLoopCount = CheckOpenMPLoop( OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses), nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); if (NestedLoopCount == 0) return StmtError(); assert((CurContext->isDependentContext() || B.builtAll()) && "omp for loop exprs were not built"); if (!CurContext->isDependentContext()) { // Finalize the clauses that need pre-built expressions for CodeGen. for (auto C : Clauses) { if (auto *LC = dyn_cast<OMPLinearClause>(C)) if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), B.NumIterations, *this, CurScope, DSAStack)) return StmtError(); } } if (checkSimdlenSafelenSpecified(*this, Clauses)) return StmtError(); getCurFunction()->setHasBranchProtectedScope(); return OMPTeamsDistributeParallelForSimdDirective::Create( Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); } StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { if (!AStmt) return StmtError(); CapturedStmt *CS = cast<CapturedStmt>(AStmt); // 1.2.2 OpenMP Language Terminology // Structured block - An executable statement with a single entry at the // top and a single exit at the bottom. // The point of exit cannot be a branch out of the structured block. // longjmp() and throw() must not violate the entry/exit criteria. CS->getCapturedDecl()->setNothrow(); OMPLoopDirective::HelperExprs B; // In presence of clause 'collapse' with number of loops, it will // define the nested loops number. unsigned NestedLoopCount = CheckOpenMPLoop( OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses), nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); if (NestedLoopCount == 0) return StmtError(); assert((CurContext->isDependentContext() || B.builtAll()) && "omp for loop exprs were not built"); if (!CurContext->isDependentContext()) { // Finalize the clauses that need pre-built expressions for CodeGen. for (auto C : Clauses) { if (auto *LC = dyn_cast<OMPLinearClause>(C)) if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), B.NumIterations, *this, CurScope, DSAStack)) return StmtError(); } } getCurFunction()->setHasBranchProtectedScope(); return OMPTeamsDistributeParallelForDirective::Create( Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); } StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { if (!AStmt) return StmtError(); CapturedStmt *CS = cast<CapturedStmt>(AStmt); // 1.2.2 OpenMP Language Terminology // Structured block - An executable statement with a single entry at the // top and a single exit at the bottom. // The point of exit cannot be a branch out of the structured block. // longjmp() and throw() must not violate the entry/exit criteria. CS->getCapturedDecl()->setNothrow(); getCurFunction()->setHasBranchProtectedScope(); return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); } StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { if (!AStmt) return StmtError(); CapturedStmt *CS = cast<CapturedStmt>(AStmt); // 1.2.2 OpenMP Language Terminology // Structured block - An executable statement with a single entry at the // top and a single exit at the bottom. // The point of exit cannot be a branch out of the structured block. // longjmp() and throw() must not violate the entry/exit criteria. CS->getCapturedDecl()->setNothrow(); OMPLoopDirective::HelperExprs B; // In presence of clause 'collapse' with number of loops, it will // define the nested loops number. auto NestedLoopCount = CheckOpenMPLoop( OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses), nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); if (NestedLoopCount == 0) return StmtError(); assert((CurContext->isDependentContext() || B.builtAll()) && "omp target teams distribute loop exprs were not built"); getCurFunction()->setHasBranchProtectedScope(); return OMPTargetTeamsDistributeDirective::Create( Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); } StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { if (!AStmt) return StmtError(); CapturedStmt *CS = cast<CapturedStmt>(AStmt); // 1.2.2 OpenMP Language Terminology // Structured block - An executable statement with a single entry at the // top and a single exit at the bottom. // The point of exit cannot be a branch out of the structured block. // longjmp() and throw() must not violate the entry/exit criteria. CS->getCapturedDecl()->setNothrow(); OMPLoopDirective::HelperExprs B; // In presence of clause 'collapse' with number of loops, it will // define the nested loops number. auto NestedLoopCount = CheckOpenMPLoop( OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses), nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); if (NestedLoopCount == 0) return StmtError(); assert((CurContext->isDependentContext() || B.builtAll()) && "omp target teams distribute parallel for loop exprs were not built"); if (!CurContext->isDependentContext()) { // Finalize the clauses that need pre-built expressions for CodeGen. for (auto C : Clauses) { if (auto *LC = dyn_cast<OMPLinearClause>(C)) if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), B.NumIterations, *this, CurScope, DSAStack)) return StmtError(); } } getCurFunction()->setHasBranchProtectedScope(); return OMPTargetTeamsDistributeParallelForDirective::Create( Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); } StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { if (!AStmt) return StmtError(); CapturedStmt *CS = cast<CapturedStmt>(AStmt); // 1.2.2 OpenMP Language Terminology // Structured block - An executable statement with a single entry at the // top and a single exit at the bottom. // The point of exit cannot be a branch out of the structured block. // longjmp() and throw() must not violate the entry/exit criteria. CS->getCapturedDecl()->setNothrow(); OMPLoopDirective::HelperExprs B; // In presence of clause 'collapse' with number of loops, it will // define the nested loops number. auto NestedLoopCount = CheckOpenMPLoop( OMPD_target_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses), nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); if (NestedLoopCount == 0) return StmtError(); assert((CurContext->isDependentContext() || B.builtAll()) && "omp target teams distribute parallel for simd loop exprs were not " "built"); if (!CurContext->isDependentContext()) { // Finalize the clauses that need pre-built expressions for CodeGen. for (auto C : Clauses) { if (auto *LC = dyn_cast<OMPLinearClause>(C)) if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), B.NumIterations, *this, CurScope, DSAStack)) return StmtError(); } } getCurFunction()->setHasBranchProtectedScope(); return OMPTargetTeamsDistributeParallelForSimdDirective::Create( Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); } StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { if (!AStmt) return StmtError(); auto *CS = cast<CapturedStmt>(AStmt); // 1.2.2 OpenMP Language Terminology // Structured block - An executable statement with a single entry at the // top and a single exit at the bottom. // The point of exit cannot be a branch out of the structured block. // longjmp() and throw() must not violate the entry/exit criteria. CS->getCapturedDecl()->setNothrow(); OMPLoopDirective::HelperExprs B; // In presence of clause 'collapse' with number of loops, it will // define the nested loops number. auto NestedLoopCount = CheckOpenMPLoop( OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses), nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); if (NestedLoopCount == 0) return StmtError(); assert((CurContext->isDependentContext() || B.builtAll()) && "omp target teams distribute simd loop exprs were not built"); getCurFunction()->setHasBranchProtectedScope(); return OMPTargetTeamsDistributeSimdDirective::Create( Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); } OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { OMPClause *Res = nullptr; switch (Kind) { case OMPC_final: Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc); break; case OMPC_num_threads: Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc); break; case OMPC_safelen: Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc); break; case OMPC_simdlen: Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc); break; case OMPC_collapse: Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc); break; case OMPC_ordered: Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr); break; case OMPC_device: Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc); break; case OMPC_num_teams: Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc); break; case OMPC_thread_limit: Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc); break; case OMPC_priority: Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc); break; case OMPC_grainsize: Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc); break; case OMPC_num_tasks: Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc); break; case OMPC_hint: Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc); break; case OMPC_if: case OMPC_default: case OMPC_proc_bind: case OMPC_schedule: case OMPC_private: case OMPC_firstprivate: case OMPC_lastprivate: case OMPC_shared: case OMPC_reduction: case OMPC_task_reduction: case OMPC_in_reduction: case OMPC_linear: case OMPC_aligned: case OMPC_copyin: case OMPC_copyprivate: case OMPC_nowait: case OMPC_untied: case OMPC_mergeable: case OMPC_threadprivate: case OMPC_flush: case OMPC_read: case OMPC_write: case OMPC_update: case OMPC_capture: case OMPC_seq_cst: case OMPC_depend: case OMPC_threads: case OMPC_simd: case OMPC_map: case OMPC_nogroup: case OMPC_dist_schedule: case OMPC_defaultmap: case OMPC_unknown: case OMPC_uniform: case OMPC_to: case OMPC_from: case OMPC_use_device_ptr: case OMPC_is_device_ptr: llvm_unreachable("Clause is not allowed."); } return Res; } // An OpenMP directive such as 'target parallel' has two captured regions: // for the 'target' and 'parallel' respectively. This function returns // the region in which to capture expressions associated with a clause. // A return value of OMPD_unknown signifies that the expression should not // be captured. static OpenMPDirectiveKind getOpenMPCaptureRegionForClause( OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, OpenMPDirectiveKind NameModifier = OMPD_unknown) { OpenMPDirectiveKind CaptureRegion = OMPD_unknown; switch (CKind) { case OMPC_if: switch (DKind) { case OMPD_target_parallel: // If this clause applies to the nested 'parallel' region, capture within // the 'target' region, otherwise do not capture. if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel) CaptureRegion = OMPD_target; break; case OMPD_cancel: case OMPD_parallel: case OMPD_parallel_sections: case OMPD_parallel_for: case OMPD_parallel_for_simd: case OMPD_target: case OMPD_target_simd: case OMPD_target_parallel_for: case OMPD_target_parallel_for_simd: case OMPD_target_teams: case OMPD_target_teams_distribute: case OMPD_target_teams_distribute_simd: case OMPD_target_teams_distribute_parallel_for: case OMPD_target_teams_distribute_parallel_for_simd: case OMPD_teams_distribute_parallel_for: case OMPD_teams_distribute_parallel_for_simd: case OMPD_distribute_parallel_for: case OMPD_distribute_parallel_for_simd: case OMPD_task: case OMPD_taskloop: case OMPD_taskloop_simd: case OMPD_target_data: case OMPD_target_enter_data: case OMPD_target_exit_data: case OMPD_target_update: // Do not capture if-clause expressions. break; case OMPD_threadprivate: case OMPD_taskyield: case OMPD_barrier: case OMPD_taskwait: case OMPD_cancellation_point: case OMPD_flush: case OMPD_declare_reduction: case OMPD_declare_simd: case OMPD_declare_target: case OMPD_end_declare_target: case OMPD_teams: case OMPD_simd: case OMPD_for: case OMPD_for_simd: case OMPD_sections: case OMPD_section: case OMPD_single: case OMPD_master: case OMPD_critical: case OMPD_taskgroup: case OMPD_distribute: case OMPD_ordered: case OMPD_atomic: case OMPD_distribute_simd: case OMPD_teams_distribute: case OMPD_teams_distribute_simd: llvm_unreachable("Unexpected OpenMP directive with if-clause"); case OMPD_unknown: llvm_unreachable("Unknown OpenMP directive"); } break; case OMPC_num_threads: switch (DKind) { case OMPD_target_parallel: CaptureRegion = OMPD_target; break; case OMPD_cancel: case OMPD_parallel: case OMPD_parallel_sections: case OMPD_parallel_for: case OMPD_parallel_for_simd: case OMPD_target: case OMPD_target_simd: case OMPD_target_parallel_for: case OMPD_target_parallel_for_simd: case OMPD_target_teams: case OMPD_target_teams_distribute: case OMPD_target_teams_distribute_simd: case OMPD_target_teams_distribute_parallel_for: case OMPD_target_teams_distribute_parallel_for_simd: case OMPD_teams_distribute_parallel_for: case OMPD_teams_distribute_parallel_for_simd: case OMPD_distribute_parallel_for: case OMPD_distribute_parallel_for_simd: case OMPD_task: case OMPD_taskloop: case OMPD_taskloop_simd: case OMPD_target_data: case OMPD_target_enter_data: case OMPD_target_exit_data: case OMPD_target_update: // Do not capture num_threads-clause expressions. break; case OMPD_threadprivate: case OMPD_taskyield: case OMPD_barrier: case OMPD_taskwait: case OMPD_cancellation_point: case OMPD_flush: case OMPD_declare_reduction: case OMPD_declare_simd: case OMPD_declare_target: case OMPD_end_declare_target: case OMPD_teams: case OMPD_simd: case OMPD_for: case OMPD_for_simd: case OMPD_sections: case OMPD_section: case OMPD_single: case OMPD_master: case OMPD_critical: case OMPD_taskgroup: case OMPD_distribute: case OMPD_ordered: case OMPD_atomic: case OMPD_distribute_simd: case OMPD_teams_distribute: case OMPD_teams_distribute_simd: llvm_unreachable("Unexpected OpenMP directive with num_threads-clause"); case OMPD_unknown: llvm_unreachable("Unknown OpenMP directive"); } break; case OMPC_num_teams: switch (DKind) { case OMPD_target_teams: CaptureRegion = OMPD_target; break; case OMPD_cancel: case OMPD_parallel: case OMPD_parallel_sections: case OMPD_parallel_for: case OMPD_parallel_for_simd: case OMPD_target: case OMPD_target_simd: case OMPD_target_parallel: case OMPD_target_parallel_for: case OMPD_target_parallel_for_simd: case OMPD_target_teams_distribute: case OMPD_target_teams_distribute_simd: case OMPD_target_teams_distribute_parallel_for: case OMPD_target_teams_distribute_parallel_for_simd: case OMPD_teams_distribute_parallel_for: case OMPD_teams_distribute_parallel_for_simd: case OMPD_distribute_parallel_for: case OMPD_distribute_parallel_for_simd: case OMPD_task: case OMPD_taskloop: case OMPD_taskloop_simd: case OMPD_target_data: case OMPD_target_enter_data: case OMPD_target_exit_data: case OMPD_target_update: case OMPD_teams: case OMPD_teams_distribute: case OMPD_teams_distribute_simd: // Do not capture num_teams-clause expressions. break; case OMPD_threadprivate: case OMPD_taskyield: case OMPD_barrier: case OMPD_taskwait: case OMPD_cancellation_point: case OMPD_flush: case OMPD_declare_reduction: case OMPD_declare_simd: case OMPD_declare_target: case OMPD_end_declare_target: case OMPD_simd: case OMPD_for: case OMPD_for_simd: case OMPD_sections: case OMPD_section: case OMPD_single: case OMPD_master: case OMPD_critical: case OMPD_taskgroup: case OMPD_distribute: case OMPD_ordered: case OMPD_atomic: case OMPD_distribute_simd: llvm_unreachable("Unexpected OpenMP directive with num_teams-clause"); case OMPD_unknown: llvm_unreachable("Unknown OpenMP directive"); } break; case OMPC_thread_limit: switch (DKind) { case OMPD_target_teams: CaptureRegion = OMPD_target; break; case OMPD_cancel: case OMPD_parallel: case OMPD_parallel_sections: case OMPD_parallel_for: case OMPD_parallel_for_simd: case OMPD_target: case OMPD_target_simd: case OMPD_target_parallel: case OMPD_target_parallel_for: case OMPD_target_parallel_for_simd: case OMPD_target_teams_distribute: case OMPD_target_teams_distribute_simd: case OMPD_target_teams_distribute_parallel_for: case OMPD_target_teams_distribute_parallel_for_simd: case OMPD_teams_distribute_parallel_for: case OMPD_teams_distribute_parallel_for_simd: case OMPD_distribute_parallel_for: case OMPD_distribute_parallel_for_simd: case OMPD_task: case OMPD_taskloop: case OMPD_taskloop_simd: case OMPD_target_data: case OMPD_target_enter_data: case OMPD_target_exit_data: case OMPD_target_update: case OMPD_teams: case OMPD_teams_distribute: case OMPD_teams_distribute_simd: // Do not capture thread_limit-clause expressions. break; case OMPD_threadprivate: case OMPD_taskyield: case OMPD_barrier: case OMPD_taskwait: case OMPD_cancellation_point: case OMPD_flush: case OMPD_declare_reduction: case OMPD_declare_simd: case OMPD_declare_target: case OMPD_end_declare_target: case OMPD_simd: case OMPD_for: case OMPD_for_simd: case OMPD_sections: case OMPD_section: case OMPD_single: case OMPD_master: case OMPD_critical: case OMPD_taskgroup: case OMPD_distribute: case OMPD_ordered: case OMPD_atomic: case OMPD_distribute_simd: llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause"); case OMPD_unknown: llvm_unreachable("Unknown OpenMP directive"); } break; case OMPC_schedule: case OMPC_dist_schedule: case OMPC_firstprivate: case OMPC_lastprivate: case OMPC_reduction: case OMPC_task_reduction: case OMPC_in_reduction: case OMPC_linear: case OMPC_default: case OMPC_proc_bind: case OMPC_final: case OMPC_safelen: case OMPC_simdlen: case OMPC_collapse: case OMPC_private: case OMPC_shared: case OMPC_aligned: case OMPC_copyin: case OMPC_copyprivate: case OMPC_ordered: case OMPC_nowait: case OMPC_untied: case OMPC_mergeable: case OMPC_threadprivate: case OMPC_flush: case OMPC_read: case OMPC_write: case OMPC_update: case OMPC_capture: case OMPC_seq_cst: case OMPC_depend: case OMPC_device: case OMPC_threads: case OMPC_simd: case OMPC_map: case OMPC_priority: case OMPC_grainsize: case OMPC_nogroup: case OMPC_num_tasks: case OMPC_hint: case OMPC_defaultmap: case OMPC_unknown: case OMPC_uniform: case OMPC_to: case OMPC_from: case OMPC_use_device_ptr: case OMPC_is_device_ptr: llvm_unreachable("Unexpected OpenMP clause."); } return CaptureRegion; } OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier, Expr *Condition, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation NameModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { Expr *ValExpr = Condition; Stmt *HelperValStmt = nullptr; OpenMPDirectiveKind CaptureRegion = OMPD_unknown; if (!Condition->isValueDependent() && !Condition->isTypeDependent() && !Condition->isInstantiationDependent() && !Condition->containsUnexpandedParameterPack()) { ExprResult Val = CheckBooleanCondition(StartLoc, Condition); if (Val.isInvalid()) return nullptr; ValExpr = MakeFullExpr(Val.get()).get(); OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier); if (CaptureRegion != OMPD_unknown) { llvm::MapVector<Expr *, DeclRefExpr *> Captures; ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); HelperValStmt = buildPreInits(Context, Captures); } } return new (Context) OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, NameModifierLoc, ColonLoc, EndLoc); } OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { Expr *ValExpr = Condition; if (!Condition->isValueDependent() && !Condition->isTypeDependent() && !Condition->isInstantiationDependent() && !Condition->containsUnexpandedParameterPack()) { ExprResult Val = CheckBooleanCondition(StartLoc, Condition); if (Val.isInvalid()) return nullptr; ValExpr = MakeFullExpr(Val.get()).get(); } return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc); } ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc, Expr *Op) { if (!Op) return ExprError(); class IntConvertDiagnoser : public ICEConvertDiagnoser { public: IntConvertDiagnoser() : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {} SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) override { return S.Diag(Loc, diag::err_omp_not_integral) << T; } SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) override { return S.Diag(Loc, diag::err_omp_incomplete_type) << T; } SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy; } SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) << ConvTy->isEnumeralType() << ConvTy; } SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) override { return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T; } SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) << ConvTy->isEnumeralType() << ConvTy; } SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType, QualType) override { llvm_unreachable("conversion functions are permitted"); } } ConvertDiagnoser; return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser); } static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, OpenMPClauseKind CKind, bool StrictlyPositive) { if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() && !ValExpr->isInstantiationDependent()) { SourceLocation Loc = ValExpr->getExprLoc(); ExprResult Value = SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr); if (Value.isInvalid()) return false; ValExpr = Value.get(); // The expression must evaluate to a non-negative integer value. llvm::APSInt Result; if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) && Result.isSigned() && !((!StrictlyPositive && Result.isNonNegative()) || (StrictlyPositive && Result.isStrictlyPositive()))) { SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause) << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0) << ValExpr->getSourceRange(); return false; } } return true; } OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { Expr *ValExpr = NumThreads; Stmt *HelperValStmt = nullptr; OpenMPDirectiveKind CaptureRegion = OMPD_unknown; // OpenMP [2.5, Restrictions] // The num_threads expression must evaluate to a positive integer value. if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads, /*StrictlyPositive=*/true)) return nullptr; OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads); if (CaptureRegion != OMPD_unknown) { llvm::MapVector<Expr *, DeclRefExpr *> Captures; ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); HelperValStmt = buildPreInits(Context, Captures); } return new (Context) OMPNumThreadsClause( ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc); } ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E, OpenMPClauseKind CKind, bool StrictlyPositive) { if (!E) return ExprError(); if (E->isValueDependent() || E->isTypeDependent() || E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) return E; llvm::APSInt Result; ExprResult ICE = VerifyIntegerConstantExpression(E, &Result); if (ICE.isInvalid()) return ExprError(); if ((StrictlyPositive && !Result.isStrictlyPositive()) || (!StrictlyPositive && !Result.isNonNegative())) { Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause) << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0) << E->getSourceRange(); return ExprError(); } if (CKind == OMPC_aligned && !Result.isPowerOf2()) { Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two) << E->getSourceRange(); return ExprError(); } if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1) DSAStack->setAssociatedLoops(Result.getExtValue()); else if (CKind == OMPC_ordered) DSAStack->setAssociatedLoops(Result.getExtValue()); return ICE; } OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { // OpenMP [2.8.1, simd construct, Description] // The parameter of the safelen clause must be a constant // positive integer expression. ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen); if (Safelen.isInvalid()) return nullptr; return new (Context) OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc); } OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { // OpenMP [2.8.1, simd construct, Description] // The parameter of the simdlen clause must be a constant // positive integer expression. ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen); if (Simdlen.isInvalid()) return nullptr; return new (Context) OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc); } OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { // OpenMP [2.7.1, loop construct, Description] // OpenMP [2.8.1, simd construct, Description] // OpenMP [2.9.6, distribute construct, Description] // The parameter of the collapse clause must be a constant // positive integer expression. ExprResult NumForLoopsResult = VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse); if (NumForLoopsResult.isInvalid()) return nullptr; return new (Context) OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc); } OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc, SourceLocation LParenLoc, Expr *NumForLoops) { // OpenMP [2.7.1, loop construct, Description] // OpenMP [2.8.1, simd construct, Description] // OpenMP [2.9.6, distribute construct, Description] // The parameter of the ordered clause must be a constant // positive integer expression if any. if (NumForLoops && LParenLoc.isValid()) { ExprResult NumForLoopsResult = VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered); if (NumForLoopsResult.isInvalid()) return nullptr; NumForLoops = NumForLoopsResult.get(); } else NumForLoops = nullptr; DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops); return new (Context) OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc); } OMPClause *Sema::ActOnOpenMPSimpleClause( OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { OMPClause *Res = nullptr; switch (Kind) { case OMPC_default: Res = ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument), ArgumentLoc, StartLoc, LParenLoc, EndLoc); break; case OMPC_proc_bind: Res = ActOnOpenMPProcBindClause( static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc, LParenLoc, EndLoc); break; case OMPC_if: case OMPC_final: case OMPC_num_threads: case OMPC_safelen: case OMPC_simdlen: case OMPC_collapse: case OMPC_schedule: case OMPC_private: case OMPC_firstprivate: case OMPC_lastprivate: case OMPC_shared: case OMPC_reduction: case OMPC_task_reduction: case OMPC_in_reduction: case OMPC_linear: case OMPC_aligned: case OMPC_copyin: case OMPC_copyprivate: case OMPC_ordered: case OMPC_nowait: case OMPC_untied: case OMPC_mergeable: case OMPC_threadprivate: case OMPC_flush: case OMPC_read: case OMPC_write: case OMPC_update: case OMPC_capture: case OMPC_seq_cst: case OMPC_depend: case OMPC_device: case OMPC_threads: case OMPC_simd: case OMPC_map: case OMPC_num_teams: case OMPC_thread_limit: case OMPC_priority: case OMPC_grainsize: case OMPC_nogroup: case OMPC_num_tasks: case OMPC_hint: case OMPC_dist_schedule: case OMPC_defaultmap: case OMPC_unknown: case OMPC_uniform: case OMPC_to: case OMPC_from: case OMPC_use_device_ptr: case OMPC_is_device_ptr: llvm_unreachable("Clause is not allowed."); } return Res; } static std::string getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last, ArrayRef<unsigned> Exclude = llvm::None) { std::string Values; unsigned Bound = Last >= 2 ? Last - 2 : 0; unsigned Skipped = Exclude.size(); auto S = Exclude.begin(), E = Exclude.end(); for (unsigned i = First; i < Last; ++i) { if (std::find(S, E, i) != E) { --Skipped; continue; } Values += "'"; Values += getOpenMPSimpleClauseTypeName(K, i); Values += "'"; if (i == Bound - Skipped) Values += " or "; else if (i != Bound + 1 - Skipped) Values += ", "; } return Values; } OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind, SourceLocation KindKwLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { if (Kind == OMPC_DEFAULT_unknown) { static_assert(OMPC_DEFAULT_unknown > 0, "OMPC_DEFAULT_unknown not greater than 0"); Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) << getListOfPossibleValues(OMPC_default, /*First=*/0, /*Last=*/OMPC_DEFAULT_unknown) << getOpenMPClauseName(OMPC_default); return nullptr; } switch (Kind) { case OMPC_DEFAULT_none: DSAStack->setDefaultDSANone(KindKwLoc); break; case OMPC_DEFAULT_shared: DSAStack->setDefaultDSAShared(KindKwLoc); break; case OMPC_DEFAULT_unknown: llvm_unreachable("Clause kind is not allowed."); break; } return new (Context) OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); } OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind, SourceLocation KindKwLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { if (Kind == OMPC_PROC_BIND_unknown) { Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0, /*Last=*/OMPC_PROC_BIND_unknown) << getOpenMPClauseName(OMPC_proc_bind); return nullptr; } return new (Context) OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); } OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause( OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr, SourceLocation StartLoc, SourceLocation LParenLoc, ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc, SourceLocation EndLoc) { OMPClause *Res = nullptr; switch (Kind) { case OMPC_schedule: enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements }; assert(Argument.size() == NumberOfElements && ArgumentLoc.size() == NumberOfElements); Res = ActOnOpenMPScheduleClause( static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]), static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]), static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr, StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2], ArgumentLoc[ScheduleKind], DelimLoc, EndLoc); break; case OMPC_if: assert(Argument.size() == 1 && ArgumentLoc.size() == 1); Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()), Expr, StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc); break; case OMPC_dist_schedule: Res = ActOnOpenMPDistScheduleClause( static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr, StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc); break; case OMPC_defaultmap: enum { Modifier, DefaultmapKind }; Res = ActOnOpenMPDefaultmapClause( static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]), static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]), StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind], EndLoc); break; case OMPC_final: case OMPC_num_threads: case OMPC_safelen: case OMPC_simdlen: case OMPC_collapse: case OMPC_default: case OMPC_proc_bind: case OMPC_private: case OMPC_firstprivate: case OMPC_lastprivate: case OMPC_shared: case OMPC_reduction: case OMPC_task_reduction: case OMPC_in_reduction: case OMPC_linear: case OMPC_aligned: case OMPC_copyin: case OMPC_copyprivate: case OMPC_ordered: case OMPC_nowait: case OMPC_untied: case OMPC_mergeable: case OMPC_threadprivate: case OMPC_flush: case OMPC_read: case OMPC_write: case OMPC_update: case OMPC_capture: case OMPC_seq_cst: case OMPC_depend: case OMPC_device: case OMPC_threads: case OMPC_simd: case OMPC_map: case OMPC_num_teams: case OMPC_thread_limit: case OMPC_priority: case OMPC_grainsize: case OMPC_nogroup: case OMPC_num_tasks: case OMPC_hint: case OMPC_unknown: case OMPC_uniform: case OMPC_to: case OMPC_from: case OMPC_use_device_ptr: case OMPC_is_device_ptr: llvm_unreachable("Clause is not allowed."); } return Res; } static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2, SourceLocation M1Loc, SourceLocation M2Loc) { if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) { SmallVector<unsigned, 2> Excluded; if (M2 != OMPC_SCHEDULE_MODIFIER_unknown) Excluded.push_back(M2); if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic); if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic) Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic); S.Diag(M1Loc, diag::err_omp_unexpected_clause_value) << getListOfPossibleValues(OMPC_schedule, /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1, /*Last=*/OMPC_SCHEDULE_MODIFIER_last, Excluded) << getOpenMPClauseName(OMPC_schedule); return true; } return false; } OMPClause *Sema::ActOnOpenMPScheduleClause( OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2, OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc, SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) { if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) || checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc)) return nullptr; // OpenMP, 2.7.1, Loop Construct, Restrictions // Either the monotonic modifier or the nonmonotonic modifier can be specified // but not both. if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) || (M1 == OMPC_SCHEDULE_MODIFIER_monotonic && M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) || (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic && M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) { Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier) << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2) << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1); return nullptr; } if (Kind == OMPC_SCHEDULE_unknown) { std::string Values; if (M1Loc.isInvalid() && M2Loc.isInvalid()) { unsigned Exclude[] = {OMPC_SCHEDULE_unknown}; Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0, /*Last=*/OMPC_SCHEDULE_MODIFIER_last, Exclude); } else { Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0, /*Last=*/OMPC_SCHEDULE_unknown); } Diag(KindLoc, diag::err_omp_unexpected_clause_value) << Values << getOpenMPClauseName(OMPC_schedule); return nullptr; } // OpenMP, 2.7.1, Loop Construct, Restrictions // The nonmonotonic modifier can only be specified with schedule(dynamic) or // schedule(guided). if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic || M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) && Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) { Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc, diag::err_omp_schedule_nonmonotonic_static); return nullptr; } Expr *ValExpr = ChunkSize; Stmt *HelperValStmt = nullptr; if (ChunkSize) { if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && !ChunkSize->isInstantiationDependent() && !ChunkSize->containsUnexpandedParameterPack()) { SourceLocation ChunkSizeLoc = ChunkSize->getLocStart(); ExprResult Val = PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); if (Val.isInvalid()) return nullptr; ValExpr = Val.get(); // OpenMP [2.7.1, Restrictions] // chunk_size must be a loop invariant integer expression with a positive // value. llvm::APSInt Result; if (ValExpr->isIntegerConstantExpr(Result, Context)) { if (Result.isSigned() && !Result.isStrictlyPositive()) { Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) << "schedule" << 1 << ChunkSize->getSourceRange(); return nullptr; } } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) && !CurContext->isDependentContext()) { llvm::MapVector<Expr *, DeclRefExpr *> Captures; ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); HelperValStmt = buildPreInits(Context, Captures); } } } return new (Context) OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind, ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc); } OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc, SourceLocation EndLoc) { OMPClause *Res = nullptr; switch (Kind) { case OMPC_ordered: Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc); break; case OMPC_nowait: Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc); break; case OMPC_untied: Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc); break; case OMPC_mergeable: Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc); break; case OMPC_read: Res = ActOnOpenMPReadClause(StartLoc, EndLoc); break; case OMPC_write: Res = ActOnOpenMPWriteClause(StartLoc, EndLoc); break; case OMPC_update: Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc); break; case OMPC_capture: Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc); break; case OMPC_seq_cst: Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc); break; case OMPC_threads: Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc); break; case OMPC_simd: Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc); break; case OMPC_nogroup: Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc); break; case OMPC_if: case OMPC_final: case OMPC_num_threads: case OMPC_safelen: case OMPC_simdlen: case OMPC_collapse: case OMPC_schedule: case OMPC_private: case OMPC_firstprivate: case OMPC_lastprivate: case OMPC_shared: case OMPC_reduction: case OMPC_task_reduction: case OMPC_in_reduction: case OMPC_linear: case OMPC_aligned: case OMPC_copyin: case OMPC_copyprivate: case OMPC_default: case OMPC_proc_bind: case OMPC_threadprivate: case OMPC_flush: case OMPC_depend: case OMPC_device: case OMPC_map: case OMPC_num_teams: case OMPC_thread_limit: case OMPC_priority: case OMPC_grainsize: case OMPC_num_tasks: case OMPC_hint: case OMPC_dist_schedule: case OMPC_defaultmap: case OMPC_unknown: case OMPC_uniform: case OMPC_to: case OMPC_from: case OMPC_use_device_ptr: case OMPC_is_device_ptr: llvm_unreachable("Clause is not allowed."); } return Res; } OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc, SourceLocation EndLoc) { DSAStack->setNowaitRegion(); return new (Context) OMPNowaitClause(StartLoc, EndLoc); } OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc, SourceLocation EndLoc) { return new (Context) OMPUntiedClause(StartLoc, EndLoc); } OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc, SourceLocation EndLoc) { return new (Context) OMPMergeableClause(StartLoc, EndLoc); } OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc, SourceLocation EndLoc) { return new (Context) OMPReadClause(StartLoc, EndLoc); } OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc, SourceLocation EndLoc) { return new (Context) OMPWriteClause(StartLoc, EndLoc); } OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc, SourceLocation EndLoc) { return new (Context) OMPUpdateClause(StartLoc, EndLoc); } OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc, SourceLocation EndLoc) { return new (Context) OMPCaptureClause(StartLoc, EndLoc); } OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc, SourceLocation EndLoc) { return new (Context) OMPSeqCstClause(StartLoc, EndLoc); } OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc, SourceLocation EndLoc) { return new (Context) OMPThreadsClause(StartLoc, EndLoc); } OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc, SourceLocation EndLoc) { return new (Context) OMPSIMDClause(StartLoc, EndLoc); } OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc, SourceLocation EndLoc) { return new (Context) OMPNogroupClause(StartLoc, EndLoc); } OMPClause *Sema::ActOnOpenMPVarListClause( OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind, OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier, OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation DepLinMapLoc) { OMPClause *Res = nullptr; switch (Kind) { case OMPC_private: Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc); break; case OMPC_firstprivate: Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc); break; case OMPC_lastprivate: Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc); break; case OMPC_shared: Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc); break; case OMPC_reduction: Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec, ReductionId); break; case OMPC_task_reduction: Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec, ReductionId); break; case OMPC_in_reduction: Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec, ReductionId); break; case OMPC_linear: Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc, LinKind, DepLinMapLoc, ColonLoc, EndLoc); break; case OMPC_aligned: Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc, ColonLoc, EndLoc); break; case OMPC_copyin: Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc); break; case OMPC_copyprivate: Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc); break; case OMPC_flush: Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc); break; case OMPC_depend: Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList, StartLoc, LParenLoc, EndLoc); break; case OMPC_map: Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit, DepLinMapLoc, ColonLoc, VarList, StartLoc, LParenLoc, EndLoc); break; case OMPC_to: Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc); break; case OMPC_from: Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc); break; case OMPC_use_device_ptr: Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc); break; case OMPC_is_device_ptr: Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc); break; case OMPC_if: case OMPC_final: case OMPC_num_threads: case OMPC_safelen: case OMPC_simdlen: case OMPC_collapse: case OMPC_default: case OMPC_proc_bind: case OMPC_schedule: case OMPC_ordered: case OMPC_nowait: case OMPC_untied: case OMPC_mergeable: case OMPC_threadprivate: case OMPC_read: case OMPC_write: case OMPC_update: case OMPC_capture: case OMPC_seq_cst: case OMPC_device: case OMPC_threads: case OMPC_simd: case OMPC_num_teams: case OMPC_thread_limit: case OMPC_priority: case OMPC_grainsize: case OMPC_nogroup: case OMPC_num_tasks: case OMPC_hint: case OMPC_dist_schedule: case OMPC_defaultmap: case OMPC_unknown: case OMPC_uniform: llvm_unreachable("Clause is not allowed."); } return Res; } ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK, ExprObjectKind OK, SourceLocation Loc) { ExprResult Res = BuildDeclRefExpr( Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc); if (!Res.isUsable()) return ExprError(); if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) { Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get()); if (!Res.isUsable()) return ExprError(); } if (VK != VK_LValue && Res.get()->isGLValue()) { Res = DefaultLvalueConversion(Res.get()); if (!Res.isUsable()) return ExprError(); } return Res; } static std::pair<ValueDecl *, bool> getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc, SourceRange &ERange, bool AllowArraySection = false) { if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() || RefExpr->containsUnexpandedParameterPack()) return std::make_pair(nullptr, true); // OpenMP [3.1, C/C++] // A list item is a variable name. // OpenMP [2.9.3.3, Restrictions, p.1] // A variable that is part of another variable (as an array or // structure element) cannot appear in a private clause. RefExpr = RefExpr->IgnoreParens(); enum { NoArrayExpr = -1, ArraySubscript = 0, OMPArraySection = 1 } IsArrayExpr = NoArrayExpr; if (AllowArraySection) { if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) { auto *Base = ASE->getBase()->IgnoreParenImpCasts(); while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) Base = TempASE->getBase()->IgnoreParenImpCasts(); RefExpr = Base; IsArrayExpr = ArraySubscript; } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) { auto *Base = OASE->getBase()->IgnoreParenImpCasts(); while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) Base = TempOASE->getBase()->IgnoreParenImpCasts(); while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) Base = TempASE->getBase()->IgnoreParenImpCasts(); RefExpr = Base; IsArrayExpr = OMPArraySection; } } ELoc = RefExpr->getExprLoc(); ERange = RefExpr->getSourceRange(); RefExpr = RefExpr->IgnoreParenImpCasts(); auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr); auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr); if ((!DE || !isa<VarDecl>(DE->getDecl())) && (S.getCurrentThisType().isNull() || !ME || !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) || !isa<FieldDecl>(ME->getMemberDecl()))) { if (IsArrayExpr != NoArrayExpr) S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr << ERange; else { S.Diag(ELoc, AllowArraySection ? diag::err_omp_expected_var_name_member_expr_or_array_item : diag::err_omp_expected_var_name_member_expr) << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange; } return std::make_pair(nullptr, false); } return std::make_pair( getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false); } OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { SmallVector<Expr *, 8> Vars; SmallVector<Expr *, 8> PrivateCopies; for (auto &RefExpr : VarList) { assert(RefExpr && "NULL expr in OpenMP private clause."); SourceLocation ELoc; SourceRange ERange; Expr *SimpleRefExpr = RefExpr; auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); if (Res.second) { // It will be analyzed later. Vars.push_back(RefExpr); PrivateCopies.push_back(nullptr); } ValueDecl *D = Res.first; if (!D) continue; QualType Type = D->getType(); auto *VD = dyn_cast<VarDecl>(D); // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] // A variable that appears in a private clause must not have an incomplete // type or a reference type. if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type)) continue; Type = Type.getNonReferenceType(); // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced // in a Construct] // Variables with the predetermined data-sharing attributes may not be // listed in data-sharing attributes clauses, except for the cases // listed below. For these exceptions only, listing a predetermined // variable in a data-sharing attribute clause is allowed and overrides // the variable's predetermined data-sharing attributes. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) { Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) << getOpenMPClauseName(OMPC_private); ReportOriginalDSA(*this, DSAStack, D, DVar); continue; } auto CurrDir = DSAStack->getCurrentDirective(); // Variably modified types are not supported for tasks. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() && isOpenMPTaskingDirective(CurrDir)) { Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) << getOpenMPClauseName(OMPC_private) << Type << getOpenMPDirectiveName(CurrDir); bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; Diag(D->getLocation(), IsDecl ? diag::note_previous_decl : diag::note_defined_here) << D; continue; } // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] // A list item cannot appear in both a map clause and a data-sharing // attribute clause on the same construct if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel || CurrDir == OMPD_target_teams || CurrDir == OMPD_target_teams_distribute || CurrDir == OMPD_target_teams_distribute_parallel_for || CurrDir == OMPD_target_teams_distribute_parallel_for_simd || CurrDir == OMPD_target_teams_distribute_simd || CurrDir == OMPD_target_parallel_for_simd || CurrDir == OMPD_target_parallel_for) { OpenMPClauseKind ConflictKind; if (DSAStack->checkMappableExprComponentListsForDecl( VD, /*CurrentRegionOnly=*/true, [&](OMPClauseMappableExprCommon::MappableExprComponentListRef, OpenMPClauseKind WhereFoundClauseKind) -> bool { ConflictKind = WhereFoundClauseKind; return true; })) { Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) << getOpenMPClauseName(OMPC_private) << getOpenMPClauseName(ConflictKind) << getOpenMPDirectiveName(CurrDir); ReportOriginalDSA(*this, DSAStack, D, DVar); continue; } } // OpenMP [2.9.3.3, Restrictions, C/C++, p.1] // A variable of class type (or array thereof) that appears in a private // clause requires an accessible, unambiguous default constructor for the // class type. // Generate helper private variable and initialize it with the default // value. The address of the original variable is replaced by the address of // the new private variable in CodeGen. This new variable is not added to // IdResolver, so the code in the OpenMP region uses original variable for // proper diagnostics. Type = Type.getUnqualifiedType(); auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(), D->hasAttrs() ? &D->getAttrs() : nullptr); ActOnUninitializedDecl(VDPrivate); if (VDPrivate->isInvalidDecl()) continue; auto VDPrivateRefExpr = buildDeclRefExpr( *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc); DeclRefExpr *Ref = nullptr; if (!VD && !CurContext->isDependentContext()) Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref); Vars.push_back((VD || CurContext->isDependentContext()) ? RefExpr->IgnoreParens() : Ref); PrivateCopies.push_back(VDPrivateRefExpr); } if (Vars.empty()) return nullptr; return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, PrivateCopies); } namespace { class DiagsUninitializedSeveretyRAII { private: DiagnosticsEngine &Diags; SourceLocation SavedLoc; bool IsIgnored; public: DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc, bool IsIgnored) : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) { if (!IsIgnored) { Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init, /*Map*/ diag::Severity::Ignored, Loc); } } ~DiagsUninitializedSeveretyRAII() { if (!IsIgnored) Diags.popMappings(SavedLoc); } }; } OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { SmallVector<Expr *, 8> Vars; SmallVector<Expr *, 8> PrivateCopies; SmallVector<Expr *, 8> Inits; SmallVector<Decl *, 4> ExprCaptures; bool IsImplicitClause = StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid(); auto ImplicitClauseLoc = DSAStack->getConstructLoc(); for (auto &RefExpr : VarList) { assert(RefExpr && "NULL expr in OpenMP firstprivate clause."); SourceLocation ELoc; SourceRange ERange; Expr *SimpleRefExpr = RefExpr; auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); if (Res.second) { // It will be analyzed later. Vars.push_back(RefExpr); PrivateCopies.push_back(nullptr); Inits.push_back(nullptr); } ValueDecl *D = Res.first; if (!D) continue; ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc; QualType Type = D->getType(); auto *VD = dyn_cast<VarDecl>(D); // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] // A variable that appears in a private clause must not have an incomplete // type or a reference type. if (RequireCompleteType(ELoc, Type, diag::err_omp_firstprivate_incomplete_type)) continue; Type = Type.getNonReferenceType(); // OpenMP [2.9.3.4, Restrictions, C/C++, p.1] // A variable of class type (or array thereof) that appears in a private // clause requires an accessible, unambiguous copy constructor for the // class type. auto ElemType = Context.getBaseElementType(Type).getNonReferenceType(); // If an implicit firstprivate variable found it was checked already. DSAStackTy::DSAVarData TopDVar; if (!IsImplicitClause) { DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); TopDVar = DVar; OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); bool IsConstant = ElemType.isConstant(Context); // OpenMP [2.4.13, Data-sharing Attribute Clauses] // A list item that specifies a given variable may not appear in more // than one clause on the same directive, except that a variable may be // specified in both firstprivate and lastprivate clauses. // OpenMP 4.5 [2.10.8, Distribute Construct, p.3] // A list item may appear in a firstprivate or lastprivate clause but not // both. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate && (CurrDir == OMPD_distribute || DVar.CKind != OMPC_lastprivate) && DVar.RefExpr) { Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) << getOpenMPClauseName(OMPC_firstprivate); ReportOriginalDSA(*this, DSAStack, D, DVar); continue; } // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced // in a Construct] // Variables with the predetermined data-sharing attributes may not be // listed in data-sharing attributes clauses, except for the cases // listed below. For these exceptions only, listing a predetermined // variable in a data-sharing attribute clause is allowed and overrides // the variable's predetermined data-sharing attributes. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced // in a Construct, C/C++, p.2] // Variables with const-qualified type having no mutable member may be // listed in a firstprivate clause, even if they are static data members. if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr && DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) { Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) << getOpenMPClauseName(OMPC_firstprivate); ReportOriginalDSA(*this, DSAStack, D, DVar); continue; } // OpenMP [2.9.3.4, Restrictions, p.2] // A list item that is private within a parallel region must not appear // in a firstprivate clause on a worksharing construct if any of the // worksharing regions arising from the worksharing construct ever bind // to any of the parallel regions arising from the parallel construct. // OpenMP 4.5 [2.15.3.4, Restrictions, p.3] // A list item that is private within a teams region must not appear in a // firstprivate clause on a distribute construct if any of the distribute // regions arising from the distribute construct ever bind to any of the // teams regions arising from the teams construct. // OpenMP 4.5 [2.15.3.4, Restrictions, p.3] // A list item that appears in a reduction clause of a teams construct // must not appear in a firstprivate clause on a distribute construct if // any of the distribute regions arising from the distribute construct // ever bind to any of the teams regions arising from the teams construct. if ((isOpenMPWorksharingDirective(CurrDir) || isOpenMPDistributeDirective(CurrDir)) && !isOpenMPParallelDirective(CurrDir) && !isOpenMPTeamsDirective(CurrDir)) { DVar = DSAStack->getImplicitDSA(D, true); if (DVar.CKind != OMPC_shared && (isOpenMPParallelDirective(DVar.DKind) || isOpenMPTeamsDirective(DVar.DKind) || DVar.DKind == OMPD_unknown)) { Diag(ELoc, diag::err_omp_required_access) << getOpenMPClauseName(OMPC_firstprivate) << getOpenMPClauseName(OMPC_shared); ReportOriginalDSA(*this, DSAStack, D, DVar); continue; } } // OpenMP [2.9.3.4, Restrictions, p.3] // A list item that appears in a reduction clause of a parallel construct // must not appear in a firstprivate clause on a worksharing or task // construct if any of the worksharing or task regions arising from the // worksharing or task construct ever bind to any of the parallel regions // arising from the parallel construct. // OpenMP [2.9.3.4, Restrictions, p.4] // A list item that appears in a reduction clause in worksharing // construct must not appear in a firstprivate clause in a task construct // encountered during execution of any of the worksharing regions arising // from the worksharing construct. if (isOpenMPTaskingDirective(CurrDir)) { DVar = DSAStack->hasInnermostDSA( D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; }, [](OpenMPDirectiveKind K) -> bool { return isOpenMPParallelDirective(K) || isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K); }, /*FromParent=*/true); if (DVar.CKind == OMPC_reduction && (isOpenMPParallelDirective(DVar.DKind) || isOpenMPWorksharingDirective(DVar.DKind) || isOpenMPTeamsDirective(DVar.DKind))) { Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate) << getOpenMPDirectiveName(DVar.DKind); ReportOriginalDSA(*this, DSAStack, D, DVar); continue; } } // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] // A list item cannot appear in both a map clause and a data-sharing // attribute clause on the same construct if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel || CurrDir == OMPD_target_teams || CurrDir == OMPD_target_teams_distribute || CurrDir == OMPD_target_teams_distribute_parallel_for || CurrDir == OMPD_target_teams_distribute_parallel_for_simd || CurrDir == OMPD_target_teams_distribute_simd || CurrDir == OMPD_target_parallel_for_simd || CurrDir == OMPD_target_parallel_for) { OpenMPClauseKind ConflictKind; if (DSAStack->checkMappableExprComponentListsForDecl( VD, /*CurrentRegionOnly=*/true, [&](OMPClauseMappableExprCommon::MappableExprComponentListRef, OpenMPClauseKind WhereFoundClauseKind) -> bool { ConflictKind = WhereFoundClauseKind; return true; })) { Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) << getOpenMPClauseName(OMPC_firstprivate) << getOpenMPClauseName(ConflictKind) << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); ReportOriginalDSA(*this, DSAStack, D, DVar); continue; } } } // Variably modified types are not supported for tasks. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() && isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) { Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) << getOpenMPClauseName(OMPC_firstprivate) << Type << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; Diag(D->getLocation(), IsDecl ? diag::note_previous_decl : diag::note_defined_here) << D; continue; } Type = Type.getUnqualifiedType(); auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(), D->hasAttrs() ? &D->getAttrs() : nullptr); // Generate helper private variable and initialize it with the value of the // original variable. The address of the original variable is replaced by // the address of the new private variable in the CodeGen. This new variable // is not added to IdResolver, so the code in the OpenMP region uses // original variable for proper diagnostics and variable capturing. Expr *VDInitRefExpr = nullptr; // For arrays generate initializer for single element and replace it by the // original array element in CodeGen. if (Type->isArrayType()) { auto VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName()); VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc); auto Init = DefaultLvalueConversion(VDInitRefExpr).get(); ElemType = ElemType.getUnqualifiedType(); auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, ".firstprivate.temp"); InitializedEntity Entity = InitializedEntity::InitializeVariable(VDInitTemp); InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc); InitializationSequence InitSeq(*this, Entity, Kind, Init); ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init); if (Result.isInvalid()) VDPrivate->setInvalidDecl(); else VDPrivate->setInit(Result.getAs<Expr>()); // Remove temp variable declaration. Context.Deallocate(VDInitTemp); } else { auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".firstprivate.temp"); VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(), RefExpr->getExprLoc()); AddInitializerToDecl(VDPrivate, DefaultLvalueConversion(VDInitRefExpr).get(), /*DirectInit=*/false); } if (VDPrivate->isInvalidDecl()) { if (IsImplicitClause) { Diag(RefExpr->getExprLoc(), diag::note_omp_task_predetermined_firstprivate_here); } continue; } CurContext->addDecl(VDPrivate); auto VDPrivateRefExpr = buildDeclRefExpr( *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), RefExpr->getExprLoc()); DeclRefExpr *Ref = nullptr; if (!VD && !CurContext->isDependentContext()) { if (TopDVar.CKind == OMPC_lastprivate) Ref = TopDVar.PrivateCopy; else { Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); if (!IsOpenMPCapturedDecl(D)) ExprCaptures.push_back(Ref->getDecl()); } } DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); Vars.push_back((VD || CurContext->isDependentContext()) ? RefExpr->IgnoreParens() : Ref); PrivateCopies.push_back(VDPrivateRefExpr); Inits.push_back(VDInitRefExpr); } if (Vars.empty()) return nullptr; return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, PrivateCopies, Inits, buildPreInits(Context, ExprCaptures)); } OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { SmallVector<Expr *, 8> Vars; SmallVector<Expr *, 8> SrcExprs; SmallVector<Expr *, 8> DstExprs; SmallVector<Expr *, 8> AssignmentOps; SmallVector<Decl *, 4> ExprCaptures; SmallVector<Expr *, 4> ExprPostUpdates; for (auto &RefExpr : VarList) { assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); SourceLocation ELoc; SourceRange ERange; Expr *SimpleRefExpr = RefExpr; auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); if (Res.second) { // It will be analyzed later. Vars.push_back(RefExpr); SrcExprs.push_back(nullptr); DstExprs.push_back(nullptr); AssignmentOps.push_back(nullptr); } ValueDecl *D = Res.first; if (!D) continue; QualType Type = D->getType(); auto *VD = dyn_cast<VarDecl>(D); // OpenMP [2.14.3.5, Restrictions, C/C++, p.2] // A variable that appears in a lastprivate clause must not have an // incomplete type or a reference type. if (RequireCompleteType(ELoc, Type, diag::err_omp_lastprivate_incomplete_type)) continue; Type = Type.getNonReferenceType(); OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced // in a Construct] // Variables with the predetermined data-sharing attributes may not be // listed in data-sharing attributes clauses, except for the cases // listed below. // OpenMP 4.5 [2.10.8, Distribute Construct, p.3] // A list item may appear in a firstprivate or lastprivate clause but not // both. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate && (CurrDir == OMPD_distribute || DVar.CKind != OMPC_firstprivate) && (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) { Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) << getOpenMPClauseName(OMPC_lastprivate); ReportOriginalDSA(*this, DSAStack, D, DVar); continue; } // OpenMP [2.14.3.5, Restrictions, p.2] // A list item that is private within a parallel region, or that appears in // the reduction clause of a parallel construct, must not appear in a // lastprivate clause on a worksharing construct if any of the corresponding // worksharing regions ever binds to any of the corresponding parallel // regions. DSAStackTy::DSAVarData TopDVar = DVar; if (isOpenMPWorksharingDirective(CurrDir) && !isOpenMPParallelDirective(CurrDir) && !isOpenMPTeamsDirective(CurrDir)) { DVar = DSAStack->getImplicitDSA(D, true); if (DVar.CKind != OMPC_shared) { Diag(ELoc, diag::err_omp_required_access) << getOpenMPClauseName(OMPC_lastprivate) << getOpenMPClauseName(OMPC_shared); ReportOriginalDSA(*this, DSAStack, D, DVar); continue; } } // OpenMP [2.14.3.5, Restrictions, C++, p.1,2] // A variable of class type (or array thereof) that appears in a // lastprivate clause requires an accessible, unambiguous default // constructor for the class type, unless the list item is also specified // in a firstprivate clause. // A variable of class type (or array thereof) that appears in a // lastprivate clause requires an accessible, unambiguous copy assignment // operator for the class type. Type = Context.getBaseElementType(Type).getNonReferenceType(); auto *SrcVD = buildVarDecl(*this, ERange.getBegin(), Type.getUnqualifiedType(), ".lastprivate.src", D->hasAttrs() ? &D->getAttrs() : nullptr); auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc); auto *DstVD = buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst", D->hasAttrs() ? &D->getAttrs() : nullptr); auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc); // For arrays generate assignment operation for single element and replace // it by the original array element in CodeGen. auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr); if (AssignmentOp.isInvalid()) continue; AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue=*/true); if (AssignmentOp.isInvalid()) continue; DeclRefExpr *Ref = nullptr; if (!VD && !CurContext->isDependentContext()) { if (TopDVar.CKind == OMPC_firstprivate) Ref = TopDVar.PrivateCopy; else { Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); if (!IsOpenMPCapturedDecl(D)) ExprCaptures.push_back(Ref->getDecl()); } if (TopDVar.CKind == OMPC_firstprivate || (!IsOpenMPCapturedDecl(D) && Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) { ExprResult RefRes = DefaultLvalueConversion(Ref); if (!RefRes.isUsable()) continue; ExprResult PostUpdateRes = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr, RefRes.get()); if (!PostUpdateRes.isUsable()) continue; ExprPostUpdates.push_back( IgnoredValueConversions(PostUpdateRes.get()).get()); } } DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref); Vars.push_back((VD || CurContext->isDependentContext()) ? RefExpr->IgnoreParens() : Ref); SrcExprs.push_back(PseudoSrcExpr); DstExprs.push_back(PseudoDstExpr); AssignmentOps.push_back(AssignmentOp.get()); } if (Vars.empty()) return nullptr; return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, SrcExprs, DstExprs, AssignmentOps, buildPreInits(Context, ExprCaptures), buildPostUpdate(*this, ExprPostUpdates)); } OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { SmallVector<Expr *, 8> Vars; for (auto &RefExpr : VarList) { assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); SourceLocation ELoc; SourceRange ERange; Expr *SimpleRefExpr = RefExpr; auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); if (Res.second) { // It will be analyzed later. Vars.push_back(RefExpr); } ValueDecl *D = Res.first; if (!D) continue; auto *VD = dyn_cast<VarDecl>(D); // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced // in a Construct] // Variables with the predetermined data-sharing attributes may not be // listed in data-sharing attributes clauses, except for the cases // listed below. For these exceptions only, listing a predetermined // variable in a data-sharing attribute clause is allowed and overrides // the variable's predetermined data-sharing attributes. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared && DVar.RefExpr) { Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) << getOpenMPClauseName(OMPC_shared); ReportOriginalDSA(*this, DSAStack, D, DVar); continue; } DeclRefExpr *Ref = nullptr; if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext()) Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref); Vars.push_back((VD || !Ref || CurContext->isDependentContext()) ? RefExpr->IgnoreParens() : Ref); } if (Vars.empty()) return nullptr; return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars); } namespace { class DSARefChecker : public StmtVisitor<DSARefChecker, bool> { DSAStackTy *Stack; public: bool VisitDeclRefExpr(DeclRefExpr *E) { if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) { DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false); if (DVar.CKind == OMPC_shared && !DVar.RefExpr) return false; if (DVar.CKind != OMPC_unknown) return true; DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA( VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; }, /*FromParent=*/true); if (DVarPrivate.CKind != OMPC_unknown) return true; return false; } return false; } bool VisitStmt(Stmt *S) { for (auto Child : S->children()) { if (Child && Visit(Child)) return true; } return false; } explicit DSARefChecker(DSAStackTy *S) : Stack(S) {} }; } // namespace namespace { // Transform MemberExpression for specified FieldDecl of current class to // DeclRefExpr to specified OMPCapturedExprDecl. class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> { typedef TreeTransform<TransformExprToCaptures> BaseTransform; ValueDecl *Field; DeclRefExpr *CapturedExpr; public: TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl) : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {} ExprResult TransformMemberExpr(MemberExpr *E) { if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) && E->getMemberDecl() == Field) { CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false); return CapturedExpr; } return BaseTransform::TransformMemberExpr(E); } DeclRefExpr *getCapturedExpr() { return CapturedExpr; } }; } // namespace template <typename T> static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups, const llvm::function_ref<T(ValueDecl *)> &Gen) { for (auto &Set : Lookups) { for (auto *D : Set) { if (auto Res = Gen(cast<ValueDecl>(D))) return Res; } } return T(); } static ExprResult buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range, Scope *S, CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, QualType Ty, CXXCastPath &BasePath, Expr *UnresolvedReduction) { if (ReductionIdScopeSpec.isInvalid()) return ExprError(); SmallVector<UnresolvedSet<8>, 4> Lookups; if (S) { LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName); Lookup.suppressDiagnostics(); while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) { auto *D = Lookup.getRepresentativeDecl(); do { S = S->getParent(); } while (S && !S->isDeclScope(D)); if (S) S = S->getParent(); Lookups.push_back(UnresolvedSet<8>()); Lookups.back().append(Lookup.begin(), Lookup.end()); Lookup.clear(); } } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) { Lookups.push_back(UnresolvedSet<8>()); Decl *PrevD = nullptr; for (auto *D : ULE->decls()) { if (D == PrevD) Lookups.push_back(UnresolvedSet<8>()); else if (auto *DRD = cast<OMPDeclareReductionDecl>(D)) Lookups.back().addDecl(DRD); PrevD = D; } } if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() || Ty->isInstantiationDependentType() || Ty->containsUnexpandedParameterPack() || filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool { return !D->isInvalidDecl() && (D->getType()->isDependentType() || D->getType()->isInstantiationDependentType() || D->getType()->containsUnexpandedParameterPack()); })) { UnresolvedSet<8> ResSet; for (auto &Set : Lookups) { ResSet.append(Set.begin(), Set.end()); // The last item marks the end of all declarations at the specified scope. ResSet.addDecl(Set[Set.size() - 1]); } return UnresolvedLookupExpr::Create( SemaRef.Context, /*NamingClass=*/nullptr, ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId, /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end()); } if (auto *VD = filterLookupForUDR<ValueDecl *>( Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * { if (!D->isInvalidDecl() && SemaRef.Context.hasSameType(D->getType(), Ty)) return D; return nullptr; })) return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc); if (auto *VD = filterLookupForUDR<ValueDecl *>( Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * { if (!D->isInvalidDecl() && SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) && !Ty.isMoreQualifiedThan(D->getType())) return D; return nullptr; })) { CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, /*DetectVirtual=*/false); if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) { if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType( VD->getType().getUnqualifiedType()))) { if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(), /*DiagID=*/0) != Sema::AR_inaccessible) { SemaRef.BuildBasePathArray(Paths, BasePath); return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc); } } } } if (ReductionIdScopeSpec.isSet()) { SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range; return ExprError(); } return ExprEmpty(); } namespace { /// Data for the reduction-based clauses. struct ReductionData { /// List of original reduction items. SmallVector<Expr *, 8> Vars; /// List of private copies of the reduction items. SmallVector<Expr *, 8> Privates; /// LHS expressions for the reduction_op expressions. SmallVector<Expr *, 8> LHSs; /// RHS expressions for the reduction_op expressions. SmallVector<Expr *, 8> RHSs; /// Reduction operation expression. SmallVector<Expr *, 8> ReductionOps; /// Taskgroup descriptors for the corresponding reduction items in /// in_reduction clauses. SmallVector<Expr *, 8> TaskgroupDescriptors; /// List of captures for clause. SmallVector<Decl *, 4> ExprCaptures; /// List of postupdate expressions. SmallVector<Expr *, 4> ExprPostUpdates; ReductionData() = delete; /// Reserves required memory for the reduction data. ReductionData(unsigned Size) { Vars.reserve(Size); Privates.reserve(Size); LHSs.reserve(Size); RHSs.reserve(Size); ReductionOps.reserve(Size); TaskgroupDescriptors.reserve(Size); ExprCaptures.reserve(Size); ExprPostUpdates.reserve(Size); } /// Stores reduction item and reduction operation only (required for dependent /// reduction item). void push(Expr *Item, Expr *ReductionOp) { Vars.emplace_back(Item); Privates.emplace_back(nullptr); LHSs.emplace_back(nullptr); RHSs.emplace_back(nullptr); ReductionOps.emplace_back(ReductionOp); TaskgroupDescriptors.emplace_back(nullptr); } /// Stores reduction data. void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp, Expr *TaskgroupDescriptor) { Vars.emplace_back(Item); Privates.emplace_back(Private); LHSs.emplace_back(LHS); RHSs.emplace_back(RHS); ReductionOps.emplace_back(ReductionOp); TaskgroupDescriptors.emplace_back(TaskgroupDescriptor); } }; } // namespace static bool ActOnOMPReductionKindClause( Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind, ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) { auto DN = ReductionId.getName(); auto OOK = DN.getCXXOverloadedOperator(); BinaryOperatorKind BOK = BO_Comma; ASTContext &Context = S.Context; // OpenMP [2.14.3.6, reduction clause] // C // reduction-identifier is either an identifier or one of the following // operators: +, -, *, &, |, ^, && and || // C++ // reduction-identifier is either an id-expression or one of the following // operators: +, -, *, &, |, ^, && and || switch (OOK) { case OO_Plus: case OO_Minus: BOK = BO_Add; break; case OO_Star: BOK = BO_Mul; break; case OO_Amp: BOK = BO_And; break; case OO_Pipe: BOK = BO_Or; break; case OO_Caret: BOK = BO_Xor; break; case OO_AmpAmp: BOK = BO_LAnd; break; case OO_PipePipe: BOK = BO_LOr; break; case OO_New: case OO_Delete: case OO_Array_New: case OO_Array_Delete: case OO_Slash: case OO_Percent: case OO_Tilde: case OO_Exclaim: case OO_Equal: case OO_Less: case OO_Greater: case OO_LessEqual: case OO_GreaterEqual: case OO_PlusEqual: case OO_MinusEqual: case OO_StarEqual: case OO_SlashEqual: case OO_PercentEqual: case OO_CaretEqual: case OO_AmpEqual: case OO_PipeEqual: case OO_LessLess: case OO_GreaterGreater: case OO_LessLessEqual: case OO_GreaterGreaterEqual: case OO_EqualEqual: case OO_ExclaimEqual: case OO_PlusPlus: case OO_MinusMinus: case OO_Comma: case OO_ArrowStar: case OO_Arrow: case OO_Call: case OO_Subscript: case OO_Conditional: case OO_Coawait: case NUM_OVERLOADED_OPERATORS: llvm_unreachable("Unexpected reduction identifier"); case OO_None: if (auto *II = DN.getAsIdentifierInfo()) { if (II->isStr("max")) BOK = BO_GT; else if (II->isStr("min")) BOK = BO_LT; } break; } SourceRange ReductionIdRange; if (ReductionIdScopeSpec.isValid()) ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc()); else ReductionIdRange.setBegin(ReductionId.getBeginLoc()); ReductionIdRange.setEnd(ReductionId.getEndLoc()); auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end(); bool FirstIter = true; for (auto RefExpr : VarList) { assert(RefExpr && "nullptr expr in OpenMP reduction clause."); // OpenMP [2.1, C/C++] // A list item is a variable or array section, subject to the restrictions // specified in Section 2.4 on page 42 and in each of the sections // describing clauses and directives for which a list appears. // OpenMP [2.14.3.3, Restrictions, p.1] // A variable that is part of another variable (as an array or // structure element) cannot appear in a private clause. if (!FirstIter && IR != ER) ++IR; FirstIter = false; SourceLocation ELoc; SourceRange ERange; Expr *SimpleRefExpr = RefExpr; auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange, /*AllowArraySection=*/true); if (Res.second) { // Try to find 'declare reduction' corresponding construct before using // builtin/overloaded operators. QualType Type = Context.DependentTy; CXXCastPath BasePath; ExprResult DeclareReductionRef = buildDeclareReductionRef( S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec, ReductionId, Type, BasePath, IR == ER ? nullptr : *IR); Expr *ReductionOp = nullptr; if (S.CurContext->isDependentContext() && (DeclareReductionRef.isUnset() || isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) ReductionOp = DeclareReductionRef.get(); // It will be analyzed later. RD.push(RefExpr, ReductionOp); } ValueDecl *D = Res.first; if (!D) continue; Expr *TaskgroupDescriptor = nullptr; QualType Type; auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens()); auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens()); if (ASE) Type = ASE->getType().getNonReferenceType(); else if (OASE) { auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase()); if (auto *ATy = BaseType->getAsArrayTypeUnsafe()) Type = ATy->getElementType(); else Type = BaseType->getPointeeType(); Type = Type.getNonReferenceType(); } else Type = Context.getBaseElementType(D->getType().getNonReferenceType()); auto *VD = dyn_cast<VarDecl>(D); // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] // A variable that appears in a private clause must not have an incomplete // type or a reference type. if (S.RequireCompleteType(ELoc, Type, diag::err_omp_reduction_incomplete_type)) continue; // OpenMP [2.14.3.6, reduction clause, Restrictions] // A list item that appears in a reduction clause must not be // const-qualified. if (Type.getNonReferenceType().isConstant(Context)) { S.Diag(ELoc, diag::err_omp_const_reduction_list_item) << ERange; if (!ASE && !OASE) { bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; S.Diag(D->getLocation(), IsDecl ? diag::note_previous_decl : diag::note_defined_here) << D; } continue; } // OpenMP [2.9.3.6, Restrictions, C/C++, p.4] // If a list-item is a reference type then it must bind to the same object // for all threads of the team. if (!ASE && !OASE && VD) { VarDecl *VDDef = VD->getDefinition(); if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) { DSARefChecker Check(Stack); if (Check.Visit(VDDef->getInit())) { S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << getOpenMPClauseName(ClauseKind) << ERange; S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef; continue; } } } // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced // in a Construct] // Variables with the predetermined data-sharing attributes may not be // listed in data-sharing attributes clauses, except for the cases // listed below. For these exceptions only, listing a predetermined // variable in a data-sharing attribute clause is allowed and overrides // the variable's predetermined data-sharing attributes. // OpenMP [2.14.3.6, Restrictions, p.3] // Any number of reduction clauses can be specified on the directive, // but a list item can appear only once in the reduction clauses for that // directive. DSAStackTy::DSAVarData DVar; DVar = Stack->getTopDSA(D, false); if (DVar.CKind == OMPC_reduction) { S.Diag(ELoc, diag::err_omp_once_referenced) << getOpenMPClauseName(ClauseKind); if (DVar.RefExpr) S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced); continue; } else if (DVar.CKind != OMPC_unknown) { S.Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) << getOpenMPClauseName(OMPC_reduction); ReportOriginalDSA(S, Stack, D, DVar); continue; } // OpenMP [2.14.3.6, Restrictions, p.1] // A list item that appears in a reduction clause of a worksharing // construct must be shared in the parallel regions to which any of the // worksharing regions arising from the worksharing construct bind. OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective(); if (isOpenMPWorksharingDirective(CurrDir) && !isOpenMPParallelDirective(CurrDir) && !isOpenMPTeamsDirective(CurrDir)) { DVar = Stack->getImplicitDSA(D, true); if (DVar.CKind != OMPC_shared) { S.Diag(ELoc, diag::err_omp_required_access) << getOpenMPClauseName(OMPC_reduction) << getOpenMPClauseName(OMPC_shared); ReportOriginalDSA(S, Stack, D, DVar); continue; } } // Try to find 'declare reduction' corresponding construct before using // builtin/overloaded operators. CXXCastPath BasePath; ExprResult DeclareReductionRef = buildDeclareReductionRef( S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec, ReductionId, Type, BasePath, IR == ER ? nullptr : *IR); if (DeclareReductionRef.isInvalid()) continue; if (S.CurContext->isDependentContext() && (DeclareReductionRef.isUnset() || isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) { RD.push(RefExpr, DeclareReductionRef.get()); continue; } if (BOK == BO_Comma && DeclareReductionRef.isUnset()) { // Not allowed reduction identifier is found. S.Diag(ReductionId.getLocStart(), diag::err_omp_unknown_reduction_identifier) << Type << ReductionIdRange; continue; } // OpenMP [2.14.3.6, reduction clause, Restrictions] // The type of a list item that appears in a reduction clause must be valid // for the reduction-identifier. For a max or min reduction in C, the type // of the list item must be an allowed arithmetic data type: char, int, // float, double, or _Bool, possibly modified with long, short, signed, or // unsigned. For a max or min reduction in C++, the type of the list item // must be an allowed arithmetic data type: char, wchar_t, int, float, // double, or bool, possibly modified with long, short, signed, or unsigned. if (DeclareReductionRef.isUnset()) { if ((BOK == BO_GT || BOK == BO_LT) && !(Type->isScalarType() || (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) { S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg) << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus; if (!ASE && !OASE) { bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; S.Diag(D->getLocation(), IsDecl ? diag::note_previous_decl : diag::note_defined_here) << D; } continue; } if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) && !S.getLangOpts().CPlusPlus && Type->isFloatingType()) { S.Diag(ELoc, diag::err_omp_clause_floating_type_arg) << getOpenMPClauseName(ClauseKind); if (!ASE && !OASE) { bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; S.Diag(D->getLocation(), IsDecl ? diag::note_previous_decl : diag::note_defined_here) << D; } continue; } } Type = Type.getNonLValueExprType(Context).getUnqualifiedType(); auto *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs", D->hasAttrs() ? &D->getAttrs() : nullptr); auto *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(), D->hasAttrs() ? &D->getAttrs() : nullptr); auto PrivateTy = Type; if (OASE || (!ASE && D->getType().getNonReferenceType()->isVariablyModifiedType())) { // For arrays/array sections only: // Create pseudo array type for private copy. The size for this array will // be generated during codegen. // For array subscripts or single variables Private Ty is the same as Type // (type of the variable or single array element). PrivateTy = Context.getVariableArrayType( Type, new (Context) OpaqueValueExpr(SourceLocation(), Context.getSizeType(), VK_RValue), ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange()); } else if (!ASE && !OASE && Context.getAsArrayType(D->getType().getNonReferenceType())) PrivateTy = D->getType().getNonReferenceType(); // Private copy. auto *PrivateVD = buildVarDecl(S, ELoc, PrivateTy, D->getName(), D->hasAttrs() ? &D->getAttrs() : nullptr); // Add initializer for private variable. Expr *Init = nullptr; auto *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc); auto *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc); if (DeclareReductionRef.isUsable()) { auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>(); auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl()); if (DRD->getInitializer()) { Init = DRDRef; RHSVD->setInit(DRDRef); RHSVD->setInitStyle(VarDecl::CallInit); } } else { switch (BOK) { case BO_Add: case BO_Xor: case BO_Or: case BO_LOr: // '+', '-', '^', '|', '||' reduction ops - initializer is '0'. if (Type->isScalarType() || Type->isAnyComplexType()) Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get(); break; case BO_Mul: case BO_LAnd: if (Type->isScalarType() || Type->isAnyComplexType()) { // '*' and '&&' reduction ops - initializer is '1'. Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get(); } break; case BO_And: { // '&' reduction op - initializer is '~0'. QualType OrigType = Type; if (auto *ComplexTy = OrigType->getAs<ComplexType>()) Type = ComplexTy->getElementType(); if (Type->isRealFloatingType()) { llvm::APFloat InitValue = llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type), /*isIEEE=*/true); Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true, Type, ELoc); } else if (Type->isScalarType()) { auto Size = Context.getTypeSize(Type); QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0); llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size); Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc); } if (Init && OrigType->isAnyComplexType()) { // Init = 0xFFFF + 0xFFFFi; auto *Im = new (Context) ImaginaryLiteral(Init, OrigType); Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get(); } Type = OrigType; break; } case BO_LT: case BO_GT: { // 'min' reduction op - initializer is 'Largest representable number in // the reduction list item type'. // 'max' reduction op - initializer is 'Least representable number in // the reduction list item type'. if (Type->isIntegerType() || Type->isPointerType()) { bool IsSigned = Type->hasSignedIntegerRepresentation(); auto Size = Context.getTypeSize(Type); QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned); llvm::APInt InitValue = (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size) : llvm::APInt::getMinValue(Size) : IsSigned ? llvm::APInt::getSignedMaxValue(Size) : llvm::APInt::getMaxValue(Size); Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc); if (Type->isPointerType()) { // Cast to pointer type. auto CastExpr = S.BuildCStyleCastExpr( SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc), SourceLocation(), Init); if (CastExpr.isInvalid()) continue; Init = CastExpr.get(); } } else if (Type->isRealFloatingType()) { llvm::APFloat InitValue = llvm::APFloat::getLargest( Context.getFloatTypeSemantics(Type), BOK != BO_LT); Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true, Type, ELoc); } break; } case BO_PtrMemD: case BO_PtrMemI: case BO_MulAssign: case BO_Div: case BO_Rem: case BO_Sub: case BO_Shl: case BO_Shr: case BO_LE: case BO_GE: case BO_EQ: case BO_NE: case BO_AndAssign: case BO_XorAssign: case BO_OrAssign: case BO_Assign: case BO_AddAssign: case BO_SubAssign: case BO_DivAssign: case BO_RemAssign: case BO_ShlAssign: case BO_ShrAssign: case BO_Comma: llvm_unreachable("Unexpected reduction operation"); } } if (Init && DeclareReductionRef.isUnset()) S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false); else if (!Init) S.ActOnUninitializedDecl(RHSVD); if (RHSVD->isInvalidDecl()) continue; if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) { S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type << ReductionIdRange; bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; S.Diag(D->getLocation(), IsDecl ? diag::note_previous_decl : diag::note_defined_here) << D; continue; } // Store initializer for single element in private copy. Will be used during // codegen. PrivateVD->setInit(RHSVD->getInit()); PrivateVD->setInitStyle(RHSVD->getInitStyle()); auto *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc); ExprResult ReductionOp; if (DeclareReductionRef.isUsable()) { QualType RedTy = DeclareReductionRef.get()->getType(); QualType PtrRedTy = Context.getPointerType(RedTy); ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE); ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE); if (!BasePath.empty()) { LHS = S.DefaultLvalueConversion(LHS.get()); RHS = S.DefaultLvalueConversion(RHS.get()); LHS = ImplicitCastExpr::Create(Context, PtrRedTy, CK_UncheckedDerivedToBase, LHS.get(), &BasePath, LHS.get()->getValueKind()); RHS = ImplicitCastExpr::Create(Context, PtrRedTy, CK_UncheckedDerivedToBase, RHS.get(), &BasePath, RHS.get()->getValueKind()); } FunctionProtoType::ExtProtoInfo EPI; QualType Params[] = {PtrRedTy, PtrRedTy}; QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI); auto *OVE = new (Context) OpaqueValueExpr( ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary, S.DefaultLvalueConversion(DeclareReductionRef.get()).get()); Expr *Args[] = {LHS.get(), RHS.get()}; ReductionOp = new (Context) CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc); } else { ReductionOp = S.BuildBinOp( Stack->getCurScope(), ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE); if (ReductionOp.isUsable()) { if (BOK != BO_LT && BOK != BO_GT) { ReductionOp = S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(), BO_Assign, LHSDRE, ReductionOp.get()); } else { auto *ConditionalOp = new (Context) ConditionalOperator( ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(), RHSDRE, Type, VK_LValue, OK_Ordinary); ReductionOp = S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(), BO_Assign, LHSDRE, ConditionalOp); } if (ReductionOp.isUsable()) ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get()); } if (!ReductionOp.isUsable()) continue; } // OpenMP [2.15.4.6, Restrictions, p.2] // A list item that appears in an in_reduction clause of a task construct // must appear in a task_reduction clause of a construct associated with a // taskgroup region that includes the participating task in its taskgroup // set. The construct associated with the innermost region that meets this // condition must specify the same reduction-identifier as the in_reduction // clause. if (ClauseKind == OMPC_in_reduction) { SourceRange ParentSR; BinaryOperatorKind ParentBOK; const Expr *ParentReductionOp; Expr *ParentBOKTD, *ParentReductionOpTD; DSAStackTy::DSAVarData ParentBOKDSA = Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK, ParentBOKTD); DSAStackTy::DSAVarData ParentReductionOpDSA = Stack->getTopMostTaskgroupReductionData( D, ParentSR, ParentReductionOp, ParentReductionOpTD); bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown; bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown; if (!IsParentBOK && !IsParentReductionOp) { S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction); continue; } if ((DeclareReductionRef.isUnset() && IsParentReductionOp) || (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK || IsParentReductionOp) { bool EmitError = true; if (IsParentReductionOp && DeclareReductionRef.isUsable()) { llvm::FoldingSetNodeID RedId, ParentRedId; ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true); DeclareReductionRef.get()->Profile(RedId, Context, /*Canonical=*/true); EmitError = RedId != ParentRedId; } if (EmitError) { S.Diag(ReductionId.getLocStart(), diag::err_omp_reduction_identifier_mismatch) << ReductionIdRange << RefExpr->getSourceRange(); S.Diag(ParentSR.getBegin(), diag::note_omp_previous_reduction_identifier) << ParentSR << (IsParentBOK ? ParentBOKDSA.RefExpr : ParentReductionOpDSA.RefExpr) ->getSourceRange(); continue; } } TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD; assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined."); } DeclRefExpr *Ref = nullptr; Expr *VarsExpr = RefExpr->IgnoreParens(); if (!VD && !S.CurContext->isDependentContext()) { if (ASE || OASE) { TransformExprToCaptures RebuildToCapture(S, D); VarsExpr = RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get(); Ref = RebuildToCapture.getCapturedExpr(); } else { VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false); } if (!S.IsOpenMPCapturedDecl(D)) { RD.ExprCaptures.emplace_back(Ref->getDecl()); if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) { ExprResult RefRes = S.DefaultLvalueConversion(Ref); if (!RefRes.isUsable()) continue; ExprResult PostUpdateRes = S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr, RefRes.get()); if (!PostUpdateRes.isUsable()) continue; if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) || Stack->getCurrentDirective() == OMPD_taskgroup) { S.Diag(RefExpr->getExprLoc(), diag::err_omp_reduction_non_addressable_expression) << RefExpr->getSourceRange(); continue; } RD.ExprPostUpdates.emplace_back( S.IgnoredValueConversions(PostUpdateRes.get()).get()); } } } // All reduction items are still marked as reduction (to do not increase // code base size). Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref); if (CurrDir == OMPD_taskgroup) { if (DeclareReductionRef.isUsable()) Stack->addTaskgroupReductionData(D, ReductionIdRange, DeclareReductionRef.get()); else Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK); } RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(), TaskgroupDescriptor); } return RD.Vars.empty(); } OMPClause *Sema::ActOnOpenMPReductionClause( ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, ArrayRef<Expr *> UnresolvedReductions) { ReductionData RD(VarList.size()); if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec, ReductionId, UnresolvedReductions, RD)) return nullptr; return OMPReductionClause::Create( Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars, ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, buildPreInits(Context, RD.ExprCaptures), buildPostUpdate(*this, RD.ExprPostUpdates)); } OMPClause *Sema::ActOnOpenMPTaskReductionClause( ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, ArrayRef<Expr *> UnresolvedReductions) { ReductionData RD(VarList.size()); if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec, ReductionId, UnresolvedReductions, RD)) return nullptr; return OMPTaskReductionClause::Create( Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars, ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, buildPreInits(Context, RD.ExprCaptures), buildPostUpdate(*this, RD.ExprPostUpdates)); } OMPClause *Sema::ActOnOpenMPInReductionClause( ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, ArrayRef<Expr *> UnresolvedReductions) { ReductionData RD(VarList.size()); if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec, ReductionId, UnresolvedReductions, RD)) return nullptr; return OMPInReductionClause::Create( Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars, ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors, buildPreInits(Context, RD.ExprCaptures), buildPostUpdate(*this, RD.ExprPostUpdates)); } bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind, SourceLocation LinLoc) { if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) || LinKind == OMPC_LINEAR_unknown) { Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus; return true; } return false; } bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc, OpenMPLinearClauseKind LinKind, QualType Type) { auto *VD = dyn_cast_or_null<VarDecl>(D); // A variable must not have an incomplete type or a reference type. if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type)) return true; if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) && !Type->isReferenceType()) { Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference) << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind); return true; } Type = Type.getNonReferenceType(); // A list item must not be const-qualified. if (Type.isConstant(Context)) { Diag(ELoc, diag::err_omp_const_variable) << getOpenMPClauseName(OMPC_linear); if (D) { bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; Diag(D->getLocation(), IsDecl ? diag::note_previous_decl : diag::note_defined_here) << D; } return true; } // A list item must be of integral or pointer type. Type = Type.getUnqualifiedType().getCanonicalType(); const auto *Ty = Type.getTypePtrOrNull(); if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) && !Ty->isPointerType())) { Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type; if (D) { bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; Diag(D->getLocation(), IsDecl ? diag::note_previous_decl : diag::note_defined_here) << D; } return true; } return false; } OMPClause *Sema::ActOnOpenMPLinearClause( ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc, SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind, SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { SmallVector<Expr *, 8> Vars; SmallVector<Expr *, 8> Privates; SmallVector<Expr *, 8> Inits; SmallVector<Decl *, 4> ExprCaptures; SmallVector<Expr *, 4> ExprPostUpdates; if (CheckOpenMPLinearModifier(LinKind, LinLoc)) LinKind = OMPC_LINEAR_val; for (auto &RefExpr : VarList) { assert(RefExpr && "NULL expr in OpenMP linear clause."); SourceLocation ELoc; SourceRange ERange; Expr *SimpleRefExpr = RefExpr; auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, /*AllowArraySection=*/false); if (Res.second) { // It will be analyzed later. Vars.push_back(RefExpr); Privates.push_back(nullptr); Inits.push_back(nullptr); } ValueDecl *D = Res.first; if (!D) continue; QualType Type = D->getType(); auto *VD = dyn_cast<VarDecl>(D); // OpenMP [2.14.3.7, linear clause] // A list-item cannot appear in more than one linear clause. // A list-item that appears in a linear clause cannot appear in any // other data-sharing attribute clause. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); if (DVar.RefExpr) { Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) << getOpenMPClauseName(OMPC_linear); ReportOriginalDSA(*this, DSAStack, D, DVar); continue; } if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type)) continue; Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType(); // Build private copy of original var. auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(), D->hasAttrs() ? &D->getAttrs() : nullptr); auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc); // Build var to save initial value. VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start"); Expr *InitExpr; DeclRefExpr *Ref = nullptr; if (!VD && !CurContext->isDependentContext()) { Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); if (!IsOpenMPCapturedDecl(D)) { ExprCaptures.push_back(Ref->getDecl()); if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) { ExprResult RefRes = DefaultLvalueConversion(Ref); if (!RefRes.isUsable()) continue; ExprResult PostUpdateRes = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr, RefRes.get()); if (!PostUpdateRes.isUsable()) continue; ExprPostUpdates.push_back( IgnoredValueConversions(PostUpdateRes.get()).get()); } } } if (LinKind == OMPC_LINEAR_uval) InitExpr = VD ? VD->getInit() : SimpleRefExpr; else InitExpr = VD ? SimpleRefExpr : Ref; AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(), /*DirectInit=*/false); auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc); DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref); Vars.push_back((VD || CurContext->isDependentContext()) ? RefExpr->IgnoreParens() : Ref); Privates.push_back(PrivateRef); Inits.push_back(InitRef); } if (Vars.empty()) return nullptr; Expr *StepExpr = Step; Expr *CalcStepExpr = nullptr; if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && !Step->isInstantiationDependent() && !Step->containsUnexpandedParameterPack()) { SourceLocation StepLoc = Step->getLocStart(); ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step); if (Val.isInvalid()) return nullptr; StepExpr = Val.get(); // Build var to save the step value. VarDecl *SaveVar = buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step"); ExprResult SaveRef = buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc); ExprResult CalcStep = BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr); CalcStep = ActOnFinishFullExpr(CalcStep.get()); // Warn about zero linear step (it would be probably better specified as // making corresponding variables 'const'). llvm::APSInt Result; bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context); if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive()) Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0] << (Vars.size() > 1); if (!IsConstant && CalcStep.isUsable()) { // Calculate the step beforehand instead of doing this on each iteration. // (This is not used if the number of iterations may be kfold-ed). CalcStepExpr = CalcStep.get(); } } return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc, ColonLoc, EndLoc, Vars, Privates, Inits, StepExpr, CalcStepExpr, buildPreInits(Context, ExprCaptures), buildPostUpdate(*this, ExprPostUpdates)); } static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV, Expr *NumIterations, Sema &SemaRef, Scope *S, DSAStackTy *Stack) { // Walk the vars and build update/final expressions for the CodeGen. SmallVector<Expr *, 8> Updates; SmallVector<Expr *, 8> Finals; Expr *Step = Clause.getStep(); Expr *CalcStep = Clause.getCalcStep(); // OpenMP [2.14.3.7, linear clause] // If linear-step is not specified it is assumed to be 1. if (Step == nullptr) Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(); else if (CalcStep) { Step = cast<BinaryOperator>(CalcStep)->getLHS(); } bool HasErrors = false; auto CurInit = Clause.inits().begin(); auto CurPrivate = Clause.privates().begin(); auto LinKind = Clause.getModifier(); for (auto &RefExpr : Clause.varlists()) { SourceLocation ELoc; SourceRange ERange; Expr *SimpleRefExpr = RefExpr; auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange, /*AllowArraySection=*/false); ValueDecl *D = Res.first; if (Res.second || !D) { Updates.push_back(nullptr); Finals.push_back(nullptr); HasErrors = true; continue; } auto &&Info = Stack->isLoopControlVariable(D); Expr *InitExpr = *CurInit; // Build privatized reference to the current linear var. auto *DE = cast<DeclRefExpr>(SimpleRefExpr); Expr *CapturedRef; if (LinKind == OMPC_LINEAR_uval) CapturedRef = cast<VarDecl>(DE->getDecl())->getInit(); else CapturedRef = buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()), DE->getType().getUnqualifiedType(), DE->getExprLoc(), /*RefersToCapture=*/true); // Build update: Var = InitExpr + IV * Step ExprResult Update; if (!Info.first) { Update = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, InitExpr, IV, Step, /* Subtract */ false); } else Update = *CurPrivate; Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(), /*DiscardedValue=*/true); // Build final: Var = InitExpr + NumIterations * Step ExprResult Final; if (!Info.first) { Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef, InitExpr, NumIterations, Step, /* Subtract */ false); } else Final = *CurPrivate; Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(), /*DiscardedValue=*/true); if (!Update.isUsable() || !Final.isUsable()) { Updates.push_back(nullptr); Finals.push_back(nullptr); HasErrors = true; } else { Updates.push_back(Update.get()); Finals.push_back(Final.get()); } ++CurInit; ++CurPrivate; } Clause.setUpdates(Updates); Clause.setFinals(Finals); return HasErrors; } OMPClause *Sema::ActOnOpenMPAlignedClause( ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { SmallVector<Expr *, 8> Vars; for (auto &RefExpr : VarList) { assert(RefExpr && "NULL expr in OpenMP linear clause."); SourceLocation ELoc; SourceRange ERange; Expr *SimpleRefExpr = RefExpr; auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, /*AllowArraySection=*/false); if (Res.second) { // It will be analyzed later. Vars.push_back(RefExpr); } ValueDecl *D = Res.first; if (!D) continue; QualType QType = D->getType(); auto *VD = dyn_cast<VarDecl>(D); // OpenMP [2.8.1, simd construct, Restrictions] // The type of list items appearing in the aligned clause must be // array, pointer, reference to array, or reference to pointer. QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType(); const Type *Ty = QType.getTypePtrOrNull(); if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) { Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr) << QType << getLangOpts().CPlusPlus << ERange; bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; Diag(D->getLocation(), IsDecl ? diag::note_previous_decl : diag::note_defined_here) << D; continue; } // OpenMP [2.8.1, simd construct, Restrictions] // A list-item cannot appear in more than one aligned clause. if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) { Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange; Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa) << getOpenMPClauseName(OMPC_aligned); continue; } DeclRefExpr *Ref = nullptr; if (!VD && IsOpenMPCapturedDecl(D)) Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); Vars.push_back(DefaultFunctionArrayConversion( (VD || !Ref) ? RefExpr->IgnoreParens() : Ref) .get()); } // OpenMP [2.8.1, simd construct, Description] // The parameter of the aligned clause, alignment, must be a constant // positive integer expression. // If no optional parameter is specified, implementation-defined default // alignments for SIMD instructions on the target platforms are assumed. if (Alignment != nullptr) { ExprResult AlignResult = VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned); if (AlignResult.isInvalid()) return nullptr; Alignment = AlignResult.get(); } if (Vars.empty()) return nullptr; return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars, Alignment); } OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { SmallVector<Expr *, 8> Vars; SmallVector<Expr *, 8> SrcExprs; SmallVector<Expr *, 8> DstExprs; SmallVector<Expr *, 8> AssignmentOps; for (auto &RefExpr : VarList) { assert(RefExpr && "NULL expr in OpenMP copyin clause."); if (isa<DependentScopeDeclRefExpr>(RefExpr)) { // It will be analyzed later. Vars.push_back(RefExpr); SrcExprs.push_back(nullptr); DstExprs.push_back(nullptr); AssignmentOps.push_back(nullptr); continue; } SourceLocation ELoc = RefExpr->getExprLoc(); // OpenMP [2.1, C/C++] // A list item is a variable name. // OpenMP [2.14.4.1, Restrictions, p.1] // A list item that appears in a copyin clause must be threadprivate. DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr); if (!DE || !isa<VarDecl>(DE->getDecl())) { Diag(ELoc, diag::err_omp_expected_var_name_member_expr) << 0 << RefExpr->getSourceRange(); continue; } Decl *D = DE->getDecl(); VarDecl *VD = cast<VarDecl>(D); QualType Type = VD->getType(); if (Type->isDependentType() || Type->isInstantiationDependentType()) { // It will be analyzed later. Vars.push_back(DE); SrcExprs.push_back(nullptr); DstExprs.push_back(nullptr); AssignmentOps.push_back(nullptr); continue; } // OpenMP [2.14.4.1, Restrictions, C/C++, p.1] // A list item that appears in a copyin clause must be threadprivate. if (!DSAStack->isThreadPrivate(VD)) { Diag(ELoc, diag::err_omp_required_access) << getOpenMPClauseName(OMPC_copyin) << getOpenMPDirectiveName(OMPD_threadprivate); continue; } // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] // A variable of class type (or array thereof) that appears in a // copyin clause requires an accessible, unambiguous copy assignment // operator for the class type. auto ElemType = Context.getBaseElementType(Type).getNonReferenceType(); auto *SrcVD = buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(), ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr); auto *PseudoSrcExpr = buildDeclRefExpr( *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc()); auto *DstVD = buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst", VD->hasAttrs() ? &VD->getAttrs() : nullptr); auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc()); // For arrays generate assignment operation for single element and replace // it by the original array element in CodeGen. auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr, PseudoSrcExpr); if (AssignmentOp.isInvalid()) continue; AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(), /*DiscardedValue=*/true); if (AssignmentOp.isInvalid()) continue; DSAStack->addDSA(VD, DE, OMPC_copyin); Vars.push_back(DE); SrcExprs.push_back(PseudoSrcExpr); DstExprs.push_back(PseudoDstExpr); AssignmentOps.push_back(AssignmentOp.get()); } if (Vars.empty()) return nullptr; return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, SrcExprs, DstExprs, AssignmentOps); } OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { SmallVector<Expr *, 8> Vars; SmallVector<Expr *, 8> SrcExprs; SmallVector<Expr *, 8> DstExprs; SmallVector<Expr *, 8> AssignmentOps; for (auto &RefExpr : VarList) { assert(RefExpr && "NULL expr in OpenMP linear clause."); SourceLocation ELoc; SourceRange ERange; Expr *SimpleRefExpr = RefExpr; auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, /*AllowArraySection=*/false); if (Res.second) { // It will be analyzed later. Vars.push_back(RefExpr); SrcExprs.push_back(nullptr); DstExprs.push_back(nullptr); AssignmentOps.push_back(nullptr); } ValueDecl *D = Res.first; if (!D) continue; QualType Type = D->getType(); auto *VD = dyn_cast<VarDecl>(D); // OpenMP [2.14.4.2, Restrictions, p.2] // A list item that appears in a copyprivate clause may not appear in a // private or firstprivate clause on the single construct. if (!VD || !DSAStack->isThreadPrivate(VD)) { auto DVar = DSAStack->getTopDSA(D, false); if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate && DVar.RefExpr) { Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) << getOpenMPClauseName(OMPC_copyprivate); ReportOriginalDSA(*this, DSAStack, D, DVar); continue; } // OpenMP [2.11.4.2, Restrictions, p.1] // All list items that appear in a copyprivate clause must be either // threadprivate or private in the enclosing context. if (DVar.CKind == OMPC_unknown) { DVar = DSAStack->getImplicitDSA(D, false); if (DVar.CKind == OMPC_shared) { Diag(ELoc, diag::err_omp_required_access) << getOpenMPClauseName(OMPC_copyprivate) << "threadprivate or private in the enclosing context"; ReportOriginalDSA(*this, DSAStack, D, DVar); continue; } } } // Variably modified types are not supported. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) { Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) << getOpenMPClauseName(OMPC_copyprivate) << Type << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; Diag(D->getLocation(), IsDecl ? diag::note_previous_decl : diag::note_defined_here) << D; continue; } // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] // A variable of class type (or array thereof) that appears in a // copyin clause requires an accessible, unambiguous copy assignment // operator for the class type. Type = Context.getBaseElementType(Type.getNonReferenceType()) .getUnqualifiedType(); auto *SrcVD = buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src", D->hasAttrs() ? &D->getAttrs() : nullptr); auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc); auto *DstVD = buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst", D->hasAttrs() ? &D->getAttrs() : nullptr); auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc); auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr); if (AssignmentOp.isInvalid()) continue; AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue=*/true); if (AssignmentOp.isInvalid()) continue; // No need to mark vars as copyprivate, they are already threadprivate or // implicitly private. assert(VD || IsOpenMPCapturedDecl(D)); Vars.push_back( VD ? RefExpr->IgnoreParens() : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false)); SrcExprs.push_back(PseudoSrcExpr); DstExprs.push_back(PseudoDstExpr); AssignmentOps.push_back(AssignmentOp.get()); } if (Vars.empty()) return nullptr; return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, SrcExprs, DstExprs, AssignmentOps); } OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { if (VarList.empty()) return nullptr; return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList); } OMPClause * Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { if (DSAStack->getCurrentDirective() == OMPD_ordered && DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) { Diag(DepLoc, diag::err_omp_unexpected_clause_value) << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend); return nullptr; } if (DSAStack->getCurrentDirective() != OMPD_ordered && (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source || DepKind == OMPC_DEPEND_sink)) { unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink}; Diag(DepLoc, diag::err_omp_unexpected_clause_value) << getListOfPossibleValues(OMPC_depend, /*First=*/0, /*Last=*/OMPC_DEPEND_unknown, Except) << getOpenMPClauseName(OMPC_depend); return nullptr; } SmallVector<Expr *, 8> Vars; DSAStackTy::OperatorOffsetTy OpsOffs; llvm::APSInt DepCounter(/*BitWidth=*/32); llvm::APSInt TotalDepCount(/*BitWidth=*/32); if (DepKind == OMPC_DEPEND_sink) { if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) { TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context); TotalDepCount.setIsUnsigned(/*Val=*/true); } } if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) || DSAStack->getParentOrderedRegionParam()) { for (auto &RefExpr : VarList) { assert(RefExpr && "NULL expr in OpenMP shared clause."); if (isa<DependentScopeDeclRefExpr>(RefExpr)) { // It will be analyzed later. Vars.push_back(RefExpr); continue; } SourceLocation ELoc = RefExpr->getExprLoc(); auto *SimpleExpr = RefExpr->IgnoreParenCasts(); if (DepKind == OMPC_DEPEND_sink) { if (DepCounter >= TotalDepCount) { Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr); continue; } ++DepCounter; // OpenMP [2.13.9, Summary] // depend(dependence-type : vec), where dependence-type is: // 'sink' and where vec is the iteration vector, which has the form: // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn] // where n is the value specified by the ordered clause in the loop // directive, xi denotes the loop iteration variable of the i-th nested // loop associated with the loop directive, and di is a constant // non-negative integer. if (CurContext->isDependentContext()) { // It will be analyzed later. Vars.push_back(RefExpr); continue; } SimpleExpr = SimpleExpr->IgnoreImplicit(); OverloadedOperatorKind OOK = OO_None; SourceLocation OOLoc; Expr *LHS = SimpleExpr; Expr *RHS = nullptr; if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) { OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode()); OOLoc = BO->getOperatorLoc(); LHS = BO->getLHS()->IgnoreParenImpCasts(); RHS = BO->getRHS()->IgnoreParenImpCasts(); } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) { OOK = OCE->getOperator(); OOLoc = OCE->getOperatorLoc(); LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts(); } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) { OOK = MCE->getMethodDecl() ->getNameInfo() .getName() .getCXXOverloadedOperator(); OOLoc = MCE->getCallee()->getExprLoc(); LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts(); RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); } SourceLocation ELoc; SourceRange ERange; auto Res = getPrivateItem(*this, LHS, ELoc, ERange, /*AllowArraySection=*/false); if (Res.second) { // It will be analyzed later. Vars.push_back(RefExpr); } ValueDecl *D = Res.first; if (!D) continue; if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) { Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus); continue; } if (RHS) { ExprResult RHSRes = VerifyPositiveIntegerConstantInClause( RHS, OMPC_depend, /*StrictlyPositive=*/false); if (RHSRes.isInvalid()) continue; } if (!CurContext->isDependentContext() && DSAStack->getParentOrderedRegionParam() && DepCounter != DSAStack->isParentLoopControlVariable(D).first) { ValueDecl* VD = DSAStack->getParentLoopControlVariable( DepCounter.getZExtValue()); if (VD) { Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 1 << VD; } else { Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0; } continue; } OpsOffs.push_back({RHS, OOK}); } else { auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr); if (!RefExpr->IgnoreParenImpCasts()->isLValue() || (ASE && !ASE->getBase() ->getType() .getNonReferenceType() ->isPointerType() && !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) { Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) << RefExpr->getSourceRange(); continue; } bool Suppress = getDiagnostics().getSuppressAllDiagnostics(); getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true); ExprResult Res = CreateBuiltinUnaryOp(SourceLocation(), UO_AddrOf, RefExpr->IgnoreParenImpCasts()); getDiagnostics().setSuppressAllDiagnostics(Suppress); if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) { Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) << RefExpr->getSourceRange(); continue; } } Vars.push_back(RefExpr->IgnoreParenImpCasts()); } if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink && TotalDepCount > VarList.size() && DSAStack->getParentOrderedRegionParam() && DSAStack->getParentLoopControlVariable(VarList.size() + 1)) { Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration) << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1); } if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink && Vars.empty()) return nullptr; } auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc, DepKind, DepLoc, ColonLoc, Vars); if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) DSAStack->addDoacrossDependClause(C, OpsOffs); return C; } OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { Expr *ValExpr = Device; Stmt *HelperValStmt = nullptr; // OpenMP [2.9.1, Restrictions] // The device expression must evaluate to a non-negative integer value. if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device, /*StrictlyPositive=*/false)) return nullptr; OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); if (isOpenMPTargetExecutionDirective(DKind) && !CurContext->isDependentContext()) { llvm::MapVector<Expr *, DeclRefExpr *> Captures; ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); HelperValStmt = buildPreInits(Context, Captures); } return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, StartLoc, LParenLoc, EndLoc); } static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef, DSAStackTy *Stack, QualType QTy) { NamedDecl *ND; if (QTy->isIncompleteType(&ND)) { SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR; return false; } return true; } /// \brief Return true if it can be proven that the provided array expression /// (array section or array subscript) does NOT specify the whole size of the /// array whose base type is \a BaseQTy. static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef, const Expr *E, QualType BaseQTy) { auto *OASE = dyn_cast<OMPArraySectionExpr>(E); // If this is an array subscript, it refers to the whole size if the size of // the dimension is constant and equals 1. Also, an array section assumes the // format of an array subscript if no colon is used. if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) { if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr())) return ATy->getSize().getSExtValue() != 1; // Size can't be evaluated statically. return false; } assert(OASE && "Expecting array section if not an array subscript."); auto *LowerBound = OASE->getLowerBound(); auto *Length = OASE->getLength(); // If there is a lower bound that does not evaluates to zero, we are not // covering the whole dimension. if (LowerBound) { llvm::APSInt ConstLowerBound; if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext())) return false; // Can't get the integer value as a constant. if (ConstLowerBound.getSExtValue()) return true; } // If we don't have a length we covering the whole dimension. if (!Length) return false; // If the base is a pointer, we don't have a way to get the size of the // pointee. if (BaseQTy->isPointerType()) return false; // We can only check if the length is the same as the size of the dimension // if we have a constant array. auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()); if (!CATy) return false; llvm::APSInt ConstLength; if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext())) return false; // Can't get the integer value as a constant. return CATy->getSize().getSExtValue() != ConstLength.getSExtValue(); } // Return true if it can be proven that the provided array expression (array // section or array subscript) does NOT specify a single element of the array // whose base type is \a BaseQTy. static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef, const Expr *E, QualType BaseQTy) { auto *OASE = dyn_cast<OMPArraySectionExpr>(E); // An array subscript always refer to a single element. Also, an array section // assumes the format of an array subscript if no colon is used. if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) return false; assert(OASE && "Expecting array section if not an array subscript."); auto *Length = OASE->getLength(); // If we don't have a length we have to check if the array has unitary size // for this dimension. Also, we should always expect a length if the base type // is pointer. if (!Length) { if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr())) return ATy->getSize().getSExtValue() != 1; // We cannot assume anything. return false; } // Check if the length evaluates to 1. llvm::APSInt ConstLength; if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext())) return false; // Can't get the integer value as a constant. return ConstLength.getSExtValue() != 1; } // Return the expression of the base of the mappable expression or null if it // cannot be determined and do all the necessary checks to see if the expression // is valid as a standalone mappable expression. In the process, record all the // components of the expression. static Expr *CheckMapClauseExpressionBase( Sema &SemaRef, Expr *E, OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents, OpenMPClauseKind CKind) { SourceLocation ELoc = E->getExprLoc(); SourceRange ERange = E->getSourceRange(); // The base of elements of list in a map clause have to be either: // - a reference to variable or field. // - a member expression. // - an array expression. // // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the // reference to 'r'. // // If we have: // // struct SS { // Bla S; // foo() { // #pragma omp target map (S.Arr[:12]); // } // } // // We want to retrieve the member expression 'this->S'; Expr *RelevantExpr = nullptr; // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2] // If a list item is an array section, it must specify contiguous storage. // // For this restriction it is sufficient that we make sure only references // to variables or fields and array expressions, and that no array sections // exist except in the rightmost expression (unless they cover the whole // dimension of the array). E.g. these would be invalid: // // r.ArrS[3:5].Arr[6:7] // // r.ArrS[3:5].x // // but these would be valid: // r.ArrS[3].Arr[6:7] // // r.ArrS[3].x bool AllowUnitySizeArraySection = true; bool AllowWholeSizeArraySection = true; while (!RelevantExpr) { E = E->IgnoreParenImpCasts(); if (auto *CurE = dyn_cast<DeclRefExpr>(E)) { if (!isa<VarDecl>(CurE->getDecl())) break; RelevantExpr = CurE; // If we got a reference to a declaration, we should not expect any array // section before that. AllowUnitySizeArraySection = false; AllowWholeSizeArraySection = false; // Record the component. CurComponents.push_back(OMPClauseMappableExprCommon::MappableComponent( CurE, CurE->getDecl())); continue; } if (auto *CurE = dyn_cast<MemberExpr>(E)) { auto *BaseE = CurE->getBase()->IgnoreParenImpCasts(); if (isa<CXXThisExpr>(BaseE)) // We found a base expression: this->Val. RelevantExpr = CurE; else E = BaseE; if (!isa<FieldDecl>(CurE->getMemberDecl())) { SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field) << CurE->getSourceRange(); break; } auto *FD = cast<FieldDecl>(CurE->getMemberDecl()); // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3] // A bit-field cannot appear in a map clause. // if (FD->isBitField()) { SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause) << CurE->getSourceRange() << getOpenMPClauseName(CKind); break; } // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] // If the type of a list item is a reference to a type T then the type // will be considered to be T for all purposes of this clause. QualType CurType = BaseE->getType().getNonReferenceType(); // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2] // A list item cannot be a variable that is a member of a structure with // a union type. // if (auto *RT = CurType->getAs<RecordType>()) if (RT->isUnionType()) { SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed) << CurE->getSourceRange(); break; } // If we got a member expression, we should not expect any array section // before that: // // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7] // If a list item is an element of a structure, only the rightmost symbol // of the variable reference can be an array section. // AllowUnitySizeArraySection = false; AllowWholeSizeArraySection = false; // Record the component. CurComponents.push_back( OMPClauseMappableExprCommon::MappableComponent(CurE, FD)); continue; } if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) { E = CurE->getBase()->IgnoreParenImpCasts(); if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) { SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name) << 0 << CurE->getSourceRange(); break; } // If we got an array subscript that express the whole dimension we // can have any array expressions before. If it only expressing part of // the dimension, we can only have unitary-size array expressions. if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, E->getType())) AllowWholeSizeArraySection = false; // Record the component - we don't have any declaration associated. CurComponents.push_back( OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr)); continue; } if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) { E = CurE->getBase()->IgnoreParenImpCasts(); auto CurType = OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType(); // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] // If the type of a list item is a reference to a type T then the type // will be considered to be T for all purposes of this clause. if (CurType->isReferenceType()) CurType = CurType->getPointeeType(); bool IsPointer = CurType->isAnyPointerType(); if (!IsPointer && !CurType->isArrayType()) { SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name) << 0 << CurE->getSourceRange(); break; } bool NotWhole = CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType); bool NotUnity = CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType); if (AllowWholeSizeArraySection) { // Any array section is currently allowed. Allowing a whole size array // section implies allowing a unity array section as well. // // If this array section refers to the whole dimension we can still // accept other array sections before this one, except if the base is a // pointer. Otherwise, only unitary sections are accepted. if (NotWhole || IsPointer) AllowWholeSizeArraySection = false; } else if (AllowUnitySizeArraySection && NotUnity) { // A unity or whole array section is not allowed and that is not // compatible with the properties of the current array section. SemaRef.Diag( ELoc, diag::err_array_section_does_not_specify_contiguous_storage) << CurE->getSourceRange(); break; } // Record the component - we don't have any declaration associated. CurComponents.push_back( OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr)); continue; } // If nothing else worked, this is not a valid map clause expression. SemaRef.Diag(ELoc, diag::err_omp_expected_named_var_member_or_array_expression) << ERange; break; } return RelevantExpr; } // Return true if expression E associated with value VD has conflicts with other // map information. static bool CheckMapConflicts( Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E, bool CurrentRegionOnly, OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents, OpenMPClauseKind CKind) { assert(VD && E); SourceLocation ELoc = E->getExprLoc(); SourceRange ERange = E->getSourceRange(); // In order to easily check the conflicts we need to match each component of // the expression under test with the components of the expressions that are // already in the stack. assert(!CurComponents.empty() && "Map clause expression with no components!"); assert(CurComponents.back().getAssociatedDeclaration() == VD && "Map clause expression with unexpected base!"); // Variables to help detecting enclosing problems in data environment nests. bool IsEnclosedByDataEnvironmentExpr = false; const Expr *EnclosingExpr = nullptr; bool FoundError = DSAS->checkMappableExprComponentListsForDecl( VD, CurrentRegionOnly, [&](OMPClauseMappableExprCommon::MappableExprComponentListRef StackComponents, OpenMPClauseKind) -> bool { assert(!StackComponents.empty() && "Map clause expression with no components!"); assert(StackComponents.back().getAssociatedDeclaration() == VD && "Map clause expression with unexpected base!"); // The whole expression in the stack. auto *RE = StackComponents.front().getAssociatedExpression(); // Expressions must start from the same base. Here we detect at which // point both expressions diverge from each other and see if we can // detect if the memory referred to both expressions is contiguous and // do not overlap. auto CI = CurComponents.rbegin(); auto CE = CurComponents.rend(); auto SI = StackComponents.rbegin(); auto SE = StackComponents.rend(); for (; CI != CE && SI != SE; ++CI, ++SI) { // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3] // At most one list item can be an array item derived from a given // variable in map clauses of the same construct. if (CurrentRegionOnly && (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) || isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) && (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) || isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) { SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(), diag::err_omp_multiple_array_items_in_map_clause) << CI->getAssociatedExpression()->getSourceRange(); SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(), diag::note_used_here) << SI->getAssociatedExpression()->getSourceRange(); return true; } // Do both expressions have the same kind? if (CI->getAssociatedExpression()->getStmtClass() != SI->getAssociatedExpression()->getStmtClass()) break; // Are we dealing with different variables/fields? if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration()) break; } // Check if the extra components of the expressions in the enclosing // data environment are redundant for the current base declaration. // If they are, the maps completely overlap, which is legal. for (; SI != SE; ++SI) { QualType Type; if (auto *ASE = dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) { Type = ASE->getBase()->IgnoreParenImpCasts()->getType(); } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>( SI->getAssociatedExpression())) { auto *E = OASE->getBase()->IgnoreParenImpCasts(); Type = OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType(); } if (Type.isNull() || Type->isAnyPointerType() || CheckArrayExpressionDoesNotReferToWholeSize( SemaRef, SI->getAssociatedExpression(), Type)) break; } // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4] // List items of map clauses in the same construct must not share // original storage. // // If the expressions are exactly the same or one is a subset of the // other, it means they are sharing storage. if (CI == CE && SI == SE) { if (CurrentRegionOnly) { if (CKind == OMPC_map) SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange; else { assert(CKind == OMPC_to || CKind == OMPC_from); SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update) << ERange; } SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) << RE->getSourceRange(); return true; } else { // If we find the same expression in the enclosing data environment, // that is legal. IsEnclosedByDataEnvironmentExpr = true; return false; } } QualType DerivedType = std::prev(CI)->getAssociatedDeclaration()->getType(); SourceLocation DerivedLoc = std::prev(CI)->getAssociatedExpression()->getExprLoc(); // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] // If the type of a list item is a reference to a type T then the type // will be considered to be T for all purposes of this clause. DerivedType = DerivedType.getNonReferenceType(); // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1] // A variable for which the type is pointer and an array section // derived from that variable must not appear as list items of map // clauses of the same construct. // // Also, cover one of the cases in: // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5] // If any part of the original storage of a list item has corresponding // storage in the device data environment, all of the original storage // must have corresponding storage in the device data environment. // if (DerivedType->isAnyPointerType()) { if (CI == CE || SI == SE) { SemaRef.Diag( DerivedLoc, diag::err_omp_pointer_mapped_along_with_derived_section) << DerivedLoc; } else { assert(CI != CE && SI != SE); SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced) << DerivedLoc; } SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) << RE->getSourceRange(); return true; } // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4] // List items of map clauses in the same construct must not share // original storage. // // An expression is a subset of the other. if (CurrentRegionOnly && (CI == CE || SI == SE)) { if (CKind == OMPC_map) SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange; else { assert(CKind == OMPC_to || CKind == OMPC_from); SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update) << ERange; } SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) << RE->getSourceRange(); return true; } // The current expression uses the same base as other expression in the // data environment but does not contain it completely. if (!CurrentRegionOnly && SI != SE) EnclosingExpr = RE; // The current expression is a subset of the expression in the data // environment. IsEnclosedByDataEnvironmentExpr |= (!CurrentRegionOnly && CI != CE && SI == SE); return false; }); if (CurrentRegionOnly) return FoundError; // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5] // If any part of the original storage of a list item has corresponding // storage in the device data environment, all of the original storage must // have corresponding storage in the device data environment. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6] // If a list item is an element of a structure, and a different element of // the structure has a corresponding list item in the device data environment // prior to a task encountering the construct associated with the map clause, // then the list item must also have a corresponding list item in the device // data environment prior to the task encountering the construct. // if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) { SemaRef.Diag(ELoc, diag::err_omp_original_storage_is_shared_and_does_not_contain) << ERange; SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here) << EnclosingExpr->getSourceRange(); return true; } return FoundError; } namespace { // Utility struct that gathers all the related lists associated with a mappable // expression. struct MappableVarListInfo final { // The list of expressions. ArrayRef<Expr *> VarList; // The list of processed expressions. SmallVector<Expr *, 16> ProcessedVarList; // The mappble components for each expression. OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents; // The base declaration of the variable. SmallVector<ValueDecl *, 16> VarBaseDeclarations; MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) { // We have a list of components and base declarations for each entry in the // variable list. VarComponents.reserve(VarList.size()); VarBaseDeclarations.reserve(VarList.size()); } }; } // Check the validity of the provided variable list for the provided clause kind // \a CKind. In the check process the valid expressions, and mappable expression // components and variables are extracted and used to fill \a Vars, // \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and // \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'. static void checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind, MappableVarListInfo &MVLI, SourceLocation StartLoc, OpenMPMapClauseKind MapType = OMPC_MAP_unknown, bool IsMapTypeImplicit = false) { // We only expect mappable expressions in 'to', 'from', and 'map' clauses. assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) && "Unexpected clause kind with mappable expressions!"); // Keep track of the mappable components and base declarations in this clause. // Each entry in the list is going to have a list of components associated. We // record each set of the components so that we can build the clause later on. // In the end we should have the same amount of declarations and component // lists. for (auto &RE : MVLI.VarList) { assert(RE && "Null expr in omp to/from/map clause"); SourceLocation ELoc = RE->getExprLoc(); auto *VE = RE->IgnoreParenLValueCasts(); if (VE->isValueDependent() || VE->isTypeDependent() || VE->isInstantiationDependent() || VE->containsUnexpandedParameterPack()) { // We can only analyze this information once the missing information is // resolved. MVLI.ProcessedVarList.push_back(RE); continue; } auto *SimpleExpr = RE->IgnoreParenCasts(); if (!RE->IgnoreParenImpCasts()->isLValue()) { SemaRef.Diag(ELoc, diag::err_omp_expected_named_var_member_or_array_expression) << RE->getSourceRange(); continue; } OMPClauseMappableExprCommon::MappableExprComponentList CurComponents; ValueDecl *CurDeclaration = nullptr; // Obtain the array or member expression bases if required. Also, fill the // components array with all the components identified in the process. auto *BE = CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind); if (!BE) continue; assert(!CurComponents.empty() && "Invalid mappable expression information."); // For the following checks, we rely on the base declaration which is // expected to be associated with the last component. The declaration is // expected to be a variable or a field (if 'this' is being mapped). CurDeclaration = CurComponents.back().getAssociatedDeclaration(); assert(CurDeclaration && "Null decl on map clause."); assert( CurDeclaration->isCanonicalDecl() && "Expecting components to have associated only canonical declarations."); auto *VD = dyn_cast<VarDecl>(CurDeclaration); auto *FD = dyn_cast<FieldDecl>(CurDeclaration); assert((VD || FD) && "Only variables or fields are expected here!"); (void)FD; // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10] // threadprivate variables cannot appear in a map clause. // OpenMP 4.5 [2.10.5, target update Construct] // threadprivate variables cannot appear in a from clause. if (VD && DSAS->isThreadPrivate(VD)) { auto DVar = DSAS->getTopDSA(VD, false); SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause) << getOpenMPClauseName(CKind); ReportOriginalDSA(SemaRef, DSAS, VD, DVar); continue; } // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9] // A list item cannot appear in both a map clause and a data-sharing // attribute clause on the same construct. // Check conflicts with other map clause expressions. We check the conflicts // with the current construct separately from the enclosing data // environment, because the restrictions are different. We only have to // check conflicts across regions for the map clauses. if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr, /*CurrentRegionOnly=*/true, CurComponents, CKind)) break; if (CKind == OMPC_map && CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr, /*CurrentRegionOnly=*/false, CurComponents, CKind)) break; // OpenMP 4.5 [2.10.5, target update Construct] // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] // If the type of a list item is a reference to a type T then the type will // be considered to be T for all purposes of this clause. QualType Type = CurDeclaration->getType().getNonReferenceType(); // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4] // A list item in a to or from clause must have a mappable type. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9] // A list item must have a mappable type. if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef, DSAS, Type)) continue; if (CKind == OMPC_map) { // target enter data // OpenMP [2.10.2, Restrictions, p. 99] // A map-type must be specified in all map clauses and must be either // to or alloc. OpenMPDirectiveKind DKind = DSAS->getCurrentDirective(); if (DKind == OMPD_target_enter_data && !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) { SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) << (IsMapTypeImplicit ? 1 : 0) << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) << getOpenMPDirectiveName(DKind); continue; } // target exit_data // OpenMP [2.10.3, Restrictions, p. 102] // A map-type must be specified in all map clauses and must be either // from, release, or delete. if (DKind == OMPD_target_exit_data && !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release || MapType == OMPC_MAP_delete)) { SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) << (IsMapTypeImplicit ? 1 : 0) << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) << getOpenMPDirectiveName(DKind); continue; } // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] // A list item cannot appear in both a map clause and a data-sharing // attribute clause on the same construct if ((DKind == OMPD_target || DKind == OMPD_target_teams || DKind == OMPD_target_teams_distribute || DKind == OMPD_target_teams_distribute_parallel_for || DKind == OMPD_target_teams_distribute_parallel_for_simd || DKind == OMPD_target_teams_distribute_simd) && VD) { auto DVar = DSAS->getTopDSA(VD, false); if (isOpenMPPrivate(DVar.CKind)) { SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) << getOpenMPClauseName(DVar.CKind) << getOpenMPClauseName(OMPC_map) << getOpenMPDirectiveName(DSAS->getCurrentDirective()); ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar); continue; } } } // Save the current expression. MVLI.ProcessedVarList.push_back(RE); // Store the components in the stack so that they can be used to check // against other clauses later on. DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents, /*WhereFoundClauseKind=*/OMPC_map); // Save the components and declaration to create the clause. For purposes of // the clause creation, any component list that has has base 'this' uses // null as base declaration. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); MVLI.VarComponents.back().append(CurComponents.begin(), CurComponents.end()); MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr : CurDeclaration); } } OMPClause * Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier, OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { MappableVarListInfo MVLI(VarList); checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc, MapType, IsMapTypeImplicit); // We need to produce a map clause even if we don't have variables so that // other diagnostics related with non-existing map clauses are accurate. return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, MVLI.VarComponents, MapTypeModifier, MapType, IsMapTypeImplicit, MapLoc); } QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc, TypeResult ParsedType) { assert(ParsedType.isUsable()); QualType ReductionType = GetTypeFromParser(ParsedType.get()); if (ReductionType.isNull()) return QualType(); // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++ // A type name in a declare reduction directive cannot be a function type, an // array type, a reference type, or a type qualified with const, volatile or // restrict. if (ReductionType.hasQualifiers()) { Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0; return QualType(); } if (ReductionType->isFunctionType()) { Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1; return QualType(); } if (ReductionType->isReferenceType()) { Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2; return QualType(); } if (ReductionType->isArrayType()) { Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3; return QualType(); } return ReductionType; } Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart( Scope *S, DeclContext *DC, DeclarationName Name, ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes, AccessSpecifier AS, Decl *PrevDeclInScope) { SmallVector<Decl *, 8> Decls; Decls.reserve(ReductionTypes.size()); LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName, ForRedeclaration); // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions // A reduction-identifier may not be re-declared in the current scope for the // same type or for a type that is compatible according to the base language // rules. llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes; OMPDeclareReductionDecl *PrevDRD = nullptr; bool InCompoundScope = true; if (S != nullptr) { // Find previous declaration with the same name not referenced in other // declarations. FunctionScopeInfo *ParentFn = getEnclosingFunction(); InCompoundScope = (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty(); LookupName(Lookup, S); FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false, /*AllowInlineNamespace=*/false); llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious; auto Filter = Lookup.makeFilter(); while (Filter.hasNext()) { auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next()); if (InCompoundScope) { auto I = UsedAsPrevious.find(PrevDecl); if (I == UsedAsPrevious.end()) UsedAsPrevious[PrevDecl] = false; if (auto *D = PrevDecl->getPrevDeclInScope()) UsedAsPrevious[D] = true; } PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] = PrevDecl->getLocation(); } Filter.done(); if (InCompoundScope) { for (auto &PrevData : UsedAsPrevious) { if (!PrevData.second) { PrevDRD = PrevData.first; break; } } } } else if (PrevDeclInScope != nullptr) { auto *PrevDRDInScope = PrevDRD = cast<OMPDeclareReductionDecl>(PrevDeclInScope); do { PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] = PrevDRDInScope->getLocation(); PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope(); } while (PrevDRDInScope != nullptr); } for (auto &TyData : ReductionTypes) { auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType()); bool Invalid = false; if (I != PreviousRedeclTypes.end()) { Diag(TyData.second, diag::err_omp_declare_reduction_redefinition) << TyData.first; Diag(I->second, diag::note_previous_definition); Invalid = true; } PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second; auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second, Name, TyData.first, PrevDRD); DC->addDecl(DRD); DRD->setAccess(AS); Decls.push_back(DRD); if (Invalid) DRD->setInvalidDecl(); else PrevDRD = DRD; } return DeclGroupPtrTy::make( DeclGroupRef::Create(Context, Decls.begin(), Decls.size())); } void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) { auto *DRD = cast<OMPDeclareReductionDecl>(D); // Enter new function scope. PushFunctionScope(); getCurFunction()->setHasBranchProtectedScope(); getCurFunction()->setHasOMPDeclareReductionCombiner(); if (S != nullptr) PushDeclContext(S, DRD); else CurContext = DRD; PushExpressionEvaluationContext( ExpressionEvaluationContext::PotentiallyEvaluated); QualType ReductionType = DRD->getType(); // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will // be replaced by '*omp_parm' during codegen. This required because 'omp_in' // uses semantics of argument handles by value, but it should be passed by // reference. C lang does not support references, so pass all parameters as // pointers. // Create 'T omp_in;' variable. auto *OmpInParm = buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in"); // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will // be replaced by '*omp_parm' during codegen. This required because 'omp_out' // uses semantics of argument handles by value, but it should be passed by // reference. C lang does not support references, so pass all parameters as // pointers. // Create 'T omp_out;' variable. auto *OmpOutParm = buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out"); if (S != nullptr) { PushOnScopeChains(OmpInParm, S); PushOnScopeChains(OmpOutParm, S); } else { DRD->addDecl(OmpInParm); DRD->addDecl(OmpOutParm); } } void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) { auto *DRD = cast<OMPDeclareReductionDecl>(D); DiscardCleanupsInEvaluationContext(); PopExpressionEvaluationContext(); PopDeclContext(); PopFunctionScopeInfo(); if (Combiner != nullptr) DRD->setCombiner(Combiner); else DRD->setInvalidDecl(); } VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) { auto *DRD = cast<OMPDeclareReductionDecl>(D); // Enter new function scope. PushFunctionScope(); getCurFunction()->setHasBranchProtectedScope(); if (S != nullptr) PushDeclContext(S, DRD); else CurContext = DRD; PushExpressionEvaluationContext( ExpressionEvaluationContext::PotentiallyEvaluated); QualType ReductionType = DRD->getType(); // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will // be replaced by '*omp_parm' during codegen. This required because 'omp_priv' // uses semantics of argument handles by value, but it should be passed by // reference. C lang does not support references, so pass all parameters as // pointers. // Create 'T omp_priv;' variable. auto *OmpPrivParm = buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv"); // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will // be replaced by '*omp_parm' during codegen. This required because 'omp_orig' // uses semantics of argument handles by value, but it should be passed by // reference. C lang does not support references, so pass all parameters as // pointers. // Create 'T omp_orig;' variable. auto *OmpOrigParm = buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig"); if (S != nullptr) { PushOnScopeChains(OmpPrivParm, S); PushOnScopeChains(OmpOrigParm, S); } else { DRD->addDecl(OmpPrivParm); DRD->addDecl(OmpOrigParm); } return OmpPrivParm; } void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer, VarDecl *OmpPrivParm) { auto *DRD = cast<OMPDeclareReductionDecl>(D); DiscardCleanupsInEvaluationContext(); PopExpressionEvaluationContext(); PopDeclContext(); PopFunctionScopeInfo(); if (Initializer != nullptr) { DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit); } else if (OmpPrivParm->hasInit()) { DRD->setInitializer(OmpPrivParm->getInit(), OmpPrivParm->isDirectInit() ? OMPDeclareReductionDecl::DirectInit : OMPDeclareReductionDecl::CopyInit); } else { DRD->setInvalidDecl(); } } Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd( Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) { for (auto *D : DeclReductions.get()) { if (IsValid) { auto *DRD = cast<OMPDeclareReductionDecl>(D); if (S != nullptr) PushOnScopeChains(DRD, S, /*AddToContext=*/false); } else D->setInvalidDecl(); } return DeclReductions; } OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { Expr *ValExpr = NumTeams; Stmt *HelperValStmt = nullptr; OpenMPDirectiveKind CaptureRegion = OMPD_unknown; // OpenMP [teams Constrcut, Restrictions] // The num_teams expression must evaluate to a positive integer value. if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams, /*StrictlyPositive=*/true)) return nullptr; OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams); if (CaptureRegion != OMPD_unknown) { llvm::MapVector<Expr *, DeclRefExpr *> Captures; ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); HelperValStmt = buildPreInits(Context, Captures); } return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc); } OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { Expr *ValExpr = ThreadLimit; Stmt *HelperValStmt = nullptr; OpenMPDirectiveKind CaptureRegion = OMPD_unknown; // OpenMP [teams Constrcut, Restrictions] // The thread_limit expression must evaluate to a positive integer value. if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit, /*StrictlyPositive=*/true)) return nullptr; OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit); if (CaptureRegion != OMPD_unknown) { llvm::MapVector<Expr *, DeclRefExpr *> Captures; ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); HelperValStmt = buildPreInits(Context, Captures); } return new (Context) OMPThreadLimitClause( ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc); } OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { Expr *ValExpr = Priority; // OpenMP [2.9.1, task Constrcut] // The priority-value is a non-negative numerical scalar expression. if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority, /*StrictlyPositive=*/false)) return nullptr; return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc); } OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { Expr *ValExpr = Grainsize; // OpenMP [2.9.2, taskloop Constrcut] // The parameter of the grainsize clause must be a positive integer // expression. if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize, /*StrictlyPositive=*/true)) return nullptr; return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc); } OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { Expr *ValExpr = NumTasks; // OpenMP [2.9.2, taskloop Constrcut] // The parameter of the num_tasks clause must be a positive integer // expression. if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks, /*StrictlyPositive=*/true)) return nullptr; return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc); } OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { // OpenMP [2.13.2, critical construct, Description] // ... where hint-expression is an integer constant expression that evaluates // to a valid lock hint. ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint); if (HintExpr.isInvalid()) return nullptr; return new (Context) OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc); } OMPClause *Sema::ActOnOpenMPDistScheduleClause( OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) { if (Kind == OMPC_DIST_SCHEDULE_unknown) { std::string Values; Values += "'"; Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0); Values += "'"; Diag(KindLoc, diag::err_omp_unexpected_clause_value) << Values << getOpenMPClauseName(OMPC_dist_schedule); return nullptr; } Expr *ValExpr = ChunkSize; Stmt *HelperValStmt = nullptr; if (ChunkSize) { if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && !ChunkSize->isInstantiationDependent() && !ChunkSize->containsUnexpandedParameterPack()) { SourceLocation ChunkSizeLoc = ChunkSize->getLocStart(); ExprResult Val = PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); if (Val.isInvalid()) return nullptr; ValExpr = Val.get(); // OpenMP [2.7.1, Restrictions] // chunk_size must be a loop invariant integer expression with a positive // value. llvm::APSInt Result; if (ValExpr->isIntegerConstantExpr(Result, Context)) { if (Result.isSigned() && !Result.isStrictlyPositive()) { Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) << "dist_schedule" << ChunkSize->getSourceRange(); return nullptr; } } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) && !CurContext->isDependentContext()) { llvm::MapVector<Expr *, DeclRefExpr *> Captures; ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); HelperValStmt = buildPreInits(Context, Captures); } } } return new (Context) OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind, ValExpr, HelperValStmt); } OMPClause *Sema::ActOnOpenMPDefaultmapClause( OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc, SourceLocation KindLoc, SourceLocation EndLoc) { // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)' if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) { std::string Value; SourceLocation Loc; Value += "'"; if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) { Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap, OMPC_DEFAULTMAP_MODIFIER_tofrom); Loc = MLoc; } else { Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap, OMPC_DEFAULTMAP_scalar); Loc = KindLoc; } Value += "'"; Diag(Loc, diag::err_omp_unexpected_clause_value) << Value << getOpenMPClauseName(OMPC_defaultmap); return nullptr; } return new (Context) OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M); } bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) { DeclContext *CurLexicalContext = getCurLexicalContext(); if (!CurLexicalContext->isFileContext() && !CurLexicalContext->isExternCContext() && !CurLexicalContext->isExternCXXContext() && !isa<CXXRecordDecl>(CurLexicalContext) && !isa<ClassTemplateDecl>(CurLexicalContext) && !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) && !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) { Diag(Loc, diag::err_omp_region_not_file_context); return false; } if (IsInOpenMPDeclareTargetContext) { Diag(Loc, diag::err_omp_enclosed_declare_target); return false; } IsInOpenMPDeclareTargetContext = true; return true; } void Sema::ActOnFinishOpenMPDeclareTargetDirective() { assert(IsInOpenMPDeclareTargetContext && "Unexpected ActOnFinishOpenMPDeclareTargetDirective"); IsInOpenMPDeclareTargetContext = false; } void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec, const DeclarationNameInfo &Id, OMPDeclareTargetDeclAttr::MapTypeTy MT, NamedDeclSetType &SameDirectiveDecls) { LookupResult Lookup(*this, Id, LookupOrdinaryName); LookupParsedName(Lookup, CurScope, &ScopeSpec, true); if (Lookup.isAmbiguous()) return; Lookup.suppressDiagnostics(); if (!Lookup.isSingleResult()) { if (TypoCorrection Corrected = CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, llvm::make_unique<VarOrFuncDeclFilterCCC>(*this), CTK_ErrorRecovery)) { diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest) << Id.getName()); checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl()); return; } Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName(); return; } NamedDecl *ND = Lookup.getAsSingle<NamedDecl>(); if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) { if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl()))) Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName(); if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) { Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT); ND->addAttr(A); if (ASTMutationListener *ML = Context.getASTMutationListener()) ML->DeclarationMarkedOpenMPDeclareTarget(ND, A); checkDeclIsAllowedInOpenMPTarget(nullptr, ND); } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) { Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link) << Id.getName(); } } else Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName(); } static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR, Sema &SemaRef, Decl *D) { if (!D) return; Decl *LD = nullptr; if (isa<TagDecl>(D)) { LD = cast<TagDecl>(D)->getDefinition(); } else if (isa<VarDecl>(D)) { LD = cast<VarDecl>(D)->getDefinition(); // If this is an implicit variable that is legal and we do not need to do // anything. if (cast<VarDecl>(D)->isImplicit()) { Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To); D->addAttr(A); if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener()) ML->DeclarationMarkedOpenMPDeclareTarget(D, A); return; } } else if (isa<FunctionDecl>(D)) { const FunctionDecl *FD = nullptr; if (cast<FunctionDecl>(D)->hasBody(FD)) LD = const_cast<FunctionDecl *>(FD); // If the definition is associated with the current declaration in the // target region (it can be e.g. a lambda) that is legal and we do not need // to do anything else. if (LD == D) { Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To); D->addAttr(A); if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener()) ML->DeclarationMarkedOpenMPDeclareTarget(D, A); return; } } if (!LD) LD = D; if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() && (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) { // Outlined declaration is not declared target. if (LD->isOutOfLine()) { SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context); SemaRef.Diag(SL, diag::note_used_here) << SR; } else { DeclContext *DC = LD->getDeclContext(); while (DC) { if (isa<FunctionDecl>(DC) && cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>()) break; DC = DC->getParent(); } if (DC) return; // Is not declared in target context. SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context); SemaRef.Diag(SL, diag::note_used_here) << SR; } // Mark decl as declared target to prevent further diagnostic. Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To); D->addAttr(A); if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener()) ML->DeclarationMarkedOpenMPDeclareTarget(D, A); } } static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR, Sema &SemaRef, DSAStackTy *Stack, ValueDecl *VD) { if (VD->hasAttr<OMPDeclareTargetDeclAttr>()) return true; if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType())) return false; return true; } void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) { if (!D || D->isInvalidDecl()) return; SourceRange SR = E ? E->getSourceRange() : D->getSourceRange(); SourceLocation SL = E ? E->getLocStart() : D->getLocation(); // 2.10.6: threadprivate variable cannot appear in a declare target directive. if (VarDecl *VD = dyn_cast<VarDecl>(D)) { if (DSAStack->isThreadPrivate(VD)) { Diag(SL, diag::err_omp_threadprivate_in_target); ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false)); return; } } if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) { // Problem if any with var declared with incomplete type will be reported // as normal, so no need to check it here. if ((E || !VD->getType()->isIncompleteType()) && !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) { // Mark decl as declared target to prevent further diagnostic. if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) { Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( Context, OMPDeclareTargetDeclAttr::MT_To); VD->addAttr(A); if (ASTMutationListener *ML = Context.getASTMutationListener()) ML->DeclarationMarkedOpenMPDeclareTarget(VD, A); } return; } } if (!E) { // Checking declaration inside declare target region. if (!D->hasAttr<OMPDeclareTargetDeclAttr>() && (isa<VarDecl>(D) || isa<FunctionDecl>(D))) { Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( Context, OMPDeclareTargetDeclAttr::MT_To); D->addAttr(A); if (ASTMutationListener *ML = Context.getASTMutationListener()) ML->DeclarationMarkedOpenMPDeclareTarget(D, A); } return; } checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D); } OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { MappableVarListInfo MVLI(VarList); checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc); if (MVLI.ProcessedVarList.empty()) return nullptr; return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, MVLI.VarComponents); } OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { MappableVarListInfo MVLI(VarList); checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc); if (MVLI.ProcessedVarList.empty()) return nullptr; return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, MVLI.VarComponents); } OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { MappableVarListInfo MVLI(VarList); SmallVector<Expr *, 8> PrivateCopies; SmallVector<Expr *, 8> Inits; for (auto &RefExpr : VarList) { assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause."); SourceLocation ELoc; SourceRange ERange; Expr *SimpleRefExpr = RefExpr; auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); if (Res.second) { // It will be analyzed later. MVLI.ProcessedVarList.push_back(RefExpr); PrivateCopies.push_back(nullptr); Inits.push_back(nullptr); } ValueDecl *D = Res.first; if (!D) continue; QualType Type = D->getType(); Type = Type.getNonReferenceType().getUnqualifiedType(); auto *VD = dyn_cast<VarDecl>(D); // Item should be a pointer or reference to pointer. if (!Type->isPointerType()) { Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer) << 0 << RefExpr->getSourceRange(); continue; } // Build the private variable and the expression that refers to it. auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(), D->hasAttrs() ? &D->getAttrs() : nullptr); if (VDPrivate->isInvalidDecl()) continue; CurContext->addDecl(VDPrivate); auto VDPrivateRefExpr = buildDeclRefExpr( *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc); // Add temporary variable to initialize the private copy of the pointer. auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp"); auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(), RefExpr->getExprLoc()); AddInitializerToDecl(VDPrivate, DefaultLvalueConversion(VDInitRefExpr).get(), /*DirectInit=*/false); // If required, build a capture to implement the privatization initialized // with the current list item value. DeclRefExpr *Ref = nullptr; if (!VD) Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref); PrivateCopies.push_back(VDPrivateRefExpr); Inits.push_back(VDInitRefExpr); // We need to add a data sharing attribute for this variable to make sure it // is correctly captured. A variable that shows up in a use_device_ptr has // similar properties of a first private variable. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); // Create a mappable component for the list item. List items in this clause // only need a component. MVLI.VarBaseDeclarations.push_back(D); MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); MVLI.VarComponents.back().push_back( OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D)); } if (MVLI.ProcessedVarList.empty()) return nullptr; return OMPUseDevicePtrClause::Create( Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList, PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents); } OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { MappableVarListInfo MVLI(VarList); for (auto &RefExpr : VarList) { assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause."); SourceLocation ELoc; SourceRange ERange; Expr *SimpleRefExpr = RefExpr; auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); if (Res.second) { // It will be analyzed later. MVLI.ProcessedVarList.push_back(RefExpr); } ValueDecl *D = Res.first; if (!D) continue; QualType Type = D->getType(); // item should be a pointer or array or reference to pointer or array if (!Type.getNonReferenceType()->isPointerType() && !Type.getNonReferenceType()->isArrayType()) { Diag(ELoc, diag::err_omp_argument_type_isdeviceptr) << 0 << RefExpr->getSourceRange(); continue; } // Check if the declaration in the clause does not show up in any data // sharing attribute. auto DVar = DSAStack->getTopDSA(D, false); if (isOpenMPPrivate(DVar.CKind)) { Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) << getOpenMPClauseName(DVar.CKind) << getOpenMPClauseName(OMPC_is_device_ptr) << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); ReportOriginalDSA(*this, DSAStack, D, DVar); continue; } Expr *ConflictExpr; if (DSAStack->checkMappableExprComponentListsForDecl( D, /*CurrentRegionOnly=*/true, [&ConflictExpr]( OMPClauseMappableExprCommon::MappableExprComponentListRef R, OpenMPClauseKind) -> bool { ConflictExpr = R.front().getAssociatedExpression(); return true; })) { Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange(); Diag(ConflictExpr->getExprLoc(), diag::note_used_here) << ConflictExpr->getSourceRange(); continue; } // Store the components in the stack so that they can be used to check // against other clauses later on. OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D); DSAStack->addMappableExpressionComponents( D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr); // Record the expression we've just processed. MVLI.ProcessedVarList.push_back(SimpleRefExpr); // Create a mappable component for the list item. List items in this clause // only need a component. We use a null declaration to signal fields in // 'this'. assert((isa<DeclRefExpr>(SimpleRefExpr) || isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) && "Unexpected device pointer expression!"); MVLI.VarBaseDeclarations.push_back( isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr); MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); MVLI.VarComponents.back().push_back(MC); } if (MVLI.ProcessedVarList.empty()) return nullptr; return OMPIsDevicePtrClause::Create( Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, MVLI.VarComponents); }
510024fe109197702fdbf45e277eb340f3c88b91
6be8bbf7b2758788daa01d4a4e906f4138b85b72
/inc/systemmanager.hpp
22a1f917e845e56aed361ae52133cf7e919973fc
[]
no_license
freahs/libtyra
00620036357ad6f5589de0abeb7be4c6953b662d
4a21dd5d52dfd92a6f6e8e6b42dd7b7b4a1c2df0
refs/heads/master
2021-07-15T12:05:33.227093
2021-03-04T07:27:26
2021-03-04T07:27:26
50,514,456
0
0
null
2018-05-23T08:18:20
2016-01-27T14:52:00
C++
UTF-8
C++
false
false
1,775
hpp
/** * Copyright 2016 Fredrik Åhs * * 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 TYRA_SYSTEMMANAGER_H #define TYRA_SYSTEMMANAGER_H #include "manager.hpp" #include "typeid.hpp" #include <memory> #include <vector> namespace tyra { class System; class World; class SystemManager : public Manager { private: std::vector<std::unique_ptr<System>> m_systems; void add(TypeId, std::unique_ptr<System>); System& get(TypeId); public: template<typename T, typename... Args> void add(Args&&... args); template<typename T> T& get(); std::vector<std::unique_ptr<System>>& all(); }; template<typename T, typename... Args> void SystemManager::add(Args&&... args) { static_assert(std::is_base_of<System, T>::value, "SystemManager::addSystem: T must be derived from System."); TypeId tid = type_id<System, T>::value; add(tid, std::make_unique<T>(std::forward<Args>(args)...)); } template<typename T> T& SystemManager::get() { static_assert(std::is_base_of<System, T>::value, "SystemManager::getSystem: T must be derived from System"); return static_cast<T&>(get(type_id<System, T>::value)); } } #endif
174ee8e96bca896ca4a10d8c0a2981d76aa6d9d0
08b8cf38e1936e8cec27f84af0d3727321cec9c4
/data/crawl/squid/old_hunk_5741.cpp
08044d62a7c7d6d80833237e9a85f310da623fb7
[]
no_license
ccdxc/logSurvey
eaf28e9c2d6307140b17986d5c05106d1fd8e943
6b80226e1667c1e0760ab39160893ee19b0e9fb1
refs/heads/master
2022-01-07T21:31:55.446839
2018-04-21T14:12:43
2018-04-21T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
874
cpp
storeAppendPrintf(s, "\tnrequests: %d\n", conn->nrequests); storeAppendPrintf(s, "\tdefer: n %d, until %ld\n", conn->defer.n, (long int)conn->defer.until); } storeAppendPrintf(s, "uri %s\n", http->uri); storeAppendPrintf(s, "log_type %s\n", log_tags[http->log_type]); storeAppendPrintf(s, "out.offset %ld, out.size %lu\n", (long int)http->out.offset, (unsigned long int)http->out.size); storeAppendPrintf(s, "req_sz %d\n", http->req_sz); e = http->entry; storeAppendPrintf(s, "entry %p/%s\n", e, e ? storeKeyText(e->hash.key) : "N/A"); e = http->old_entry; storeAppendPrintf(s, "old_entry %p/%s\n", e, e ? storeKeyText(e->hash.key) : "N/A"); storeAppendPrintf(s, "start %ld.%06d (%f seconds ago)\n", (long int)http->start.tv_sec, (int)http->start.tv_usec, tvSubDsec(http->start, current_time)); storeAppendPrintf(s, "\n"); }
c41bb62707a8442bd7e43e38037a0f613f464933
3160cc30e4ca4af1726dd7412e2452c33546ad11
/chapter-4/strtype1.cpp
e7755cc0b44b100bbe3b30aab56a7c3bbad6ecbd
[]
no_license
jxliu1216/CPP-Primer-Plus
d999224fca5234a251a9186ebe0ef0e212c824e4
4184862afd14ce00c76a8b65c037525e6ffce2e9
refs/heads/master
2022-04-04T00:23:07.473819
2019-12-27T06:44:44
2019-12-27T06:44:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
596
cpp
//strtype1.cpp -- using the C++ string class #include <iostream> #include <string> int main(void) { using namespace std; char charr1[20]; char charr2[20] = "jaguar"; string str1; string str2 = "panther"; cout << "Enter a kind of feline: "; cin >> charr1; cout << "Enter another kind of feline: "; cin >> str1; cout << "Here are some felines:\n"; cout << charr1 << " " << charr2 << " " << str1 << " " << str2 << endl; cout << "The third letter in " << charr2 << " is " << charr2[2] << endl; cout << "The third letter in " << str1 << " is " << str2[2] << endl; return 0; }
464d130f3b4e9d2aa25bbee0e75b67f99ff30d23
8319097d116501d562c0d1cbaafe3fcdebebb119
/embeddeddialogs/customproxy.cpp
1f92107e706c739fe939233e46124b74be3b0bea
[]
no_license
GiantClam/jubangktv
e6d596d33b4193e2c891e1f69021142b5078f811
51dd618ce38b9628669e5973c75cf3f1344b0bbf
refs/heads/master
2020-05-20T11:09:02.341186
2012-09-16T17:19:42
2012-09-16T17:19:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,295
cpp
/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the demonstration applications of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "customproxy.h" #include <QtGui> CustomProxy::CustomProxy(QGraphicsItem *parent, Qt::WindowFlags wFlags) : QGraphicsProxyWidget(parent, wFlags), popupShown(false), currentPopup(0) { setOpacity(0.98); timeLine = new QTimeLine(250, this); connect(timeLine, SIGNAL(valueChanged(qreal)), this, SLOT(updateStep(qreal))); connect(timeLine, SIGNAL(stateChanged(QTimeLine::State)), this, SLOT(stateChanged(QTimeLine::State))); } QRectF CustomProxy::boundingRect() const { return QGraphicsProxyWidget::boundingRect().adjusted(0, 0, 10, 10); } void CustomProxy::paintWindowFrame(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { const QColor color(0, 0, 0, 64); QRectF r = windowFrameRect(); QRectF right(r.right(), r.top() + 10, 10, r.height() - 10); QRectF bottom(r.left() + 10, r.bottom(), r.width(), 10); bool intersectsRight = right.intersects(option->exposedRect); bool intersectsBottom = bottom.intersects(option->exposedRect); if (intersectsRight && intersectsBottom) { QPainterPath path; path.addRect(right); path.addRect(bottom); painter->setPen(Qt::NoPen); painter->setBrush(color); painter->drawPath(path); } else if (intersectsBottom) { painter->fillRect(bottom, color); } else if (intersectsRight) { painter->fillRect(right, color); } QGraphicsProxyWidget::paintWindowFrame(painter, option, widget); } void CustomProxy::hoverEnterEvent(QGraphicsSceneHoverEvent *event) { QGraphicsProxyWidget::hoverEnterEvent(event); scene()->setActiveWindow(this); if (timeLine->currentValue() != 1) zoomIn(); } void CustomProxy::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) { QGraphicsProxyWidget::hoverLeaveEvent(event); if (!popupShown && (timeLine->direction() != QTimeLine::Backward || timeLine->currentValue() != 0)) zoomOut(); } bool CustomProxy::sceneEventFilter(QGraphicsItem *watched, QEvent *event) { if (watched->isWindow() && (event->type() == QEvent::UngrabMouse || event->type() == QEvent::GrabMouse)) { popupShown = watched->isVisible(); if (!popupShown && !isUnderMouse()) zoomOut(); } return QGraphicsProxyWidget::sceneEventFilter(watched, event); } QVariant CustomProxy::itemChange(GraphicsItemChange change, const QVariant &value) { if (change == ItemChildAddedChange || change == ItemChildRemovedChange) { if (change == ItemChildAddedChange) { currentPopup = qVariantValue<QGraphicsItem *>(value); currentPopup->setCacheMode(ItemCoordinateCache); if (scene()) currentPopup->installSceneEventFilter(this); } else if (scene()) { currentPopup->removeSceneEventFilter(this); currentPopup = 0; } } else if (currentPopup && change == ItemSceneHasChanged) { currentPopup->installSceneEventFilter(this); } return QGraphicsProxyWidget::itemChange(change, value); } void CustomProxy::updateStep(qreal step) { #if 0 QRectF r = boundingRect(); setTransform(QTransform() .translate(r.width() / 2, r.height() / 2) .rotate(step * 30, Qt::XAxis) .rotate(step * 10, Qt::YAxis) .rotate(step * 5, Qt::ZAxis) .scale(1 + 1.5 * step, 1 + 1.5 * step) .translate(-r.width() / 2, -r.height() / 2)); #endif } void CustomProxy::stateChanged(QTimeLine::State state) { if (state == QTimeLine::Running) { if (timeLine->direction() == QTimeLine::Forward) setCacheMode(ItemCoordinateCache); } else if (state == QTimeLine::NotRunning) { if (timeLine->direction() == QTimeLine::Backward) setCacheMode(DeviceCoordinateCache); } } void CustomProxy::zoomIn() { if (timeLine->direction() != QTimeLine::Forward) timeLine->setDirection(QTimeLine::Forward); if (timeLine->state() == QTimeLine::NotRunning) timeLine->start(); } void CustomProxy::zoomOut() { if (timeLine->direction() != QTimeLine::Backward) timeLine->setDirection(QTimeLine::Backward); if (timeLine->state() == QTimeLine::NotRunning) timeLine->start(); }
ba737bf36d1a074e942fdf76ad3eb37cd2135552
0bddb4647ce0e42c126fe7748ac95eae4751d02c
/PX4-Autopilot/build/px4_sitl_default/build_gazebo/MotorSpeed.pb.h
8f2b933bedcc687f6097efce5d57890424ef78a7
[ "BSD-3-Clause" ]
permissive
cuongchutan/Custom-Robotics-Academy
ec407c83d28ec171bd29ceb71850a248432e7367
8501cc5090e67c45609bf774b8779e53e4030144
refs/heads/main
2023-03-11T09:40:51.958056
2021-03-01T10:01:34
2021-03-01T10:06:39
343,366,745
0
0
null
null
null
null
UTF-8
C++
false
true
7,951
h
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: MotorSpeed.proto #ifndef PROTOBUF_INCLUDED_MotorSpeed_2eproto #define PROTOBUF_INCLUDED_MotorSpeed_2eproto #include <string> #include <google/protobuf/stubs/common.h> #if GOOGLE_PROTOBUF_VERSION < 3006001 #error This file was generated by a newer version of protoc which is #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif #if 3006001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/arena.h> #include <google/protobuf/arenastring.h> #include <google/protobuf/generated_message_table_driven.h> #include <google/protobuf/generated_message_util.h> #include <google/protobuf/inlined_string_field.h> #include <google/protobuf/metadata.h> #include <google/protobuf/message.h> #include <google/protobuf/repeated_field.h> // IWYU pragma: export #include <google/protobuf/extension_set.h> // IWYU pragma: export #include <google/protobuf/unknown_field_set.h> // @@protoc_insertion_point(includes) #define PROTOBUF_INTERNAL_EXPORT_protobuf_MotorSpeed_2eproto namespace protobuf_MotorSpeed_2eproto { // Internal implementation detail -- do not use these members. struct TableStruct { static const ::google::protobuf::internal::ParseTableField entries[]; static const ::google::protobuf::internal::AuxillaryParseTableField aux[]; static const ::google::protobuf::internal::ParseTable schema[1]; static const ::google::protobuf::internal::FieldMetadata field_metadata[]; static const ::google::protobuf::internal::SerializationTable serialization_table[]; static const ::google::protobuf::uint32 offsets[]; }; void AddDescriptors(); } // namespace protobuf_MotorSpeed_2eproto namespace mav_msgs { namespace msgs { class MotorSpeed; class MotorSpeedDefaultTypeInternal; extern MotorSpeedDefaultTypeInternal _MotorSpeed_default_instance_; } // namespace msgs } // namespace mav_msgs namespace google { namespace protobuf { template<> ::mav_msgs::msgs::MotorSpeed* Arena::CreateMaybeMessage<::mav_msgs::msgs::MotorSpeed>(Arena*); } // namespace protobuf } // namespace google namespace mav_msgs { namespace msgs { // =================================================================== class MotorSpeed : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:mav_msgs.msgs.MotorSpeed) */ { public: MotorSpeed(); virtual ~MotorSpeed(); MotorSpeed(const MotorSpeed& from); inline MotorSpeed& operator=(const MotorSpeed& from) { CopyFrom(from); return *this; } #if LANG_CXX11 MotorSpeed(MotorSpeed&& from) noexcept : MotorSpeed() { *this = ::std::move(from); } inline MotorSpeed& operator=(MotorSpeed&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } #endif inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields(); } inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields(); } static const ::google::protobuf::Descriptor* descriptor(); static const MotorSpeed& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY static inline const MotorSpeed* internal_default_instance() { return reinterpret_cast<const MotorSpeed*>( &_MotorSpeed_default_instance_); } static constexpr int kIndexInFileMessages = 0; void Swap(MotorSpeed* other); friend void swap(MotorSpeed& a, MotorSpeed& b) { a.Swap(&b); } // implements Message ---------------------------------------------- inline MotorSpeed* New() const final { return CreateMaybeMessage<MotorSpeed>(NULL); } MotorSpeed* New(::google::protobuf::Arena* arena) const final { return CreateMaybeMessage<MotorSpeed>(arena); } void CopyFrom(const ::google::protobuf::Message& from) final; void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const MotorSpeed& from); void MergeFrom(const MotorSpeed& from); void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(MotorSpeed* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { return NULL; } inline void* MaybeArenaPtr() const { return NULL; } public: ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // repeated float motor_speed = 1 [packed = true]; int motor_speed_size() const; void clear_motor_speed(); static const int kMotorSpeedFieldNumber = 1; float motor_speed(int index) const; void set_motor_speed(int index, float value); void add_motor_speed(float value); const ::google::protobuf::RepeatedField< float >& motor_speed() const; ::google::protobuf::RepeatedField< float >* mutable_motor_speed(); // @@protoc_insertion_point(class_scope:mav_msgs.msgs.MotorSpeed) private: ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; ::google::protobuf::internal::HasBits<1> _has_bits_; mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::RepeatedField< float > motor_speed_; mutable int _motor_speed_cached_byte_size_; friend struct ::protobuf_MotorSpeed_2eproto::TableStruct; }; // =================================================================== // =================================================================== #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wstrict-aliasing" #endif // __GNUC__ // MotorSpeed // repeated float motor_speed = 1 [packed = true]; inline int MotorSpeed::motor_speed_size() const { return motor_speed_.size(); } inline void MotorSpeed::clear_motor_speed() { motor_speed_.Clear(); } inline float MotorSpeed::motor_speed(int index) const { // @@protoc_insertion_point(field_get:mav_msgs.msgs.MotorSpeed.motor_speed) return motor_speed_.Get(index); } inline void MotorSpeed::set_motor_speed(int index, float value) { motor_speed_.Set(index, value); // @@protoc_insertion_point(field_set:mav_msgs.msgs.MotorSpeed.motor_speed) } inline void MotorSpeed::add_motor_speed(float value) { motor_speed_.Add(value); // @@protoc_insertion_point(field_add:mav_msgs.msgs.MotorSpeed.motor_speed) } inline const ::google::protobuf::RepeatedField< float >& MotorSpeed::motor_speed() const { // @@protoc_insertion_point(field_list:mav_msgs.msgs.MotorSpeed.motor_speed) return motor_speed_; } inline ::google::protobuf::RepeatedField< float >* MotorSpeed::mutable_motor_speed() { // @@protoc_insertion_point(field_mutable_list:mav_msgs.msgs.MotorSpeed.motor_speed) return &motor_speed_; } #ifdef __GNUC__ #pragma GCC diagnostic pop #endif // __GNUC__ // @@protoc_insertion_point(namespace_scope) } // namespace msgs } // namespace mav_msgs // @@protoc_insertion_point(global_scope) #endif // PROTOBUF_INCLUDED_MotorSpeed_2eproto
23f95d3243df7ca4468971dca7817ce47ae54902
cfeac52f970e8901871bd02d9acb7de66b9fb6b4
/generated/src/aws-cpp-sdk-compute-optimizer/source/model/UpdateEnrollmentStatusRequest.cpp
caef5ed12c781c7edbb7d339ba1bcd5d247b1d5e
[ "Apache-2.0", "MIT", "JSON" ]
permissive
aws/aws-sdk-cpp
aff116ddf9ca2b41e45c47dba1c2b7754935c585
9a7606a6c98e13c759032c2e920c7c64a6a35264
refs/heads/main
2023-08-25T11:16:55.982089
2023-08-24T18:14:53
2023-08-24T18:14:53
35,440,404
1,681
1,133
Apache-2.0
2023-09-12T15:59:33
2015-05-11T17:57:32
null
UTF-8
C++
false
false
1,232
cpp
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/compute-optimizer/model/UpdateEnrollmentStatusRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::ComputeOptimizer::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; UpdateEnrollmentStatusRequest::UpdateEnrollmentStatusRequest() : m_status(Status::NOT_SET), m_statusHasBeenSet(false), m_includeMemberAccounts(false), m_includeMemberAccountsHasBeenSet(false) { } Aws::String UpdateEnrollmentStatusRequest::SerializePayload() const { JsonValue payload; if(m_statusHasBeenSet) { payload.WithString("status", StatusMapper::GetNameForStatus(m_status)); } if(m_includeMemberAccountsHasBeenSet) { payload.WithBool("includeMemberAccounts", m_includeMemberAccounts); } return payload.View().WriteReadable(); } Aws::Http::HeaderValueCollection UpdateEnrollmentStatusRequest::GetRequestSpecificHeaders() const { Aws::Http::HeaderValueCollection headers; headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "ComputeOptimizerService.UpdateEnrollmentStatus")); return headers; }
acb102f906a8015784ced2f3c8db3a54cde230ca
c591b56220405b715c1aaa08692023fca61f22d4
/Prachi bansal/Milestone-11/question-37.cpp
89694e62bc0d830eb22997106932497eb1c57756
[]
no_license
Girl-Code-It/Beginner-CPP-Submissions
ea99a2bcf8377beecba811d813dafc2593ea0ad9
f6c80a2e08e2fe46b2af1164189272019759935b
refs/heads/master
2022-07-24T22:37:18.878256
2021-11-16T04:43:08
2021-11-16T04:43:08
263,825,293
37
105
null
2023-06-05T09:16:10
2020-05-14T05:39:40
C++
UTF-8
C++
false
false
417
cpp
//ascending order #include<iostream> using namespace std; int main(){ int a[20],temp,n; cout<<"Enter the size: "; cin>>n; cout<<"Enter the elememts: "; for(int i=0;i<n;i++){ cin>>a[i]; } cout<<"Array in ascending order is: "; for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ if(a[i]>a[j]){ temp=a[i]; a[i]=a[j]; a[j]=temp; } } } for(int i=0;i<n;i++){ cout<<a[i]<<" "; } return 0; }
7a56f25ec20b2d476187317c07299c82b7b42bbd
5c134dd6e991661317cfc17a763af002680b1887
/smallestDistinctWindow-SlidingWindow.cpp
db946e7c0eaa2f75da7734bdf1f92bfc9a10c5c7
[]
no_license
noob-hu-yaar/CP-
b8442716862dc6171aca238f573bc2c723552d3e
e238c91638eb57af9458a0c6d916847d93bd83d1
refs/heads/master
2023-08-12T16:44:22.079749
2021-10-02T12:43:22
2021-10-02T12:43:22
272,474,320
1
3
null
2021-10-02T12:43:23
2020-06-15T15:23:23
C++
UTF-8
C++
false
false
1,140
cpp
#include<bits/stdc++.h> using namespace std; #define fast ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0); #define mod 1000000007; typedef long long int ll; int main(){ fast; int t;cin>>t; while(t--){ string s;cin>>s; set <char> st; for(ll i=0;i<s.length();i++)st.insert(s[i]); int distinct = st.size(); int ct[256]={0}; int mini=INT_MAX,cc=0,start=0,start_index=-1; for(ll i=0;i<s.length();i++){ ct[s[i]]++; //checks the distinct element count if(ct[s[i]]==1){ cc++; } //when all the distinct elements are present in the current window if(cc==distinct){ //to shift the window from the start while(ct[s[start]]>1){ if(ct[s[start]]>1) ct[s[start]]--; start++; } int len = i-start+1; //computing the value of mini window length if(len<mini){ mini = len ; start_index = start; } } } cout<<s.substr(start_index,mini)<<endl; } }
7ac4b57a60549d3bc65fe80f43cb1d34806e21e9
424d9d65e27cd204cc22e39da3a13710b163f4e7
/chrome/browser/chromeos/web_applications/connectivity_diagnostics_system_web_app_info.cc
2d0032554aa8a682750edb58b065c056688ce24a
[ "BSD-3-Clause" ]
permissive
bigben0123/chromium
7c5f4624ef2dacfaf010203b60f307d4b8e8e76d
83d9cd5e98b65686d06368f18b4835adbab76d89
refs/heads/master
2023-01-10T11:02:26.202776
2020-10-30T09:47:16
2020-10-30T09:47:16
275,543,782
0
0
BSD-3-Clause
2020-10-30T09:47:18
2020-06-28T08:45:11
null
UTF-8
C++
false
false
1,494
cc
// Copyright 2020 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 "chrome/browser/chromeos/web_applications/connectivity_diagnostics_system_web_app_info.h" #include <memory> #include "chrome/browser/chromeos/web_applications/system_web_app_install_utils.h" #include "chrome/common/web_application_info.h" #include "chromeos/components/connectivity_diagnostics/url_constants.h" #include "chromeos/grit/connectivity_diagnostics_resources.h" #include "chromeos/strings/grit/chromeos_strings.h" #include "third_party/blink/public/mojom/manifest/display_mode.mojom.h" #include "ui/base/l10n/l10n_util.h" #include "url/gurl.h" std::unique_ptr<WebApplicationInfo> CreateWebAppInfoForConnectivityDiagnosticsSystemWebApp() { std::unique_ptr<WebApplicationInfo> info = std::make_unique<WebApplicationInfo>(); info->start_url = GURL(chromeos::kChromeUIConnectivityDiagnosticsUrl); info->scope = GURL(chromeos::kChromeUIConnectivityDiagnosticsUrl); info->title = l10n_util::GetStringUTF16(IDS_CONNECTIVITY_DIAGNOSTICS_TITLE); web_app::CreateIconInfoForSystemWebApp( info->start_url, {{"app_icon_128.png", 128, IDR_CONNECTIVITY_DIAGNOSTICS_APP_ICON_128_PNG}}, *info); info->theme_color = 0xFFFFFFFF; info->background_color = 0xFFFFFFFF; info->display_mode = blink::mojom::DisplayMode::kStandalone; info->open_as_window = true; return info; }
229079062451737ab0ca6f130acde19a1fc6e828
62ad25cc8e9905ac4a3372c241afbb9de2cf4bfd
/src/meta_server/ddl_manager.cpp
c465becad4f06739114057f3accabaf84215f205
[ "Apache-2.0" ]
permissive
junxfl/BaikalDB
096e77b8985bb1a057324793d0423985e09716a7
70c7ff68fb36027339516a90de1c5368fc6ee0d3
refs/heads/master
2023-03-30T12:38:41.204797
2021-04-02T04:00:57
2021-04-02T04:00:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
44,550
cpp
// copyright (c) 2018-present baidu, inc. 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 "ddl_manager.h" #include "region_manager.h" #include "meta_rocksdb.h" #include "mut_table_key.h" #include "table_manager.h" #include "log.h" #include "meta_util.h" namespace baikaldb { DEFINE_int32(baikaldb_max_concurrent, 10, "global ddl baikaldb concurrent"); DEFINE_int32(ddl_status_update_interval_us, 10 * 1000 * 1000, "ddl_status_update_interval(us)"); DEFINE_int32(max_region_num_ratio, 2, "max region number ratio"); DEFINE_int32(max_ddl_retry_time, 30, "max ddl retry time"); DECLARE_int32(baikal_heartbeat_interval_us); std::string construct_global_ddl_key(const std::string identify, std::initializer_list<int64_t> ids) { std::string ddl_key; ddl_key = MetaServer::SCHEMA_IDENTIFY + identify; for (auto id : ids) { ddl_key.append((char*)&id, sizeof(int64_t)); } return ddl_key; } bool StatusChangePolicy::should_change(int64_t table_id, pb::IndexState status) { BAIDU_SCOPED_LOCK(_mutex); size_t index = static_cast<size_t>(status); if (_time_costs_map[table_id][index] == nullptr) { _time_costs_map[table_id][index].reset(new TimeCost); return false; } else { return _time_costs_map[table_id][index]->get_time() > 5 * FLAGS_ddl_status_update_interval_us; } } void DBManager::process_common_task_hearbeat(const std::string& address, const pb::BaikalHeartBeatRequest* request, pb::BaikalHeartBeatResponse* response) { _common_task_map.update(address, [&address, &response](CommonTaskMap& db_task_map) { auto todo_iter = db_task_map.to_do_task_map.begin(); for (; todo_iter != db_task_map.to_do_task_map.end(); ) { auto ddl_work_handle = response->add_region_ddl_works(); auto& region_ddl_info = todo_iter->second.region_info; region_ddl_info.set_status(pb::DdlWorkDoing); region_ddl_info.set_address(address); ddl_work_handle->CopyFrom(region_ddl_info); todo_iter->second.update_timestamp = butil::gettimeofday_us(); // 通过raft更新状态为 doing auto task_id = std::to_string(region_ddl_info.table_id()) + "_" + std::to_string(region_ddl_info.region_id()); DB_NOTICE("start_db task_%s work %s", task_id.c_str(), region_ddl_info.ShortDebugString().c_str()); DDLManager::get_instance()->update_region_ddlwork(region_ddl_info); db_task_map.doing_task_map.insert(*todo_iter); todo_iter = db_task_map.to_do_task_map.erase(todo_iter); } }); //处理已经完成的工作 for (const auto& region_ddl_info : request->region_ddl_works()) { // 删除 _to_launch_task_info_map内任务。 //DB_NOTICE("update ddlwork %s", region_ddl_info.ShortDebugString().c_str()); _common_task_map.update(region_ddl_info.address(), [&region_ddl_info](CommonTaskMap& db_task_map) { auto task_id = std::to_string(region_ddl_info.table_id()) + "_" + std::to_string(region_ddl_info.region_id()); if (region_ddl_info.status() == pb::DdlWorkDoing) { // 正在运行,跟新时间戳。 auto iter = db_task_map.doing_task_map.find(task_id); if (iter != db_task_map.doing_task_map.end()) { iter->second.update_timestamp = butil::gettimeofday_us(); //DB_NOTICE("task_%s update work %s", task_id.c_str(), region_ddl_info.ShortDebugString().c_str()); } } else { auto doing_iter = db_task_map.doing_task_map.find(task_id); if (doing_iter != db_task_map.doing_task_map.end()) { DB_NOTICE("task_%s work done %s", task_id.c_str(), region_ddl_info.ShortDebugString().c_str()); DDLManager::get_instance()->update_region_ddlwork(region_ddl_info); db_task_map.doing_task_map.erase(doing_iter); } } }); } } void DBManager::process_broadcast_task_hearbeat(const std::string& address, const pb::BaikalHeartBeatRequest* request, pb::BaikalHeartBeatResponse* response) { { std::vector<BroadcastTaskPtr> broadcast_task_tmp_vec; broadcast_task_tmp_vec.reserve(4); { BAIDU_SCOPED_LOCK(_broadcast_mutex); for (auto& txn_task : _broadcast_task_map) { broadcast_task_tmp_vec.emplace_back(txn_task.second); } } for (auto& txn_task_ptr : broadcast_task_tmp_vec) { bool ret = txn_task_ptr->to_do_task_map.exist(address); if (ret) { MemDdlWork work; work.update_timestamp = butil::gettimeofday_us(); txn_task_ptr->to_do_task_map.erase(address); txn_task_ptr->doing_task_map.set(address, work); auto txn_work_handle = response->add_ddl_works(); txn_work_handle->CopyFrom(txn_task_ptr->work); txn_work_handle->set_status(pb::DdlWorkDoing); } } } for (const auto& txn_ddl_info : request->ddl_works()) { auto table_id = txn_ddl_info.table_id(); BroadcastTaskPtr txn_ptr; { BAIDU_SCOPED_LOCK(_broadcast_mutex); auto iter = _broadcast_task_map.find(table_id); if (iter == _broadcast_task_map.end()) { DB_NOTICE("unknown txn task."); continue; } txn_ptr = iter->second; } DB_NOTICE("before number %ld", txn_ptr->number.load()); //iter->second.done_txn_task_map.insert(std::make_pair(address, txn_ddl_info)); //判断是否所有的db都返回。 if (txn_ddl_info.status() == pb::DdlWorkDoing) { bool ret = txn_ptr->doing_task_map.update(address, [](MemDdlWork& ddlwork){ ddlwork.update_timestamp = butil::gettimeofday_us(); DB_NOTICE("update txn work timestamp %ld", ddlwork.update_timestamp); }); if (!ret) { txn_ptr->to_do_task_map.update(address, [](MemDdlWork& ddlwork){ ddlwork.update_timestamp = butil::gettimeofday_us(); DB_NOTICE("update txn work timestamp %ld", ddlwork.update_timestamp); }); } continue; } else if (txn_ddl_info.status() == pb::DdlWorkFail) { DB_WARNING("wait txn work %s fail.", txn_ddl_info.ShortDebugString().c_str()); DDLManager::get_instance()->set_txn_ready(txn_ptr->work.table_id(), false); { BAIDU_SCOPED_LOCK(_broadcast_mutex); _broadcast_task_map.erase(table_id); } } else if (txn_ddl_info.status() == pb::DdlWorkDone) { bool ret = txn_ptr->doing_task_map.exist(address); if (ret) { txn_ptr->number--; txn_ptr->doing_task_map.erase(address); } } if (txn_ptr->number == 0) { DB_NOTICE("table_%ld txn work done.", table_id); DDLManager::get_instance()->set_txn_ready(txn_ptr->work.table_id(), true); { BAIDU_SCOPED_LOCK(_broadcast_mutex); _broadcast_task_map.erase(table_id); } } } } void DBManager::process_baikal_heartbeat(const pb::BaikalHeartBeatRequest* request, pb::BaikalHeartBeatResponse* response, brpc::Controller* cntl) { // 更新baikaldb 信息 if (!request->can_do_ddlwork()) { return; } TimeCost tc; std::string address = butil::endpoint2str(cntl->remote_side()).c_str(); auto room = request->physical_room(); update_baikaldb_info(address, room); auto update_db_info_ts = tc.get_time(); tc.reset(); process_common_task_hearbeat(address, request, response); auto common_task_ts = tc.get_time(); tc.reset(); process_broadcast_task_hearbeat(address, request, response); auto broadcast_task_ts = tc.get_time(); DB_NOTICE("process ddl baikal heartbeat update biakaldb info %ld, common task time %ld, broadcast task time %ld", update_db_info_ts, common_task_ts, broadcast_task_ts); DB_DEBUG("ddl_request : %s address %s", request->ShortDebugString().c_str(), address.c_str()); DB_DEBUG("dll_response : %s address %s", response->ShortDebugString().c_str(), address.c_str()); } bool DBManager::round_robin_select(std::string* selected_address) { BAIDU_SCOPED_LOCK(_address_instance_mutex); auto iter = _address_instance_map.find(_last_rolling_instance); if (iter == _address_instance_map.end() || (++iter) == _address_instance_map.end()) { iter = _address_instance_map.begin(); } auto instance_count = _address_instance_map.size(); for (size_t index = 0; index < instance_count; ++index) { if (iter == _address_instance_map.end()) { iter = _address_instance_map.begin(); } if (iter->second.instance_status.state == pb::FAULTY) { DB_NOTICE("address %s is faulty.", iter->first.c_str()); iter++; continue; } int32_t current_task_number = 0; auto find_task_map = _common_task_map.init_if_not_exist_else_update(iter->first, [&current_task_number](CommonTaskMap& db_task_map){ current_task_number = db_task_map.doing_task_map.size() + db_task_map.to_do_task_map.size(); }); if (!find_task_map || current_task_number < FLAGS_baikaldb_max_concurrent) { _last_rolling_instance = iter->first; *selected_address = iter->first; DB_NOTICE("select address %s", iter->first.c_str()); return true; } iter++; } return false; } bool DBManager::select_instance(std::string* selected_address) { return round_robin_select(selected_address); } int DBManager::execute_task(MemRegionDdlWork& work) { //选择address执行 auto& region_ddl_info = work.region_info; work.update_timestamp = butil::gettimeofday_us(); std::string address; if (select_instance(&address)) { auto task_id = std::to_string(region_ddl_info.table_id()) + "_" + std::to_string(region_ddl_info.region_id()); auto retry_time = region_ddl_info.retry_time(); region_ddl_info.set_retry_time(++retry_time); CommonTaskMap map; map.to_do_task_map[task_id] = work; _common_task_map.init_if_not_exist_else_update(address, [&work, &task_id](CommonTaskMap& db_task_map){ db_task_map.to_do_task_map[task_id] = work; }, map); DB_NOTICE("choose address_%s for task_%s", address.c_str(), task_id.c_str()); return 0; } else { return -1; } } std::vector<std::string> DBManager::get_faulty_baikaldb() { std::vector<std::string> ret; ret.reserve(5); BAIDU_SCOPED_LOCK(_address_instance_mutex); auto iter = _address_instance_map.begin(); for (; iter != _address_instance_map.end(); ) { if (butil::gettimeofday_us() - iter->second.instance_status.timestamp > FLAGS_baikal_heartbeat_interval_us * 20) { DB_NOTICE("db %s is faulty.", iter->first.c_str()); iter->second.instance_status.state = pb::FAULTY; ret.emplace_back(iter->first); if (butil::gettimeofday_us() - iter->second.instance_status.timestamp > FLAGS_baikal_heartbeat_interval_us * 90) { DB_NOTICE("db %s is dead, delete", iter->first.c_str()); iter = _address_instance_map.erase(iter); continue; } } iter++; } return ret; } void DBManager::init() { _bth.run([this]() { DB_NOTICE("sleep, wait collect db info."); bthread_usleep(2 * 60 * 1000 * 1000LL); while (!_shutdown) { if (!_meta_state_machine->is_leader()) { DB_NOTICE("not leader, sleep."); bthread_usleep_fast_shutdown(5 * 1000 * 1000, _shutdown); continue; } DB_NOTICE("db manager working thread."); _common_task_map.traverse([this](CommonTaskMap& db_task_map) { auto traverse_func = [](std::unordered_map<TaskId, MemRegionDdlWork>& update_map){ auto iter = update_map.begin(); for (; iter != update_map.end(); ) { if (butil::gettimeofday_us() - iter->second.update_timestamp > FLAGS_baikal_heartbeat_interval_us * 20) { auto task_id = std::to_string(iter->second.region_info.table_id()) + "_" + std::to_string(iter->second.region_info.region_id()); DB_NOTICE("task_%s restart work %s", task_id.c_str(), iter->second.region_info.ShortDebugString().c_str()); iter->second.region_info.set_status(pb::DdlWorkIdle); DDLManager::get_instance()->update_region_ddlwork(iter->second.region_info); iter = update_map.erase(iter); } else { iter++; } } }; traverse_func(db_task_map.to_do_task_map); traverse_func(db_task_map.doing_task_map); }); std::vector<BroadcastTaskPtr> broadcast_task_tmp_vec; { broadcast_task_tmp_vec.reserve(4); { BAIDU_SCOPED_LOCK(_broadcast_mutex); for (auto& txn_task : _broadcast_task_map) { broadcast_task_tmp_vec.emplace_back(txn_task.second); } } } for (auto& cast_task_ptr : broadcast_task_tmp_vec) { auto delete_heartbeat_timeout_txn_work = [&cast_task_ptr](ThreadSafeMap<std::string, MemDdlWork>& work_map){ std::vector<std::string> timeout_instance_vec; timeout_instance_vec.reserve(5); work_map.traverse_with_key_value([&cast_task_ptr, &timeout_instance_vec](std::string instance, MemDdlWork& work){ if (butil::gettimeofday_us() - work.update_timestamp > FLAGS_baikal_heartbeat_interval_us * 30) { DB_WARNING("instance %s txn work heartbeat timeout.", instance.c_str()); timeout_instance_vec.emplace_back(instance); } }); for (auto& instance : timeout_instance_vec) { cast_task_ptr->number -= work_map.erase(instance); } }; delete_heartbeat_timeout_txn_work(cast_task_ptr->doing_task_map); delete_heartbeat_timeout_txn_work(cast_task_ptr->to_do_task_map); } auto faulty_dbs = get_faulty_baikaldb(); for (const auto& faulty_db : faulty_dbs) { _common_task_map.update(faulty_db, [this](CommonTaskMap& db_task_map) { auto re_launch_task_func = [this](std::unordered_map<TaskId, MemRegionDdlWork>& task_map){ for (auto& task : task_map) { auto task_id = std::to_string(task.second.region_info.table_id()) + "_" + std::to_string(task.second.region_info.region_id()); DB_NOTICE("re_launch task_%s %s", task_id.c_str(), task.second.region_info.ShortDebugString().c_str()); task.second.region_info.set_status(pb::DdlWorkIdle); DDLManager::get_instance()->update_region_ddlwork(task.second.region_info); } task_map.clear(); }; re_launch_task_func(db_task_map.to_do_task_map); re_launch_task_func(db_task_map.doing_task_map); }); BAIDU_SCOPED_LOCK(_broadcast_mutex); for (auto& txn_work : _broadcast_task_map) { txn_work.second->number -= txn_work.second->to_do_task_map.erase(faulty_db); txn_work.second->number -= txn_work.second->doing_task_map.erase(faulty_db); } } bthread_usleep_fast_shutdown(20 * 1000 * 1000, _shutdown); } }); } int DBManager::restore_task(const pb::RegionDdlWork& region_ddl_info) { auto task_id = std::to_string(region_ddl_info.table_id()) + "_" + std::to_string(region_ddl_info.region_id()); CommonTaskMap map; MemRegionDdlWork work; work.region_info = region_ddl_info; work.update_timestamp = butil::gettimeofday_us(); map.to_do_task_map[task_id] = work; _common_task_map.init_if_not_exist_else_update(region_ddl_info.address(), [&work, &task_id](CommonTaskMap& db_task_map){ db_task_map.doing_task_map[task_id] = work; }, map); DB_NOTICE("choose address_%s for doing_task_map task_%s", region_ddl_info.address().c_str(), task_id.c_str()); return 0; } void DBManager::update_txn_ready(int64_t table_id) { auto is_ready = false; { BAIDU_SCOPED_LOCK(_broadcast_mutex); auto iter = _broadcast_task_map.find(table_id); if (iter != _broadcast_task_map.end()) { if (iter->second->number == 0) { is_ready = true; _broadcast_task_map.erase(iter); } } else { DB_WARNING("unknown txn work %ld", table_id); } } if (is_ready) { DDLManager::get_instance()->set_txn_ready(table_id, true); } } int DDLManager::init_del_global_ddlwork(int64_t table_id, int64_t index_id) { DB_NOTICE("init del global ddl tid_%ld iid_%ld", table_id, index_id); int ret = 0; BAIDU_SCOPED_LOCK(_table_mutex); if (_table_ddl_mem.count(table_id) == 1) { DB_WARNING("table_id_%ld delete global index is running..", table_id); return -1; } MemDdlInfo mem_info; mem_info.work_info.set_table_id(table_id); mem_info.work_info.set_op_type(pb::OP_DROP_INDEX); mem_info.work_info.set_index_id(index_id); mem_info.work_info.set_errcode(pb::IN_PROCESS); mem_info.work_info.set_global(true); _table_ddl_mem.emplace(table_id, mem_info); std::string global_ddl_string; if (!mem_info.work_info.SerializeToString(&global_ddl_string)) { DB_FATAL("serialzeTostring error."); return -1; } if(MetaRocksdb::get_instance()->put_meta_info( construct_global_ddl_key(MetaServer::DDLWORK_IDENTIFY, {table_id}), global_ddl_string) != 0) { DB_FATAL("put meta info error."); return -1; } return 0; } int DDLManager::init_global_ddlwork(int64_t table_id, int64_t index_id, std::unordered_map<int64_t, std::set<int64_t>>& partition_regions) { DB_NOTICE("init global ddl tid_%ld iid_%ld", table_id, index_id); int ret = 0; BAIDU_SCOPED_LOCK(_table_mutex); if (_table_ddl_mem.count(table_id) == 1) { DB_WARNING("table_id_%ld add global index is running..", table_id); return -1; } MemDdlInfo mem_info; mem_info.work_info.set_table_id(table_id); mem_info.work_info.set_op_type(pb::OP_ADD_INDEX); mem_info.work_info.set_index_id(index_id); mem_info.work_info.set_errcode(pb::IN_PROCESS); mem_info.work_info.set_global(true); _table_ddl_mem.emplace(table_id, mem_info); std::string global_ddl_string; if (!mem_info.work_info.SerializeToString(&global_ddl_string)) { DB_FATAL("serialzeTostring error."); return -1; } if(MetaRocksdb::get_instance()->put_meta_info( construct_global_ddl_key(MetaServer::DDLWORK_IDENTIFY, {table_id}), global_ddl_string) != 0) { DB_FATAL("put meta info error."); return -1; } std::vector<int64_t> region_ids; std::unordered_map<int64_t, int64_t> region_partition_map; region_ids.reserve(1000); for (const auto& partition_region : partition_regions) { for (auto& region_id : partition_region.second) { region_ids.emplace_back(region_id); region_partition_map[region_id] = partition_region.first; } } DB_NOTICE("work %s region size %zu", mem_info.work_info.ShortDebugString().c_str(), region_ids.size()); std::vector<SmartRegionInfo> region_infos; RegionManager::get_instance()->get_region_info(region_ids, region_infos); MemRegionDdlWorkMapPtr region_map_ptr; { BAIDU_SCOPED_LOCK(_region_mutex); _region_ddlwork[table_id].reset(new ThreadSafeMap<int64_t, MemRegionDdlWork>); region_map_ptr = _region_ddlwork[table_id]; } for (const auto& region_info : region_infos) { pb::RegionDdlWork region_work; region_work.set_table_id(table_id); region_work.set_region_id(region_info->region_id()); region_work.set_start_key(region_info->start_key()); region_work.set_end_key(region_info->end_key()); region_work.set_status(pb::DdlWorkIdle); region_work.set_index_id(index_id); region_work.set_partition(region_partition_map[region_info->region_id()]); std::string region_work_string; if (!region_work.SerializeToString(&region_work_string)) { DB_FATAL("serialze region work error."); return -1; } MemRegionDdlWork region_ddl_work; region_ddl_work.region_info = region_work; region_map_ptr->set(region_info->region_id(), region_ddl_work); auto task_id = std::to_string(table_id) + "_" + std::to_string(region_work.region_id()); DB_NOTICE("init region_ddlwork task_%s table%ld region_%ld region_%s", task_id.c_str(), table_id, region_info->region_id(), region_work.ShortDebugString().c_str()); if(MetaRocksdb::get_instance()->put_meta_info( construct_global_ddl_key(MetaServer::GLOBAL_DDLWORK_REGION_IDENTIFY, {table_id, region_info->region_id()}), region_work_string) != 0) { DB_FATAL("put region info error."); return -1; } } return 0; } // 定时线程处理所有ddl work。 int DDLManager::work() { DB_NOTICE("sleep, wait ddl manager init."); bthread_usleep(3 * 60 * 1000 * 1000LL); while (!_shutdown) { if (!_meta_state_machine->is_leader()) { DB_NOTICE("not leader, sleep."); bthread_usleep_fast_shutdown(5 * 1000 * 1000, _shutdown); continue; } DB_NOTICE("leader process ddl work."); std::unordered_map<int64_t, MemDdlInfo> temp_ddl_mem; { BAIDU_SCOPED_LOCK(_table_mutex); for (auto iter = _table_ddl_mem.begin(); iter != _table_ddl_mem.end(); iter++) { if (iter->second.work_info.errcode() == pb::SUCCESS || iter->second.work_info.errcode() == pb::EXEC_FAIL) { pb::MetaManagerRequest clear_request; clear_request.mutable_ddlwork_info()->CopyFrom(iter->second.work_info); clear_request.set_op_type(pb::OP_DELETE_DDLWORK); apply_raft(clear_request); if (iter->second.work_info.errcode() == pb::EXEC_FAIL && iter->second.work_info.op_type() == pb::OP_ADD_INDEX) { DB_NOTICE("ddl add index job fail, drop index %s", iter->second.work_info.ShortDebugString().c_str()); TableManager::get_instance()->drop_index_request(iter->second.work_info); } DB_NOTICE("ddl job[%s] finish.", iter->second.work_info.ShortDebugString().c_str()); } else { if (iter->second.work_info.suspend()) { DB_NOTICE("work %ld is suspend.", iter->second.work_info.table_id()); } else { temp_ddl_mem.insert(*iter); } } } } for (auto& table_ddl_info : temp_ddl_mem) { auto op_type = table_ddl_info.second.work_info.op_type(); if (op_type == pb::OP_DROP_INDEX) { drop_index_global_ddlwork(table_ddl_info.second.work_info); } else if (op_type == pb::OP_ADD_INDEX) { add_index_global_ddlwork(table_ddl_info.second.work_info); } else { DB_FATAL("unknown optype."); } } bthread_usleep_fast_shutdown(20 * 1000 * 1000, _shutdown); } return 0; } int DDLManager::load_table_ddl_snapshot(const pb::DdlWorkInfo& global_ddl_work) { BAIDU_SCOPED_LOCK(_table_mutex); DB_NOTICE("load table ddl snapshot %s.", global_ddl_work.ShortDebugString().c_str()); MemDdlInfo mem_info; mem_info.work_info = global_ddl_work; _table_ddl_mem.emplace(global_ddl_work.table_id(), mem_info); return 0; } int DDLManager::load_region_ddl_snapshot(const std::string& region_ddl_info) { pb::RegionDdlWork region_work; if (!region_work.ParseFromString(region_ddl_info)) { DB_FATAL("parse from string error."); return 0; } MemRegionDdlWork region_ddl_work; region_ddl_work.region_info = region_work; auto task_id = std::to_string(region_ddl_work.region_info.table_id()) + "_" + std::to_string(region_ddl_work.region_info.region_id()); DB_NOTICE("load region ddl task_%s snapshot %s", task_id.c_str(), region_ddl_work.region_info.ShortDebugString().c_str()); auto table_id = region_work.table_id(); BAIDU_SCOPED_LOCK(_region_mutex); if (_region_ddlwork[table_id] == nullptr) { _region_ddlwork[table_id].reset(new ThreadSafeMap<int64_t, MemRegionDdlWork>); } _region_ddlwork[table_id]->set(region_work.region_id(), region_ddl_work); return 0; } void DDLManager::on_leader_start() { std::vector<MemRegionDdlWorkMapPtr> region_work_ptrs; region_work_ptrs.reserve(5); { BAIDU_SCOPED_LOCK(_region_mutex); for (auto& region_map_pair : _region_ddlwork) { region_work_ptrs.emplace_back(region_map_pair.second); } } for (auto& region_work_ptr : region_work_ptrs) { DB_NOTICE("leader start reload ddl work."); region_work_ptr->traverse([this](MemRegionDdlWork& work) { auto& region_work = work.region_info; if (region_work.status() == pb::DdlWorkDoing) { DB_NOTICE("restore ddl work %s.", region_work.ShortDebugString().c_str()); increase_doing_work_number(region_work.table_id()); DBManager::get_instance()->restore_task(region_work); } }); } } int DDLManager::launch_work() { _work_thread.run([this]() { this->work(); }); return 0; } int DDLManager::drop_index_global_ddlwork(pb::DdlWorkInfo& g_ddl_work) { int64_t table_id = g_ddl_work.table_id(); size_t region_size = TableManager::get_instance()->get_region_size(g_ddl_work.index_id()); DB_NOTICE("global index region size %zu", region_size); DB_NOTICE("process drop global index ddlwork tid_%ld", table_id); pb::IndexState current_state; if (TableManager::get_instance()->get_index_state(g_ddl_work.table_id(), g_ddl_work.index_id(), current_state) != 0) { DB_WARNING("ddl index not ready. table_id[%ld] index_id[%ld]", g_ddl_work.table_id(), g_ddl_work.index_id()); return -1; } if (g_ddl_work.errcode() == pb::EXEC_FAIL) { DB_FATAL("drop index failed"); return 0; } switch (current_state) { case pb::IS_NONE: if (_update_policy.should_change(table_id, current_state)) { g_ddl_work.set_deleted(true); g_ddl_work.set_errcode(pb::SUCCESS); TableManager::get_instance()->update_index_status(g_ddl_work); pb::MetaManagerRequest clear_request; clear_request.mutable_ddlwork_info()->CopyFrom(g_ddl_work); clear_request.set_op_type(pb::OP_DELETE_DDLWORK); apply_raft(clear_request); pb::MetaManagerRequest request; request.mutable_ddlwork_info()->CopyFrom(g_ddl_work); request.set_op_type(pb::OP_REMOVE_GLOBAL_INDEX_DATA); apply_raft(request); _update_policy.clear(table_id); update_table_ddl_mem(g_ddl_work); } break; case pb::IS_DELETE_ONLY: if (_update_policy.should_change(table_id, current_state)) { g_ddl_work.set_job_state(pb::IS_NONE); TableManager::get_instance()->update_index_status(g_ddl_work); update_table_ddl_mem(g_ddl_work); } break; case pb::IS_WRITE_ONLY: if (_update_policy.should_change(table_id, current_state)) { g_ddl_work.set_job_state(pb::IS_DELETE_ONLY); TableManager::get_instance()->update_index_status(g_ddl_work); update_table_ddl_mem(g_ddl_work); } break; case pb::IS_WRITE_LOCAL: if (_update_policy.should_change(table_id, current_state)) { g_ddl_work.set_job_state(pb::IS_WRITE_ONLY); TableManager::get_instance()->update_index_status(g_ddl_work); update_table_ddl_mem(g_ddl_work); } break; case pb::IS_PUBLIC: if (_update_policy.should_change(table_id, current_state)) { g_ddl_work.set_job_state(pb::IS_WRITE_ONLY); TableManager::get_instance()->update_index_status(g_ddl_work); update_table_ddl_mem(g_ddl_work); } break; default: break; } return 0; } //处理单个ddl work int DDLManager::add_index_global_ddlwork(pb::DdlWorkInfo& g_ddl_work) { int64_t table_id = g_ddl_work.table_id(); size_t region_size = TableManager::get_instance()->get_region_size(g_ddl_work.index_id()); DB_NOTICE("global index region size %zu", region_size); DB_NOTICE("global ddlwork tid_%ld", table_id); pb::IndexState current_state; if (TableManager::get_instance()->get_index_state(g_ddl_work.table_id(), g_ddl_work.index_id(), current_state) != 0) { DB_WARNING("ddl index not ready. table_id[%ld] index_id[%ld]", g_ddl_work.table_id(), g_ddl_work.index_id()); return -1; } if (g_ddl_work.errcode() == pb::EXEC_FAIL) { DB_FATAL("ddl work %s fail", g_ddl_work.ShortDebugString().c_str()); return 0; } switch (current_state) { case pb::IS_NONE: if (_update_policy.should_change(table_id, current_state)) { g_ddl_work.set_job_state(pb::IS_DELETE_ONLY); update_table_ddl_mem(g_ddl_work); TableManager::get_instance()->update_index_status(g_ddl_work); } break; case pb::IS_DELETE_ONLY: if (_update_policy.should_change(table_id, current_state)) { g_ddl_work.set_job_state(pb::IS_WRITE_ONLY); update_table_ddl_mem(g_ddl_work); TableManager::get_instance()->update_index_status(g_ddl_work); } break; case pb::IS_WRITE_ONLY: { if (!exist_wait_txn_info(table_id)) { set_wait_txn_info(table_id, g_ddl_work); DBManager::get_instance()->execute_broadcast_task(g_ddl_work); } else { DBManager::get_instance()->update_txn_ready(table_id); if (is_txn_done(table_id)) { if (is_txn_success(table_id)) { DB_NOTICE("ddl work %s all txn done", g_ddl_work.ShortDebugString().c_str()); g_ddl_work.set_job_state(pb::IS_WRITE_LOCAL); update_table_ddl_mem(g_ddl_work); TableManager::get_instance()->update_index_status(g_ddl_work); erase_txn_info(table_id); } else { DB_WARNING("ddl work %s wait txn fail.", g_ddl_work.ShortDebugString().c_str()); DB_WARNING("ddl work %s rollback.", g_ddl_work.ShortDebugString().c_str()); g_ddl_work.set_errcode(pb::EXEC_FAIL); update_table_ddl_mem(g_ddl_work); erase_txn_info(table_id); _update_policy.clear(table_id); } } else { DB_NOTICE("ddl work wait all txn done."); } } } break; case pb::IS_WRITE_LOCAL: //遍历任务提交执行,如果全部任务执行完成,设置状态为PUBLIC { bool done = true; bool rollback = false; const size_t max_task_number = 20; size_t current_task_number = 0; int32_t wait_num = 0; MemRegionDdlWorkMapPtr region_map_ptr; { BAIDU_SCOPED_LOCK(_region_mutex); region_map_ptr = _region_ddlwork[table_id]; } if (region_map_ptr == nullptr) { DB_WARNING("ddl work table_id %ld is done.", table_id); return 0; } int32_t doing_work_number = get_doing_work_number(table_id); if (doing_work_number == -1) { return 0; } else if (doing_work_number > region_size * FLAGS_max_region_num_ratio) { DB_NOTICE("table_%ld not enough region.", table_id); return 0; } region_map_ptr->traverse_with_early_return([&done, &rollback, this, table_id, region_size, &current_task_number, max_task_number, &g_ddl_work, &wait_num](MemRegionDdlWork& region_work) -> bool { auto task_id = std::to_string(region_work.region_info.table_id()) + "_" + std::to_string(region_work.region_info.region_id()); if (region_work.region_info.status() == pb::DdlWorkIdle) { done = false; DB_NOTICE("execute task_%s %s", task_id.c_str(), region_work.region_info.ShortDebugString().c_str()); if (DBManager::get_instance()->execute_task(region_work) == 0) { //提交任务成功,设置状态为DOING. region_work.region_info.set_status(pb::DdlWorkDoing); if (increase_doing_work_number(table_id) > region_size * FLAGS_max_region_num_ratio) { DB_NOTICE("table_%ld not enough region.", table_id); return false; } current_task_number++; if (current_task_number > max_task_number) { DB_NOTICE("table_%ld launch task next round.", table_id); return false; } } else { DB_NOTICE("table_%ld not enough baikaldb to execute.", table_id); return false; } } if (region_work.region_info.status() != pb::DdlWorkDone) { DB_NOTICE("wait task_%s %s", task_id.c_str(), region_work.region_info.ShortDebugString().c_str()); wait_num++; done = false; } if (region_work.region_info.status() == pb::DdlWorkFail) { auto retry_time = region_work.region_info.retry_time(); if (retry_time < FLAGS_max_ddl_retry_time) { if (DBManager::get_instance()->execute_task(region_work) == 0) { region_work.region_info.set_status(pb::DdlWorkDoing); if (increase_doing_work_number(table_id) > region_size * FLAGS_max_region_num_ratio) { DB_NOTICE("not enough region."); return false; } DB_NOTICE("retry task_%s %s", task_id.c_str(), region_work.region_info.ShortDebugString().c_str()); } } else { rollback = true; DB_NOTICE("rollback task_%s %s", task_id.c_str(), region_work.region_info.ShortDebugString().c_str()); } done = false; } else if (region_work.region_info.status() == pb::DdlWorkDupUniq || region_work.region_info.status() == pb::DdlWorkError) { DB_FATAL("region task_%s %s dup uniq or create global index region error.", task_id.c_str(), region_work.region_info.ShortDebugString().c_str()); done = false; rollback = true; } if (rollback) { DB_FATAL("ddl work %s rollback.", g_ddl_work.ShortDebugString().c_str()); g_ddl_work.set_errcode(pb::EXEC_FAIL); update_table_ddl_mem(g_ddl_work); _update_policy.clear(table_id); return false; } return true; }); if (done) { DB_NOTICE("done"); g_ddl_work.set_job_state(pb::IS_PUBLIC); g_ddl_work.set_errcode(pb::SUCCESS); update_table_ddl_mem(g_ddl_work); TableManager::get_instance()->update_index_status(g_ddl_work); } else { DB_NOTICE("wait %d ddl work to finish.", wait_num); } } break; case pb::IS_PUBLIC: DB_NOTICE("work done."); break; default: break; } return 0; } int DDLManager::update_region_ddlwork(const pb::RegionDdlWork& work) { auto table_id = work.table_id(); if (work.status() != pb::DdlWorkDoing) { decrease_doing_work_number(table_id); } pb::MetaManagerRequest request; request.mutable_global_ddl_request()->mutable_region_ddl_work()->CopyFrom(work); request.set_op_type(pb::OP_UPDATE_GLOBAL_REGION_DDL_WORK); apply_raft(request); return 0; } int DDLManager::delete_global_ddlwork_region_info(int64_t table_id) { DB_NOTICE("delete ddl region info."); { BAIDU_SCOPED_LOCK(_region_mutex); _region_ddlwork.erase(table_id); } rocksdb::WriteOptions write_options; std::string begin_key = construct_global_ddl_key(MetaServer::GLOBAL_DDLWORK_REGION_IDENTIFY, {table_id}); std::string end_key = begin_key; end_key.append(8, 0xFF); RocksWrapper* db = RocksWrapper::get_instance(); auto res = db->remove_range(write_options, db->get_meta_info_handle(), begin_key, end_key, true); if (!res.ok()) { DB_FATAL("DDL_LOG remove_index error: code=%d, msg=%s", res.code(), res.ToString().c_str()); } return 0; } int DDLManager::delete_global_ddlwork_info(int64_t table_id) { DB_NOTICE("delete ddl table info."); { BAIDU_SCOPED_LOCK(_table_mutex); _table_ddl_mem.erase(table_id); } _update_policy.clear(table_id); { BAIDU_SCOPED_LOCK(_txn_mutex); _wait_txns.erase(table_id); } std::vector<std::string> keys {construct_global_ddl_key(MetaServer::DDLWORK_IDENTIFY, {table_id})}; if(MetaRocksdb::get_instance()->delete_meta_info(keys) != 0) { DB_FATAL("delete meta info error."); return -1; } return 0; } int DDLManager::update_ddl_status(bool is_suspend, int64_t table_id) { baikaldb::pb::DdlWorkInfo mem_info; if (get_ddl_mem(table_id, mem_info)) { mem_info.set_suspend(is_suspend); update_table_ddl_mem(mem_info); std::string global_ddl_string; if (!mem_info.SerializeToString(&global_ddl_string)) { DB_FATAL("serialzeTostring error."); return -1; } if(MetaRocksdb::get_instance()->put_meta_info( construct_global_ddl_key(MetaServer::DDLWORK_IDENTIFY, {table_id}), global_ddl_string) != 0) { DB_FATAL("put meta info error."); return -1; } } return 0; } int DDLManager::raft_update_info(const pb::MetaManagerRequest& request, const int64_t apply_index, braft::Closure* done) { auto& ddl_request = request.global_ddl_request(); auto table_id = ddl_request.table_id(); switch (request.op_type()) { case pb::OP_UPDATE_GLOBAL_REGION_DDL_WORK: { update_global_ddlwork_region_info(request.global_ddl_request().region_ddl_work()); break; } case pb::OP_SUSPEND_DDL_WORK: { DB_NOTICE("suspend global ddl work %ld", table_id); update_ddl_status(true, table_id); break; } case pb::OP_RESTART_DDL_WORK: { DB_NOTICE("restart global ddl work %ld", table_id); update_ddl_status(false, table_id); break; } default: break; } IF_DONE_SET_RESPONSE(done, pb::SUCCESS, "success"); return 0; } void DDLManager::delete_ddlwork(const pb::MetaManagerRequest& request, braft::Closure* done) { DB_NOTICE("delete ddlwork %s", request.ShortDebugString().c_str()); int64_t table_id = request.ddlwork_info().table_id(); delete_global_ddlwork_region_info(table_id); delete_global_ddlwork_info(table_id); Bthread _rm_th; _rm_th.run([table_id](){ DBManager::get_instance()->clear_task(table_id); }); IF_DONE_SET_RESPONSE(done, pb::SUCCESS, "success"); } int DDLManager::apply_raft(const pb::MetaManagerRequest& request) { SchemaManager::get_instance()->process_schema_info(NULL, &request, NULL, NULL); return 0; } int DDLManager::update_global_ddlwork_region_info(const pb::RegionDdlWork& work) { auto table_id = work.table_id(); MemRegionDdlWorkMapPtr region_map_ptr; { BAIDU_SCOPED_LOCK(_region_mutex); region_map_ptr = _region_ddlwork[table_id]; } auto task_id = std::to_string(table_id) + "_" + std::to_string(work.region_id()); if (region_map_ptr != nullptr) { DB_NOTICE("update region task_%s %s", task_id.c_str(), work.ShortDebugString().c_str()); MemRegionDdlWork region_work; region_work.region_info = work; region_map_ptr->set(work.region_id(), region_work); } std::string region_ddl_string; if (!work.SerializeToString(&region_ddl_string)) { DB_FATAL("serialzeTostring error."); return -1; } if(MetaRocksdb::get_instance()->put_meta_info( construct_global_ddl_key(MetaServer::GLOBAL_DDLWORK_REGION_IDENTIFY, {work.table_id(), work.region_id()}), region_ddl_string) != 0) { DB_FATAL("put region info error."); return -1; } return 0; } void DDLManager::get_global_ddlwork_info(const pb::QueryRequest* request, pb::QueryResponse* response) { auto table_id = request->table_id(); MemRegionDdlWorkMapPtr region_map_ptr; { BAIDU_SCOPED_LOCK(_region_mutex); region_map_ptr = _region_ddlwork[table_id]; } if (region_map_ptr != nullptr) { region_map_ptr->traverse([&response](MemRegionDdlWork& region_work){ auto iter = response->add_region_ddl_infos(); iter->CopyFrom(region_work.region_info); }); } } }
0fbc6b411979e99a535bca5f52b4fbb324d679b4
8ca1a64788221a76a72b6ce21cb3d0a8fb74d237
/FormularioExpressaoQuatroVariaveis.cpp
f195054d185fcc75fdb5d046d9ccc49432957d3f
[]
no_license
EltonCustodio/Pratilog
782f5738f6202b764061d399049ce828df19c877
6514e6061baa2fdae910f54dd5740af813ea4af0
refs/heads/master
2016-09-06T03:06:42.015347
2015-05-13T14:41:17
2015-05-13T14:41:17
35,554,112
0
0
null
null
null
null
UTF-8
C++
false
false
1,667
cpp
//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "FormularioExpressaoQuatroVariaveis.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.dfm" TFormExpressaoQuatroVariaveis *FormExpressaoQuatroVariaveis; //--------------------------------------------------------------------------- __fastcall TFormExpressaoQuatroVariaveis::TFormExpressaoQuatroVariaveis(TComponent* Owner) : TForm(Owner) { } //--------------------------------------------------------------------------- void __fastcall TFormExpressaoQuatroVariaveis::ButtonPraticarClick( TObject *Sender) { Status = 4; Close(); } //--------------------------------------------------------------------------- void __fastcall TFormExpressaoQuatroVariaveis::RadioButtonExpUmQuatroVariaveisClick( TObject *Sender) { Expressao = 1; } //--------------------------------------------------------------------------- void __fastcall TFormExpressaoQuatroVariaveis::RadioButtonExpDoisQuatroVariaveisClick( TObject *Sender) { Expressao = 2; } //--------------------------------------------------------------------------- void __fastcall TFormExpressaoQuatroVariaveis::RadioButtonExpTresQuatroVariaveisClick( TObject *Sender) { Expressao = 3; } //--------------------------------------------------------------------------- void __fastcall TFormExpressaoQuatroVariaveis::ButtonVoltarClick( TObject *Sender) { Status = 5; Close(); } //---------------------------------------------------------------------------
1ed3dd1e4a083079f0d1c2cd6d5871337b3377bb
805e83058e2cb1c4042fe31a0c5f2aacf76eca63
/Glanda/CmdUpdateObj.cpp
463a894ab0dd31ba13d15ab07702c9826980a3a8
[]
no_license
progmalover/vc-stgld
70ee037f3f27857fcdbb344b5ee8533c724b43b9
96055b2a2deca44eed5bb2c6e1e3f6cb1aff3a6b
refs/heads/master
2021-01-12T05:17:05.334966
2017-01-12T14:49:44
2017-01-12T14:49:44
77,895,327
0
0
null
null
null
null
UTF-8
C++
false
false
673
cpp
#include "StdAfx.h" #include "cmdupdateobj.h" #include "TransAdaptor.h" #include "gldCharacter.h" #include "gldMovieClip.h" #include "gldShape.h" #include "SWFProxy.h" #include "gldInstance.h" CExtractObj::CExtractObj() : m_pObj(NULL) { } CExtractObj::CExtractObj(const gld_shape &shape) { gld_shape tshape = shape; //ASSERT(tshape.ptr()); //gldCharacter *pChar = (gldCharacter *)tshape.ptr(); //m_pObj = pChar->m_key->GetObj(); gldInstance *pInstance = CTraitInstance(tshape); m_pObj = pInstance->m_obj; } CExtractObj::CExtractObj(gldMovieClip *pMC) { m_pObj = NULL; } CExtractObj::operator gldObj*() { return m_pObj; }
d686329dc0df11123178ac36d08b80a0964133ce
dbe1ad8c1ae77e80c1f0d613c70334bf911d2f5f
/apps/shaderResearch/alphamask/src/testApp.cpp
2ddc10715201c4a2b72ab8cfe9c5a7a423830714
[]
no_license
levky/OF
b239f2337ecdadc2ef72058f7cc6e206167e78f2
49acda22ecb8ff2e4e2cf198d7f494c562ab2e89
refs/heads/master
2020-05-15T18:28:12.238925
2011-09-15T10:15:57
2011-09-15T10:16:01
1,170,485
2
1
null
null
null
null
UTF-8
C++
false
false
4,818
cpp
/* * ofxAlphaMaskShader.h * * Created by James George, http://www.jamesgeorge.org * in collaboration with FlightPhase http://www.flightphase.com * * 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. * * ---------------------- * * ofxAlphaMaskShader is not really an addon, but an example * of how to use a shader to have one image become the alpha * channel of another. */ #include "testApp.h" //-------------------------------------------------------------- void testApp::setup(){ //need this for alpha to come through ofEnableAlphaBlending(); //we use 3 images, a bottom layer, a top layer, and a mask image //the bottom layer is always drawn first //then the top layer is drawn over it,using the mask to punch out //some of the alpha //in this example, they are all the same size. We move the mask //to match the mouse so it looks like you can x-ray through the hand topLayer.loadImage("topLayer.png"); mask.loadImage("mask.png"); bottomLayer.loadImage("bottomLayer.png"); //set the texture parameters for the maks shader. just do this at the beginning maskShader.load("composite"); maskShader.begin(); maskShader.setUniformTexture("Tex0", topLayer.getTextureReference(), 0); maskShader.setUniformTexture("Tex1", mask.getTextureReference(), 1); maskShader.end(); } //-------------------------------------------------------------- void testApp::update(){ } //-------------------------------------------------------------- void testApp::draw(){ //first draw the bottom layer bottomLayer.draw(0, 0); //then draw a quad for the top layer using our composite shader to set the alpha maskShader.begin(); //our shader uses two textures, the top layer and the alpha //we can load two textures into a shader using the multi texture coordinate extensions glActiveTexture(GL_TEXTURE0_ARB); topLayer.getTextureReference().bind(); glActiveTexture(GL_TEXTURE1_ARB); mask.getTextureReference().bind(); //draw a quad the size of the frame glBegin(GL_QUADS); //move the mask around with the mouse by modifying the texture coordinates float maskOffset = 15 - mouseY; glMultiTexCoord2d(GL_TEXTURE0_ARB, 0, 0); glMultiTexCoord2d(GL_TEXTURE1_ARB, 0, maskOffset); glVertex2f( 0, 0); glMultiTexCoord2d(GL_TEXTURE0_ARB, topLayer.getWidth(), 0); glMultiTexCoord2d(GL_TEXTURE1_ARB, mask.getWidth(), maskOffset); glVertex2f( ofGetWidth(), 0); glMultiTexCoord2d(GL_TEXTURE0_ARB, topLayer.getWidth(), topLayer.getHeight()); glMultiTexCoord2d(GL_TEXTURE1_ARB, mask.getWidth(), mask.getHeight() + maskOffset); glVertex2f( ofGetWidth(), ofGetHeight()); glMultiTexCoord2d(GL_TEXTURE0_ARB, 0, topLayer.getHeight()); glMultiTexCoord2d(GL_TEXTURE1_ARB, 0, mask.getHeight() + maskOffset); glVertex2f( 0, ofGetHeight() ); glEnd(); //deactive and clean up glActiveTexture(GL_TEXTURE1_ARB); mask.getTextureReference().unbind(); glActiveTexture(GL_TEXTURE0_ARB); topLayer.getTextureReference().unbind(); maskShader.end(); } //-------------------------------------------------------------- void testApp::keyPressed(int key){ } //-------------------------------------------------------------- void testApp::keyReleased(int key){ } //-------------------------------------------------------------- void testApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void testApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::windowResized(int w, int h){ }
825c645a79e7bbe9b94ffe4006035038531529ed
dcc457a45dffc039e197de1251d9a3ed7db2cde2
/1454E.cpp
21d39a052c776ab88bc1b698eba6203369d33f49
[]
no_license
shammo18/Sports-Programming
53500a0d5036de6ffda0f444814ccfc9710c2fba
88fc129c6005c379bc489871ab9ad4ba6b1cffaf
refs/heads/master
2023-01-28T22:59:08.746384
2020-12-09T09:42:31
2020-12-09T09:42:31
266,929,767
0
0
null
null
null
null
UTF-8
C++
false
false
5,817
cpp
//Bismillahir Rahmanir Rahim //#pragma GCC optimize("Ofast,unroll-loops") //#pragma GCC target("avx,avx2,fma") #include<bits/stdc++.h> #include<ext/pb_ds/assoc_container.hpp> #include<ext/pb_ds/tree_policy.hpp> #define ll long long #define ull unsigned long long #define pii pair<int,int> #define pll pair<ll,ll> #define xx first #define yy second #define sci(n) scanf("%d",&n) #define scii(n,m) scanf("%d%d",&n,&m) #define sciii(n,m,w) scanf("%d%d%d",&n,&m,&w) #define scl(n) scanf("%lld",&n) #define scll(n,m) scanf("%lld%lld",&n,&m) #define sclll(n,m,w) scanf("%lld%lld%lld",&n,&m,&w) #define pf(a) printf("%d\n",a) #define CASE(a) printf("Case %d: ",a) #define endl '\n' #define READ freopen("input.txt","r",stdin) #define WRITE freopen("output.txt","w",stdout); #define PI acos(-1) #define mem(a,b) memset(a,b,sizeof(a)) #define SQR(a) (a)*(a) #define all(v) v.begin(),v.end() #define pb push_back #define IOS ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); #define mod 1000000007 #define inf INT_MAX #define eps 1e-9 using namespace __gnu_pbds; using namespace std; #define Gene template< class #define Rics printer& operator, Gene c> struct rge{c b, e;}; Gene c> rge<c> range(c i, c j){ return {i, j};} struct printer{ ~printer(){cerr<<endl;} Gene c >Rics(c x){ cerr<<boolalpha<<x; return *this;} Rics(string x){cerr<<x;return *this;} Gene c, class d >Rics(pair<c, d> x){ return *this,"(",x.first,", ",x.second,")";} Gene ... d, Gene ...> class c >Rics(c<d...> x){ return *this, range(begin(x), end(x));} Gene c >Rics(rge<c> x){ *this,"["; for(auto it = x.b; it != x.e; ++it) *this,(it==x.b?"":", "),*it; return *this,"]";} }; #define debug() cerr<<"LINE "<<__LINE__<<" >> ", printer() #define dbg(x) "[",#x,": ",(x),"] " mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); int my_rand(int l, int r) { return uniform_int_distribution<int>(l, r) (rng); } //int dx[] = {0,1,0,-1,1,1,-1,-1}; //int dy[] = {1,0,-1,0,1,-1,-1,1}; //ll ncr(ll n,ll r){if(n==r)return 1;if(r==1)return n;if(dp[n][r]!=-1)return dp[n][r];return dp[n][r]=ncr(n-1,r)+ncr(n-1,r-1);} // bit manipulations //bool checkbit(int mask,int bit){return mask & (1<<bit);} //int setbit(int mask,int bit){ return mask | (1<<bit) ; } //int clearbit(int mask,int bit){return mask & ~(1<<bit);} //int togglebit(int mask,int bit){return mask ^ (1<<bit);} //int bitno(int mask) {return (int)__builtin_popcount(mask);} template <typename T> T BigMod (T b,T p,T m){if (p == 0) return 1;if (p%2 == 0){T s = BigMod(b,p/2,m);return ((s%m)*(s%m))%m;}return ((b%m)*(BigMod(b,p-1,m)%m))%m;} template <typename T> T ModInv (T b,T m){return BigMod(b,m-2,m);} template <typename T> T POW(T B,T P){ if(P==0) return 1; if(P&1) return B*POW(B,P-1); else return SQR(POW(B,P/2));} template <typename T> T Dis(T x1,T y1,T x2, T y2){return sqrt( SQR(x1-x2) + SQR(y1-y2) );} template <typename T> T Angle(T x1,T y1,T x2, T y2){ return atan( double(y1-y2) / double(x1-x2));} template <typename T> T gcd(T a,T b){if(a<0)return gcd(-a,b);if(b<0)return gcd(a,-b);return (b==0)?a:gcd(b,a%b);} template <typename T> T lcm(T a,T b) {if(a<0)return lcm(-a,b);if(b<0)return lcm(a,-b);return a*(b/gcd(a,b));} template <typename T> T euclide(T a,T b,T &x,T &y) {if(a<0){T d=euclide(-a,b,x,y);x=-x;return d;} if(b<0){T d=euclide(a,-b,x,y);y=-y;return d;} if(b==0){x=1;y=0;return a;}else{T d=euclide(b,a%b,x,y);T t=x;x=y;y=t-(a/b)*y;return d;}} template <typename T> void ia (T a[],int n){for (int i=0; i<n; i++) cin >> a[i];} template <typename T> void pa (T a[],int n){for (int i=0; i<n-1; i++) cout << a[i] << " ";cout << a[n-1] << endl;} template <typename T> ll isLeft(T a,T b,T c) { return (a.x-b.x)*(b.y-c.y)-(b.x-c.x)*(a.y-b.y);} template<typename T> using ordered_set=tree<T,null_type,less<T>,rb_tree_tag,tree_order_statistics_node_update>; ///********************************MY CODE STARTS HERE********************************/// int n; const int N = 200005; vector<int> g[N]; bool vis[N] , col[N]; int sub[N]; int one , two; void dfs(int u , int p){ vis[u] = true; for(auto v : g[u]){ if(v == p) continue; if(!vis[v]) dfs(v , u); else { //cout << u << " " << v << endl; one = u; two = v; return; } } } bool flag = false; void dfs2(int u , int p){ vis[u] = true; if(!flag)col[u] = true; for(auto v : g[u]){ if(v == p || (u == one && v == two)) continue; if(!vis[v])dfs2(v , u); else{ flag = true; return; } } if(!flag)col[u] = false; } void dfs3(int u , int p){ vis[u] = true; sub[u] = 1; for(auto v : g[u]){ if(v == p) continue; if(!vis[v]){ dfs3(v , u); sub[u] += sub[v]; } } } void solve(){ cin >> n; for(int i = 0;i <= n;i++){ g[i].clear(); vis[i] = col[i] = 0; sub[i] = 0; flag = false; } for(int i = 0;i < n;i++){ int u , v; cin >> u >> v; g[u].pb(v); g[v].pb(u); } dfs(1 , 0); mem(vis , 0); dfs2(one , 0); for(int i = 1;i <= n;i++){ //cout << col[i] <<" "; vis[i] = col[i]; } ll sum = 0; ll ans = 0; ll cnt = 0; for(int i = 1;i <= n;i++){ if(col[i]){ dfs3(i , 0); sum += --sub[i]; cnt++; } } // cout << sum << endl; ll temp = 0; for(int i = 1;i <= n;i++){ if(col[i]){ temp += 2LL * sub[i] * (sum - sub[i]); ans += (sub[i] * (sub[i] - 1)) / 2; } } // cout << temp << endl; ans += temp / 2; ans += cnt * (cnt - 1); ans += sum * (2 * cnt - 1); cout << ans << endl; // for(int i = 1;i <= n;i++){ // cout << sub[i] <<" "; // } } int main(){ //IOS; int T = 1; cin >> T; while(T--){ solve(); } return 0; }
f244ca5258cffe0069316cc407126a1bdbd1ccd6
cec2c23d218596762eccc767c8aa8c1b67532fec
/cimgtest.cpp
525c9705b13a49f8719c4859fd302c917cb713bc
[]
no_license
suiqingsheng/book
4e330434fa70529616e12d8049f028c33e3394c7
5dcc27354d48205a195771010d67db8aedecf14e
refs/heads/master
2020-05-19T17:18:07.286805
2012-05-02T19:58:23
2012-05-02T19:58:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,204
cpp
/* * cimgtest.cpp * * Created on: Apr 27, 2012 * Author: tobias */ #include <algorithm> #include <vector> #include <map> #include <string> #include "CImg.h" using namespace cimg_library; float fabsf(float); void cluster_search(const CImg<float> & fimage, CImg<unsigned char> & cluster, int x, int y, float sameness_limit) { std::vector<std::pair<int,int> > open_set(1, std::pair<int,int>(x,y)); while (open_set.size()) { x = open_set.back().first; y = open_set.back().second; open_set.pop_back(); cluster(x,y) = 255; for (int xx = x-1; xx <= x+1; ++xx) for (int yy = y-1; yy <= y+1; ++yy) { if (xx >= 0 && xx < cluster.width() && yy >= 0 && yy < cluster.height()) if (cluster(xx,yy) == 0 && fabsf(fimage(x,y) - fimage(xx,yy)) < sameness_limit) { cluster(xx, yy) = 128; open_set.push_back(std::pair<int,int>(xx,yy)); } } } } CImg<float> rgb_to_gray(const CImg<unsigned char> & img) { int w = img.width(); int h = img.height(); CImg<float> fimage(w,h,1,1,0.0f); for (int x = 0; x < w; ++x) for (int y = 0; y < h; ++y) fimage(x,y) = (img(x,y,0,0) * 0.30f + img(x,y,0,1) * 0.59f + img(x,y,0,2) * 0.11f) / 256.0f; return fimage; } int max_hist_bin_index(const CImg<float> & hist) { float maxval = -1e6; int maxind = -1; for(int x = 0;x < hist.width();++x){ if(hist(x, 0) > maxval){ maxval = hist(x, 0); maxind = x; } } return maxind; } int center_square_max_hist_bin(const CImg<float> & fimage, const int bins) { int w = fimage.width(); int h = fimage.height(); int lsquare = std::min(w,h) / 3; int left = (w - lsquare) / 2; int top = (h - lsquare) / 2; CImg<float> square = fimage.get_crop(left,top,left+lsquare,top+lsquare); CImg<float> hist = square.get_histogram(bins, 0.0f, 1.0f); return max_hist_bin_index(hist); } CImg<unsigned char> find_biggest_cluster(int w, int h, const float initial_white, CImg<float> fimage, const float initial_tolerance, const float sameness_limit) { CImg<unsigned char> clustered_flag(w, h, 1, 1, 0), biggest_cluster(clustered_flag), current_cluster(clustered_flag); double biggest_cluster_size = 0; for(int x = 0;x < w;++x) for(int y = 0;y < h;++y){ if(clustered_flag(x, y) == 0 && fabsf(initial_white - fimage(x, y)) < initial_tolerance){ current_cluster.fill((unsigned char)(0)); cluster_search(fimage, current_cluster, x, y, sameness_limit); double current_cluster_size = current_cluster.sum() / 255; clustered_flag |= current_cluster; if(current_cluster_size > biggest_cluster_size){ printf("replaces biggest cluster\n"); biggest_cluster.assign(current_cluster); biggest_cluster_size = current_cluster_size; } } } return biggest_cluster; } void find_white_area(const CImg<float> & fimage) { int w = fimage.width(); int h = fimage.height(); const int bins = 64; const float initial_tolerance = 1.0f / bins / 2; const float initial_white = 1.0f / bins * center_square_max_hist_bin(fimage, bins) + initial_tolerance; const float sameness_limit = 1.0f / 256 * 8; //4; CImg<unsigned char> biggest_cluster = find_biggest_cluster(w, h, initial_white, fimage, initial_tolerance, sameness_limit); biggest_cluster.save_png("/tmp/x.png", 1); biggest_cluster.display("White Area"); } int max_hist_bin_width(const CImg<float> & hist, int maxind) { float maxval = hist(maxind, 0); int width = 2, searchdownind = maxind - 1, searchupind = maxind + 1; while(searchdownind > 0 && hist(searchdownind, 0) > maxval / 2){ --searchdownind; ++width; } while(searchupind < hist.width() && hist(searchupind, 0) > maxval / 2){ ++searchupind; ++width; } return width; } void crop_at_white_margin(CImg<float> & fimage, const float white = 0.67) { int w = fimage.width(), h = fimage.height(); enum {north,south,east,west}; int crop[4]; for (int blowing = north; blowing <= west; ++blowing) { printf("searching %d\n", blowing); crop[blowing] = 0; int max_search, max_dark_edges; bool found_white = false; if (blowing <= south) { max_search = h / 5; max_dark_edges = w / 15; } else { max_search = w / 5; max_dark_edges = h / 15; } for (int search = 0; search < max_search; ++search) { CImg<float> test; switch(blowing) { case north: test = fimage.get_crop(0,search,w-1,search); break; case south: test = fimage.get_crop(0,h-search-1,w-1,h-search-1); break; case west: test = fimage.get_crop(search,0,search,h-1).transpose(); break; case east: test = fimage.get_crop(w-search-1,0,w-search-1,h-1).transpose(); break; } // count dark pixels, ignore edge case as defined int low_edge_last_dark = -1, high_edge_last_dark = -1; for (int edge_ind = 0; edge_ind < max_dark_edges; ++edge_ind) { if (test(edge_ind) < white) low_edge_last_dark = edge_ind; if (test(test.width()-edge_ind-1) < white) high_edge_last_dark = edge_ind; } bool dark = low_edge_last_dark + high_edge_last_dark + 2 > max_dark_edges; for (int ind = max_dark_edges; ind < test.width() - max_dark_edges; ++ind) dark = dark || (test(ind) < white); if (found_white) { crop[blowing] = search; if (dark) break; } found_white = !dark; } } fimage.crop(crop[west],crop[north],w-crop[east]-1,h-crop[south]-1); } void white_statistics(CImg<float> & fimage, const int bins, const int max_adjacent_white_diff = 2, const int M = 11, const int N = 15) { int w = fimage.width(); int h = fimage.height(); CImg<float> hist = fimage.get_histogram(bins, 0.0f, 1.0f); int gmaxind = max_hist_bin_index(hist); int gwidth = max_hist_bin_width(hist, gmaxind); int min_white = std::max(1, gmaxind - gwidth); int max_white = std::min(bins - 1, gmaxind + gwidth); printf("white= %d +- %d\n", gmaxind, gwidth); int tile_w = w / N; int tile_h = h / M; CImg<int> tiles_white(N,M,1,1,-1); CImg<int> tiles_white_width(tiles_white); for (int m = 0; m < M; ++m) { for (int n = 0; n < N; ++n) { CImg<float> hist = fimage.get_crop(n * tile_w, m * tile_h, (n+1)*tile_w-1, (m+1)*tile_h-1).histogram(bins,0.0f,1.0f); tiles_white(n,m) = max_hist_bin_index(hist); tiles_white_width(n,m) = max_hist_bin_width(hist, tiles_white(n,m)); printf("%d ",tiles_white(n,m)); } printf("\n"); } // white value correction; // Determine values that need not be corrected. std::vector<std::pair<int,int> > open_set, correct_these_set; CImg<unsigned char> tiles_checked(N,M,1,1,0); for (int m = 0; m < M; ++m) for (int n = 0; n < N; ++n) { if (tiles_white(n,m) == gmaxind) { open_set.push_back(std::pair<int,int>(n,m)); tiles_checked(n,m) = 128; } } if (open_set.size() == 0) { fprintf(stderr, "Empty open set\n"); exit(1); } while (open_set.size()) { int n = open_set.front().first; int m = open_set.front().second; open_set.erase(open_set.begin()); for (int nn = n-1; nn <= n+1; ++nn) for (int mm = m-1; mm<=m+1; ++mm) { if (nn >= 0 && nn < N && mm >= 0 && mm < M) if (tiles_checked(nn,mm) == 0) { if (tiles_white(nn,mm) >= min_white && tiles_white(nn,mm) <= max_white && abs(tiles_white(nn,mm) - tiles_white(n,m)) <= max_adjacent_white_diff) { open_set.push_back(std::pair<int,int>(nn,mm)); tiles_checked(nn,mm) = 128; } else { correct_these_set.push_back(std::pair<int,int>(nn,mm)); } } } } // Correct the rest for (unsigned k = 0; k < correct_these_set.size(); ++k) { int n = correct_these_set[k].first; int m = correct_these_set[k].second; if (tiles_checked(n,m) == 0) { int numerator = 0, denominator = 0; for (int nn = n-1; nn <= n+1; ++nn) for (int mm = m-1; mm<=m+1; ++mm) if (nn >= 0 && nn < N && mm >= 0 && mm < M) { if (tiles_checked(nn,mm)) { numerator += tiles_white(nn,mm); ++denominator; } else correct_these_set.push_back(std::pair<int,int>(nn,mm)); } tiles_white(n,m) = denominator ? (numerator / denominator) : gmaxind; tiles_checked(n,m) = 64; } } printf("corrected:\n"); for (int m = 0; m < M; ++m) { for (int n = 0; n < N; ++n) { printf("%d ",tiles_white(n,m)); } printf("\n"); } // whiten CImg<bool> outside_white_corridor(w,h,1,1,false); for (int x = 0; x < w; ++x) for (int y = 0; y < h; ++y) { int m = std::min(y / tile_h, M-1); int n = std::min(x / tile_w, N-1); int white = tiles_white(n,m); int width = std::min(tiles_white_width(n,m), 3); if (fabs(white - fimage(x,y) * bins) > width) outside_white_corridor(x,y) = true; float white_lower_limit = float(white - width) / bins; fimage(x,y) = std::min(255.0/256,pow(fimage(x,y) / white_lower_limit, 6)); } // crop 1: discard columns/lines with mostly non-white pixels int top,bot,lef,rig; for (top = 0; top < h && outside_white_corridor.get_crop(0,top,w-1,top).sum() > (w / 2.0); ++top); for (bot = h-1; bot > top && outside_white_corridor.get_crop(0,bot,w-1,bot).sum() > (w / 2.0); --bot); for (lef = 0; lef < w && outside_white_corridor.get_crop(lef,0,lef,h-1).sum() > (h / 2.0); ++lef); for (rig = w-1; rig > lef && outside_white_corridor.get_crop(rig,0,rig,h-1).sum() > (h / 2.0); --rig); fimage.crop(lef,top,rig,bot); // crop 2: search for white-ish margin crop_at_white_margin(fimage); } void black_statistics(const CImg<float> & fimage, const int bins, const int M = 11, const int N = 15) { int w = fimage.width(); int h = fimage.height(); CImg<float> hist = fimage.get_histogram(bins, 0.0f, 1.0f); int gmaxind = max_hist_bin_index(hist); int gwidth = max_hist_bin_width(hist, gmaxind); printf("white= %d +- %d\n", gmaxind, gwidth); int tile_w = w / N; int tile_h = h / M; CImg<int> tiles(N,M,1,1,-1); for (int m = 0; m < M; ++m) { for (int n = 0; n < N; ++n) { CImg<float> hist = fimage.get_crop(n * tile_w, m * tile_h, (n+1)*tile_w-1, (m+1)*tile_h-1).histogram(bins,0.0f,1.0f); int maxind = max_hist_bin_index(hist); int width = max_hist_bin_width(hist, maxind); printf("%d+-%d ",maxind,width); if (maxind >= (gmaxind - gwidth) && maxind <= (gmaxind + gwidth)) tiles(n,m) = maxind; } printf("\n"); } // shepard interpolation; CImg<float> ftiles(tiles); for (int m = 0; m < M; ++m) for (int n = 0; n < N; ++n) { if (tiles(n,m) < 0) { float weightsum = 0; ftiles(n,m) = 0; for (int x = 0; x < N; ++x) for (int y = 0; y < M; ++y) if (tiles(x,y) >= 0) { float weight = 1 / sqrt((x-n)*(x-n) + (y-m)*(y-m)); weightsum += weight; ftiles(n,m) += weight * tiles(x,y); } ftiles(n,m) /= weightsum; } else ftiles(n,m) = tiles(n,m); } } int main(int argc, char ** argv) { std::string filename = "/home/tobias/Buch/Softwareentwicklung/Android/Android_Web_Apps/DSCN0477.JPG"; if (argc >= 3) filename = argv[2]; std::string mode = "find_white"; if (argc >= 2) mode = argv[1]; if (mode == "fine_white") { CImg<unsigned char> image(filename.c_str()); CImg<float> fimage = rgb_to_gray(image); find_white_area(fimage); } else if (mode == "white_statistics") { CImg<unsigned char> image(filename.c_str()); CImg<float> fimage = rgb_to_gray(image); const int bins = 64; white_statistics(fimage, bins); for (int fnameind = 3; fnameind < argc; ++fnameind) { CImg<unsigned char> image(argv[fnameind]); CImg<float> fimage = rgb_to_gray(image); white_statistics(fimage, bins); } } else if (mode == "black_statistics") { CImg<unsigned char> image(filename.c_str()); CImg<float> fimage = rgb_to_gray(image); const int bins = 64; white_statistics(fimage, bins); for (int fnameind = 3; fnameind < argc; ++fnameind) { CImg<unsigned char> image(argv[fnameind]); CImg<float> fimage = rgb_to_gray(image); white_statistics(fimage, bins); } } else if (mode == "book") { std::string output_dir = argv[2]; std::map<double, std::string> page_map; for (int i = 3; i < (argc - 1); i+= 2) { filename = argv[i]; double page = atof(argv[i+1]); page_map[page] = filename; } for (std::map<double,std::string>::const_iterator i = page_map.begin(); i != page_map.end(); ++i) { CImg<unsigned char> image((*i).second.c_str()); CImg<float> fimage = rgb_to_gray(image); const int bins = 64; white_statistics(fimage, bins); char output_name[100] = ""; double page = (*i).first; snprintf(output_name, 99, "/%07.2f.png", page); fimage *= 256; CImg<float> rotated(fimage.height(), fimage.width(), 1, 1); bool odd = false; if (page >= 1.0) odd = int(page) & 1; else odd = int(page * 100) & 1; for (int x = 0; x < fimage.width(); ++x) for (int y = 0; y < fimage.height(); ++y) { if (odd) rotated(rotated.width() - y - 1,x) = fimage(x,y); else rotated(y, rotated.height() - x - 1) = fimage(x,y); } rotated.save_png((output_dir + output_name).c_str(), 1); } } return 0; }
3d94ab617b17e0aa55477e5a9e4a2ef95780638e
c9603c7d7f83d8704b5cfabad7a28ec429af6fa0
/test/unit_test/test_seqence.cpp
68eddc1ec7fed0d8da44fa00cd70a5567d8512bd
[ "BSL-1.0" ]
permissive
dan-42/spoon
6bc5bc7bb89df4df28a19abe37828cc1f9aa93e9
be0a8770b371fcb33fb63e6e934972cb08ace2a6
refs/heads/master
2021-01-22T08:02:49.138827
2017-09-13T19:30:23
2017-09-13T19:30:23
92,599,624
4
0
null
null
null
null
UTF-8
C++
false
false
2,610
cpp
/** * ninja-wooki, is a BACnet stack C++ library * * Copyright (C) 2015 Daniel Friedrich * * This file is part of ninja-wooki. * * ninja-wooki 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. * * ninja-wooki 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 Mupen64PlusAE. If not, see <http://www.gnu.org/licenses/>. * * Authors: Daniel Friedrich */ #define BOOST_TEST_MODULE test spoon seqence #include <boost/test/included/unit_test.hpp> #include <boost/fusion/adapted/struct.hpp> #include <iostream> #include <vector> #include <spoon.hpp> #include <spoon/seq.hpp> #include <spoon/binary.hpp> struct pod_type { bool my_bool; uint32_t my_uint32; double my_double; }; BOOST_FUSION_ADAPT_STRUCT(pod_type, my_bool, my_uint32, my_double); BOOST_AUTO_TEST_SUITE( test_spoon_seq ) BOOST_AUTO_TEST_CASE( test_spoon_seq_simple ) { constexpr auto engine = spoon::seq<pod_type>(spoon::big_endian::bool8, spoon::big_endian::uint32, spoon::big_endian::float64); std::vector<uint8_t> binary_data{}; { pod_type var{true, 1337, 3.14}; auto success = spoon::serialize(binary_data, engine, var); BOOST_TEST(success == true); BOOST_TEST( binary_data.size() == size_t{13} ); BOOST_TEST(binary_data[0] == 0x01); BOOST_TEST(binary_data[1] == 0x00); BOOST_TEST(binary_data[2] == 0x00); BOOST_TEST(binary_data[3] == 0x05); BOOST_TEST(binary_data[4] == 0x39); BOOST_TEST(binary_data[5] == 0x40); BOOST_TEST(binary_data[6] == 0x09); BOOST_TEST(binary_data[7] == 0x1E); BOOST_TEST(binary_data[8] == 0xB8); BOOST_TEST(binary_data[9] == 0x51); BOOST_TEST(binary_data[10] == 0xEB); BOOST_TEST(binary_data[11] == 0x85); BOOST_TEST(binary_data[12] == 0x1F); } { pod_type pod; auto start = binary_data.begin(); const auto end = binary_data.end(); auto success = spoon::deserialize(start, end, engine, pod); BOOST_TEST(success == true); BOOST_TEST((start == end), "start != end"); BOOST_TEST(pod.my_bool == true); BOOST_TEST(pod.my_uint32 == uint32_t{1337}); BOOST_TEST(pod.my_double == 3.14); } } BOOST_AUTO_TEST_SUITE_END()
9d55df722d4c376f1d4effafc364a9cddd764afb
85a8417c78231eeb2dbfae22fa2a57d1a30207a0
/chpater7/nullptr.cpp
6969ebbda0b180e0d20823e9a799d888e32b4ac0
[]
no_license
lilelr/codes-understanding-of-C-11
4298a9a4a581c4aab6b05de5ee611527a7e2ff4d
d1524cb738e8495eeb9c42b80d8c6289ba755877
refs/heads/master
2021-01-22T12:57:24.459225
2018-04-14T06:51:09
2018-04-14T06:51:09
102,360,880
0
0
null
null
null
null
UTF-8
C++
false
false
1,343
cpp
#include <climits> #include <cassert> #include <iostream> #include <vector> #include <map> #include <string> #include <type_traits> #include <typeinfo> #include <memory> #include <atomic> #include <thread> //#include <cstdatomic> #include <unistd.h> #include <cstdlib> /* at_quick_exit example */ #include <stdio.h> /* puts */ #include <stdlib.h> /* at_quick_exit, quick_exit, EXIT_SUCCESS */ using namespace std; void fun(char* p){ ccout<< "invoke fun(char* ) "<< endl; } void fun(int){ cout<<"invoke fun(int)"<<endl; } template <typename T> void g(T* t){} template <typename T> void h(T t){} int main () { fun(nullptr); fun(0); char* cp = nullptr; // int n1 = nullptr; // int n2 = reinterpret_cast<int>(nullptr); nullptr_t nptr; if(nptr == nullptr){ cout<<"nullptr_t nptr == nullptr "<<endl; }else{ cout<<"nullptr_t nptr != nullptr"<<endl; } if (nptr < nullptr){ cout<<"nullptr_t nptr < nullptr"<<endl; }else{ cout<<"nullptr_t nptr !< nullptr"<<endl; } if (sizeof(nullptr_t) == sizeof(void*)){ cout<<" sizeof(nullptr_t) == sizeof(void*)"<<endl; } sizeof(nullptr); typeid(nullptr); // throw(nullptr); g(nullptr); g((float*) nullptr); h(0); h(nullptr); h((float*) nullptr); return 0; }
0607da635100c9ba32178cc1578dc3cd8dc5b2cd
f3a729d3588f6c31975d44b37f1b3a29c01db3cd
/812A.cpp
96814de62e1022b61057b1990a1e05b8570b026e
[]
no_license
yongwhan/codeforces
887e7cca0b47aa2ba65b1133300c63a808a15590
aa8fa27ca1a07fcb7f9dac5b1ce908b7bfcd49e2
refs/heads/master
2020-11-28T01:47:52.239077
2019-12-23T04:16:29
2019-12-23T04:16:29
229,671,486
0
0
null
2019-12-23T04:05:28
2019-12-23T03:43:38
C++
UTF-8
C++
false
false
301
cpp
#include<iostream> using namespace std; int main(){ int l[4],s[4],r[4],p[4]; for (int i=0; i<4; i++) cin>>l[i]>>s[i]>>r[i]>>p[i]; for (int i=0; i<4; i++) if (p[i]&&(l[i]||s[i]||r[i]||r[(i+3)%4]||s[(i+2)%4]||l[(i+1)%4])) { cout << "YES" << endl; return 0; } cout << "NO" << endl; return 0; }
9c0e1581442e92d830ba0c2d9254f32fad3e93ab
bf7a9ee52c1c1ae00827eea5a71960bd354c2dac
/NVGame.cpp
49f445a0935792f397418e9cbfb54d031e5b86c2
[]
no_license
RYAN9528221/FFMPEG-MUX-audio-and-video
cbbf38afb5a40948613b8c51d877fc5b7a56d136
d0aaf34af3faea4722a3f84386b605ac7082c06c
refs/heads/master
2021-03-01T04:35:01.789430
2020-03-08T05:13:03
2020-03-08T05:13:03
245,754,297
4
1
null
null
null
null
UTF-8
C++
false
false
37,634
cpp
#include<opencv.hpp> #include<highgui.hpp> #include"screen_record.h" #include <SDKDDKVer.h> #include <stdio.h> #include <tchar.h> #include <string> #include <process.h> //#define USE_FILTER // TODO: 婓森揭竘蚚最唗剒猁腔坻芛恅璃 #include <Windows.h> #pragma comment(lib, "Winmm.lib") #include <dshow.h> #pragma comment(lib, "Strmiids.lib") #define __STDC_CONSTANT_MACROS #include"screen_record.h" using namespace cv; using namespace dnn; #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <libavutil/avassert.h> #include <libavutil/channel_layout.h> #include <libavutil/opt.h> #include <libavutil/mathematics.h> #include <libavutil/timestamp.h> #include <libavformat/avformat.h> #include <libswscale/swscale.h> #include <libswresample/swresample.h> #define STREAM_DURATION 18//大約19秒 #define STREAM_FRAME_RATE 30 /* 25 images/s */ #define STREAM_PIX_FMT AV_PIX_FMT_YUV420P /* default pix_fmt */ #define SCALE_FLAGS SWS_BICUBIC #define av_ts2str(ts) av_ts_make_string((char[AV_TS_MAX_STRING_SIZE]){0}, ts) // a wrapper around a single output AVStream AVFormatContext* video_ctx = NULL;//....................新增變數 AVFormatContext* audio_ctx = NULL;//....................新增變數 int video_index(0); int audio_index(0); //==================== //插入式廣告 Mat frameAdvertising; VideoCapture cap; //==================== typedef struct OutputStream { AVStream* st; AVCodecContext* enc; /* pts of the next frame that will be generated */ int64_t next_pts; int samples_count; AVFrame* frame; AVFrame* tmp_frame; float t, tincr, tincr2; struct SwsContext* sws_ctx;//video struct SwrContext* swr_ctx;//audio } OutputStream; static void log_packet(const AVFormatContext* fmt_ctx, const AVPacket* pkt) { AVRational* time_base = &fmt_ctx->streams[pkt->stream_index]->time_base; /* printf("pts:%s pts_time:%s dts:%s dts_time:%s duration:%s duration_time:%s stream_index:%d\n", av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, time_base), av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, time_base), av_ts2str(pkt->duration), av_ts2timestr(pkt->duration, time_base), pkt->stream_index); */ } static int write_frame(AVFormatContext* fmt_ctx, const AVRational* time_base, AVStream* st, AVPacket* pkt) { /* rescale output packet timestamp values from codec to stream timebase */ av_packet_rescale_ts(pkt, *time_base, st->time_base); pkt->stream_index = st->index; /* Write the compressed frame to the media file. */ log_packet(fmt_ctx, pkt); return av_interleaved_write_frame(fmt_ctx, pkt); } /* Add an output stream. */ static void add_stream(OutputStream* ost, AVFormatContext* oc,AVCodec** codec,enum AVCodecID codec_id) { AVCodecContext* c; int i; //設定編碼器 *codec = avcodec_find_encoder(codec_id); if (!(*codec)) { fprintf(stderr, "Could not find encoder for '%s'\n", avcodec_get_name(codec_id)); exit(1); } ost->st = avformat_new_stream(oc, NULL); if (!ost->st) { fprintf(stderr, "Could not allocate stream\n"); exit(1); } ost->st->id = oc->nb_streams - 1; c = avcodec_alloc_context3(*codec); if (!c) { fprintf(stderr, "Could not alloc an encoding context\n"); exit(1); } ost->enc = c; switch ((*codec)->type) { case AVMEDIA_TYPE_AUDIO: c->sample_fmt = (*codec)->sample_fmts ?(*codec)->sample_fmts[0] : AV_SAMPLE_FMT_FLTP; c->bit_rate = 64000; c->sample_rate = 44100; if ((*codec)->supported_samplerates) { c->sample_rate = (*codec)->supported_samplerates[0]; for (i = 0; (*codec)->supported_samplerates[i]; i++) { if ((*codec)->supported_samplerates[i] == 44100) c->sample_rate = 44100; } } c->channels = av_get_channel_layout_nb_channels(c->channel_layout); c->channel_layout = AV_CH_LAYOUT_STEREO; if ((*codec)->channel_layouts) { c->channel_layout = (*codec)->channel_layouts[0]; for (i = 0; (*codec)->channel_layouts[i]; i++) { if ((*codec)->channel_layouts[i] == AV_CH_LAYOUT_STEREO) c->channel_layout = AV_CH_LAYOUT_STEREO; } } c->channels = av_get_channel_layout_nb_channels(c->channel_layout); ost->st->time_base = AVRational{ 1, c->sample_rate }; break; case AVMEDIA_TYPE_VIDEO: c->codec_id = codec_id; c->bit_rate = 400000; //解析度設定(必需為2的倍數) c->width = 1920; c->height =1080; // timebase: 這是基本時間單位(以秒為單位)表示其中的幀時間戳。 對於固定fps內容 //時基應為1 / framerate,時間戳增量應為1 ost->st->time_base = AVRational{ 1, STREAM_FRAME_RATE }; c->time_base = ost->st->time_base; c->gop_size = 12; /* emit one intra frame every twelve frames at most */ c->pix_fmt = STREAM_PIX_FMT; if (c->codec_id == AV_CODEC_ID_MPEG2VIDEO) { /* just for testing, we also add B-frames */ c->max_b_frames = 2; } if (c->codec_id == AV_CODEC_ID_MPEG1VIDEO) { //需要避免使用其中一些係數溢出的宏塊。 //普通視頻不會發生這種情況,因為 //色度平面的運動與亮度平面不匹配。 c->mb_decision = 2; } break; default: break; } //某些格式希望流頭分開 if (oc->oformat->flags & AVFMT_GLOBALHEADER) { c->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; } return; } /**************************************************************/ /* audio output */ static AVFrame* alloc_audio_frame(enum AVSampleFormat sample_fmt, uint64_t channel_layout, int sample_rate, int nb_samples) { AVFrame* frame = av_frame_alloc(); int ret; if (!frame) { fprintf(stderr, "Error allocating an audio frame\n"); exit(1); } frame->format = sample_fmt; frame->channel_layout = channel_layout; frame->sample_rate = sample_rate; frame->nb_samples = nb_samples; if (nb_samples) { ret = av_frame_get_buffer(frame, 0); if (ret < 0) { fprintf(stderr, "Error allocating an audio buffer\n"); exit(1); } } return frame; } static void open_audio(AVFormatContext* oc, AVCodec* codec, OutputStream* ost, AVDictionary* opt_arg) { AVCodecContext* c; int nb_samples; int ret; AVDictionary* opt = NULL; c = ost->enc; /* open it */ av_dict_copy(&opt, opt_arg, 0); ret = avcodec_open2(c, codec, &opt); av_dict_free(&opt); if (ret < 0) { //fprintf(stderr, "Could not open audio codec: %s\n", av_err2str(ret)); exit(1); } /* init signal generator */ ost->t = 0; ost->tincr = 2 * M_PI * 220 / c->sample_rate; /* increment frequency by 110 Hz per second */ ost->tincr2 = 2 * M_PI * 220 / c->sample_rate / c->sample_rate; if (c->codec->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE) nb_samples = 10000; else nb_samples = c->frame_size; ost->frame = alloc_audio_frame(c->sample_fmt, c->channel_layout, c->sample_rate, nb_samples); ost->tmp_frame = alloc_audio_frame(AV_SAMPLE_FMT_S16, c->channel_layout, c->sample_rate, nb_samples); /* copy the stream parameters to the muxer */ ret = avcodec_parameters_from_context(ost->st->codecpar, c); if (ret < 0) { fprintf(stderr, "Could not copy the stream parameters\n"); exit(1); } /* create resampler context */ ost->swr_ctx = swr_alloc(); if (!ost->swr_ctx) { fprintf(stderr, "Could not allocate resampler context\n"); exit(1); } /* set options */ av_opt_set_int(ost->swr_ctx, "in_channel_count", c->channels, 0); av_opt_set_int(ost->swr_ctx, "in_sample_rate", c->sample_rate, 0); //av_opt_set_sample_fmt(ost->swr_ctx, "in_sample_fmt", AV_SAMPLE_FMT_S16, 0); av_opt_set_sample_fmt(ost->swr_ctx, "in_sample_fmt", AV_SAMPLE_FMT_FLTP, 0); av_opt_set_int(ost->swr_ctx, "out_channel_count", c->channels, 0); av_opt_set_int(ost->swr_ctx, "out_sample_rate", c->sample_rate, 0); av_opt_set_sample_fmt(ost->swr_ctx, "out_sample_fmt", c->sample_fmt, 0); ///初始化重採樣編碼器 if ((ret = swr_init(ost->swr_ctx)) < 0) { fprintf(stderr, "Failed to initialize the resampling context\n"); exit(1); } } /* Prepare a 16 bit dummy audio frame of 'frame_size' samples and * 'nb_channels' channels. */ static AVFrame* get_audio_frame(OutputStream* ost) { AVFrame* frame = ost->tmp_frame; int j, i, v; int16_t* q = (int16_t*)frame->data[0]; AVFrame* frameRead = av_frame_alloc(); AVPacket packet; while (1) { int ret = av_read_frame(audio_ctx, &packet); int got_picture; if (packet.stream_index == audio_index) { ret = avcodec_decode_audio4(audio_ctx->streams[audio_index]->codec, frameRead, &got_picture, &packet); if (!got_picture) { continue; } else { break; } } } //判斷是否還要繼續產生像 if (av_compare_ts(ost->next_pts, ost->enc->time_base, STREAM_DURATION, AVRational{ 1, 1 }) > 0) return NULL; frameRead->pts = ost->next_pts; ost->next_pts += frameRead->nb_samples; ost->tmp_frame = frameRead; return frameRead; int16_t* q2 = (int16_t*)frameRead->data[0]; //int16_t* q3 = (int16_t*)frameRead->data[1]; //判斷是否還要繼續產生像 if (av_compare_ts(ost->next_pts, ost->enc->time_base,STREAM_DURATION, AVRational { 1, 1 }) > 0) return NULL; for (j = 0; j < frame->nb_samples; j++) { v = (int)(sin(ost->t) * 100000); for (i = 0; i < ost->enc->channels; i++) { //*q++ = v; *q++ = *q2++; //*q++ = *q3++; } ost->t -= 0.1*ost->tincr; ost->tincr += ost->tincr2;//降頻 } printf("%.2lf\n", ost->t); frame->pts = ost->next_pts; ost->next_pts += frame->nb_samples; return frame; } /* * encode one audio frame and send it to the muxer * return 1 when encoding is finished, 0 otherwise */ static int write_audio_frame(AVFormatContext* oc, OutputStream* ost) { AVCodecContext* c; AVPacket pkt = { 0 }; // data and size must be 0; AVFrame* frame; int ret; int got_packet; int dst_nb_samples; av_init_packet(&pkt); c = ost->enc; frame = get_audio_frame(ost); if (frame) { //使用重採樣器將樣本從本機格式轉換為目標編解碼器格式 dst_nb_samples = av_rescale_rnd(swr_get_delay(ost->swr_ctx, c->sample_rate) + frame->nb_samples,c->sample_rate, c->sample_rate, AV_ROUND_UP); av_assert0(dst_nb_samples == frame->nb_samples); /* when we pass a frame to the encoder, it may keep a reference to it * internally; * make sure we do not overwrite it here */ ret = av_frame_make_writable(ost->frame); if (ret < 0) exit(1); /* convert to destination format */ ret = swr_convert(ost->swr_ctx,ost->frame->data, dst_nb_samples,(const uint8_t**)frame->data, frame->nb_samples); if (ret < 0) { fprintf(stderr, "Error while converting\n"); exit(1); } frame = ost->frame; frame->pts = av_rescale_q(ost->samples_count, AVRational{1, c->sample_rate}, c->time_base); ost->samples_count += dst_nb_samples; } ret = avcodec_encode_audio2(c, &pkt, frame, &got_packet); if (ret < 0) { //fprintf(stderr, "Error encoding audio frame: %s\n", av_err2str(ret)); exit(1); } if (got_packet) { ret = write_frame(oc, &c->time_base, ost->st, &pkt); if (ret < 0) { //fprintf(stderr, "Error while writing audio frame: %s\n",av_err2str(ret)); exit(1); } } return (frame || got_packet) ? 0 : 1; } /**************************************************************/ /* video output */ static AVFrame* alloc_picture(enum AVPixelFormat pix_fmt, int width, int height) { AVFrame* picture; int ret; picture = av_frame_alloc(); if (!picture) return NULL; picture->format = pix_fmt; picture->width = width; picture->height = height; /* allocate the buffers for the frame data */ ret = av_frame_get_buffer(picture, 32); if (ret < 0) { fprintf(stderr, "Could not allocate frame data.\n"); exit(1); } return picture; } static void open_video(AVFormatContext* oc, AVCodec* codec, OutputStream* ost, AVDictionary* opt_arg) { int ret; AVCodecContext* c = ost->enc; AVDictionary* opt = NULL; av_dict_copy(&opt, opt_arg, 0); /* open the codec */ ret = avcodec_open2(c, codec, &opt); av_dict_free(&opt); if (ret < 0) { //fprintf(stderr, "Could not open video codec: %s\n", av_err2str(ret)); exit(1); } /* allocate and init a re-usable frame */ ost->frame = alloc_picture(c->pix_fmt, c->width, c->height); if (!ost->frame) { fprintf(stderr, "Could not allocate video frame\n"); exit(1); } /* If the output format is not YUV420P, then a temporary YUV420P * picture is needed too. It is then converted to the required * output format. */ ost->tmp_frame = NULL; if (c->pix_fmt != AV_PIX_FMT_YUV420P) { ost->tmp_frame = alloc_picture(AV_PIX_FMT_YUV420P, c->width, c->height); if (!ost->tmp_frame) { fprintf(stderr, "Could not allocate temporary picture\n"); exit(1); } } /* copy the stream parameters to the muxer */ ret = avcodec_parameters_from_context(ost->st->codecpar, c); if (ret < 0) { fprintf(stderr, "Could not copy the stream parameters\n"); exit(1); } } /* Prepare a dummy image. */ static void fill_yuv_image(AVFrame* pict, int frame_index,int width, int height) { int x, y, i; i = frame_index; /* Y */ for (y = 0; y < height; y++) for (x = 0; x < width; x++) pict->data[0][y * pict->linesize[0] + x] = x + y + i * 3; /* // Cb and Cr for (y = 0; y < height / 2; y++) { for (x = 0; x < width / 2; x++) { pict->data[1][y * pict->linesize[1] + x] = 128 + y + i * 2; pict->data[2][y * pict->linesize[2] + x] = 64 + x + i * 5; } } */ } static AVFrame* get_video_frame(OutputStream* ost) { AVCodecContext* c_ctx = ost->enc; //判斷是否還要繼續產生影片 if (av_compare_ts(ost->next_pts, c_ctx->time_base, STREAM_DURATION, AVRational{ 1, 1 }) > 0) { return NULL; } /* when we pass a frame to the encoder, it may keep a reference to it * internally; make sure we do not overwrite it here */ if (av_frame_make_writable(ost->frame) < 0) exit(1); if (c_ctx->pix_fmt != AV_PIX_FMT_YUV420P) { /* as we only generate a YUV420P picture, we must convert it * to the codec pixel format if needed */ if (!ost->sws_ctx) { ost->sws_ctx = sws_getContext(c_ctx->width, c_ctx->height, AV_PIX_FMT_YUV420P, c_ctx->width, c_ctx->height, c_ctx->pix_fmt, SCALE_FLAGS, NULL, NULL, NULL); if (!ost->sws_ctx) { fprintf(stderr,"Could not initialize the conversion context\n"); exit(1); } } fill_yuv_image(ost->tmp_frame, ost->next_pts, c_ctx->width, c_ctx->height); sws_scale(ost->sws_ctx, (const uint8_t* const*)ost->tmp_frame->data,ost->tmp_frame->linesize, 0, c_ctx->height, ost->frame->data,ost->frame->linesize); } else { //fill_yuv_image(ost->frame, ost->next_pts, c_ctx->width, c_ctx->height); AVFrame* pict = ost->frame; int x, y, i; i = ost->next_pts; Mat img = imread("mask.bmp"); int nChannels = img.channels(); int stepWidth = img.step; uchar* pData = img.ptr(0); cap.read(frameAdvertising);//廣告 if (frameAdvertising.data) { cv::resize(frameAdvertising, frameAdvertising, cv::Size(418, 544)); frameAdvertising.copyTo(img(cv::Rect(840, 130, frameAdvertising.cols, frameAdvertising.rows))); } /* Y */ int index; for (int row = 0; row < pict->height; row++) { for (int col = 0; col < pict->width; col++) { double R = (*(pData + row * stepWidth + col * nChannels + 2)); double G = (*(pData + row * stepWidth + col * nChannels + 1)); double B = (*(pData + row * stepWidth + col * nChannels )); pict->data[0][row * pict->linesize[0] + col] = 0.257 * R + 0.504 * G + 0.098 * B + 16; } } // Cb and Cr for (int row = 0; row < pict->height / 2; row++) { for (int col = 0; col < pict->width / 2; col++) { double R = (*(pData + row * stepWidth * 2 + col * nChannels * 2 + 2)); double G= (*(pData + row * stepWidth * 2 + col * nChannels * 2 + 1)); double B = (*(pData + row * stepWidth * 2 + col * nChannels * 2 )); double Y = 0.257 * R + 0.504 * G + 0.098 * B + 16; pict->data[1][row * pict->linesize[1] + col] = -0.148 * R - 0.291 * G + 0.439 * B + 128; pict->data[2][row * pict->linesize[2] + col] = 0.439 * R - 0.368 * G - 0.071 * B + 128; } } /* // Y for (int row = 0; row < pict->height; row++) for (int col = 0; col < pict->width; col++) pict->data[0][row * pict->linesize[0] + col] = 0.299 * (*(pData + row * stepWidth + col * nChannels + 2)) + 0.587 * (*(pData + row * stepWidth + col * nChannels + 1)) + 0.114 * (*(pData + row * stepWidth + col * nChannels + 0)); //CB for (int row = 0; row < pict->height/2; row++) for (int col = 0; col < pict->width/2; col++) pict->data[1][row * pict->linesize[1] + col] = -0.168 * (*(pData + row * stepWidth*2 + col * nChannels * 2 + 2)) + -0.3316 * (*(pData + row * stepWidth * 2 + col * nChannels * 2 + 1)) + 0.5 * (*(pData + row * stepWidth * 2 + col * nChannels * 2 + 0)); //CR for (int row = 0; row < pict->height/2; row++) for (int col = 0; col < pict->width/2; col++) pict->data[2][row * pict->linesize[2] + col] = 0.4 * (*(pData + row * stepWidth * 2 + col * nChannels * 2 + 2)) + -0.4 * (*(pData + row * stepWidth * 2 + col * nChannels * 2 + 1)) + -0.08 * (*(pData + row * stepWidth * 2 + col * nChannels * 2 + 0)); */ /* //Cb and Cr for (int row = 0; row < height / 2; y++) { for (x = 0; x < width / 2; x++) { pict->data[1][y * pict->linesize[1] + x] = *(pData + row * stepWidth + col * nChannels + 0); pict->data[2][y * pict->linesize[2] + x] = *(pData + row * stepWidth + col * nChannels + 0); } } */ struct SwsContext* img_convert_ctx2 = NULL; int stream_index(0); int w = pict->width; int h = pict->height; img_convert_ctx2 = sws_getContext(w, h, AV_PIX_FMT_RGB24, w, h, AV_PIX_FMT_YUV420P, SWS_FAST_BILINEAR, NULL, NULL, NULL); //sws_scale(img_convert_ctx2, pict->data, pict->linesize, 0, pict->height, pict->data, pict->linesize); } ost->frame->pts = ost->next_pts++; return ost->frame; } //=================================================================== //編碼一個視頻幀並將其發送到多路復用器 //編碼完成後返回1,否則返回0 static int write_video_frame(AVFormatContext* oc, OutputStream* ost) { int ret; AVCodecContext* c; AVFrame* frame; int got_packet = 0; AVPacket pkt = { 0 }; c = ost->enc; frame = get_video_frame(ost);//影片擷取竟然跟寫入放在一起...... av_init_packet(&pkt); //================================================================ //開始編碼到輸出Packet ret = avcodec_encode_video2(c, &pkt, frame, &got_packet); if (ret < 0) { printf("Error encoding video frame"); //(stderr, "Error encoding video frame: %s\n", av_err2str(ret)); exit(1); } if (got_packet) { ret = write_frame(oc, &c->time_base, ost->st, &pkt); } else { ret = 0; } if (ret < 0) { printf("Error while writing video frame"); //fprintf(stderr, "Error while writing video frame: %s\n", av_err2str(ret)); exit(1); } return (frame || got_packet) ? 0 : 1; } static void close_stream(AVFormatContext* oc, OutputStream* ost) { avcodec_free_context(&ost->enc); av_frame_free(&ost->frame); av_frame_free(&ost->tmp_frame); sws_freeContext(ost->sws_ctx); swr_free(&ost->swr_ctx); } static int open_input_file(const char* filename) { return 0; } Mat WaterData(AVFrame* pFrame, int W, int H) { int nChannels; int stepWidth; int width = W; int height = H; Mat frameImage = Mat::ones(cv::Size(W, H), CV_8UC3); uchar* pData = frameImage.ptr(0); stepWidth = frameImage.step; nChannels = frameImage.channels(); for (int row = 0; row < height; row++) { for (int col = 0; col < width; col++) { *(pData + row * stepWidth + col * nChannels + 0) = pFrame->data[0][row * pFrame->linesize[0] + col * nChannels + 2]; *(pData + row * stepWidth + col * nChannels + 1) = pFrame->data[0][row * pFrame->linesize[0] + col * nChannels + 1]; *(pData + row * stepWidth + col * nChannels + 2) = pFrame->data[0][row * pFrame->linesize[0] + col * nChannels + 0]; } } for (int row = 0; row < height; row++) { for (int col = 0; col < width; col++) { pFrame->data[0][row * pFrame->linesize[0] + col * nChannels + 2] = *(pData + row * stepWidth + col * nChannels + 0); pFrame->data[0][row * pFrame->linesize[0] + col * nChannels + 1] = *(pData + row * stepWidth + col * nChannels + 1); pFrame->data[0][row * pFrame->linesize[0] + col * nChannels + 0] = *(pData + row * stepWidth + col * nChannels + 2); } } return frameImage; } unsigned int __stdcall captrue_video(void* param); int main(int argc, char** argv) { //========================================== //插入式廣告: cap.open("chinapig.mp4"); if (!cap.isOpened()) { cerr << "ERROR! Unable to open camera\n"; return -1; } //========================================== int got_frame(0); bool b_UseGPUNVenc(false); //======================================= //AVFormatContext* video_ctx = NULL;//....................新增變數 //AVFormatContext* audio_ctx = NULL;//....................新增變數 AVFormatContext* out_ctx; //======================================= OutputStream video_st = { 0 }, audio_st = { 0 }; const char* out_filename = "NVRecord.mp4";//輸出檔案 AVOutputFormat* out_fmt; AVCodec* audio_Encoder, * video_Encoder;//編碼器 int ret; int have_video = 0, have_audio = 0; int encode_video = 0, encode_audio = 0; AVDictionary* opt = NULL; int i; //====================================================================== //1.OpenInoput讀取視頻資訊(開啟解碼器) video_index=(0); audio_index=(0); av_register_all(); avformat_network_init(); avdevice_register_all();//Registe if ((ret = avformat_open_input(&video_ctx, "123.mp4", NULL, NULL)) < 0) { av_log(NULL, AV_LOG_ERROR, "Cannot open input file\n"); return ret; } if ((ret = avformat_find_stream_info(video_ctx, NULL)) < 0) { av_log(NULL, AV_LOG_ERROR, "Cannot find stream information\n"); return ret; } for (i = 0; i < video_ctx->nb_streams; i++) { AVStream* stream; AVCodecContext* codec_ctx; stream = video_ctx->streams[i]; codec_ctx = stream->codec; /* Reencode video & audio and remux subtitles etc. */ if (codec_ctx->codec_type == AVMEDIA_TYPE_VIDEO) { video_index = i; /* Open decoder */ if (b_UseGPUNVenc) { ret = avcodec_open2(codec_ctx, avcodec_find_decoder_by_name("h264_cuvid"), NULL); if (!ret) { b_UseGPUNVenc = false; ret = avcodec_open2(codec_ctx, avcodec_find_decoder(codec_ctx->codec_id), NULL); } } else { ret = avcodec_open2(codec_ctx, avcodec_find_decoder(codec_ctx->codec_id), NULL); } if (ret < 0) { av_log(NULL, AV_LOG_ERROR, "Failed to open decoder for stream #%u\n", i); return ret; } } } av_dump_format(video_ctx, 0, "123.mp4", 0); //2.開啟音訊解碼器和影片 audio_ctx = NULL; av_register_all(); avdevice_register_all(); avfilter_register_all(); //AVInputFormat* ifmt = av_find_input_format("dshow"); //if ((ret = avformat_open_input(&audio_ctx, "audio=Stereo Mix (Realtek(R) Audio)", ifmt, NULL)) < 0) if ((ret = avformat_open_input(&audio_ctx, "123.mp4", NULL, NULL)) < 0) { av_log(NULL, AV_LOG_ERROR, "Cannot open input file\n"); return ret; } if ((ret = avformat_find_stream_info(audio_ctx, NULL)) < 0) { av_log(NULL, AV_LOG_ERROR, "Cannot find stream information\n"); return ret; } for (i = 0; i < audio_ctx->nb_streams; i++) { AVStream* stream; AVCodecContext* codec_ctx; stream = audio_ctx->streams[i]; codec_ctx = stream->codec; /* Reencode video & audio and remux subtitles etc. */ if (codec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) { audio_index = i; /* Open decoder */ ret = avcodec_open2(codec_ctx,avcodec_find_decoder(codec_ctx->codec_id), NULL); if (ret < 0) { av_log(NULL, AV_LOG_ERROR, "Failed to open decoder for stream #%u\n", i); return ret; } } } av_dump_format(audio_ctx, 0, "123.mp4", 0); _beginthreadex(NULL, 0, captrue_video, NULL, 0, NULL);//影片可以開始先解碼了 //試試看解碼 /* struct SwsContext* img_convert_ctx = NULL; struct SwsContext* img_convert_ctx2 = NULL; int stream_index(0); int w = video_ctx->streams[stream_index]->codec->width; int h = video_ctx->streams[stream_index]->codec->height; img_convert_ctx = sws_getContext(w, h, video_ctx->streams[stream_index]->codec->pix_fmt, w, h, AV_PIX_FMT_RGB24, 4, NULL, NULL, NULL); img_convert_ctx2 = sws_getContext(w, h, AV_PIX_FMT_RGB24, w, h, AV_PIX_FMT_YUV420P, SWS_FAST_BILINEAR, NULL, NULL, NULL); AVPacket packet; enum AVMediaType type; while (ret >= 0) { ret = av_read_frame(video_ctx, &packet); stream_index = packet.stream_index; type = video_ctx->streams[packet.stream_index]->codec->codec_type; av_log(NULL, AV_LOG_DEBUG, "Demuxer gave frame of stream_index %u\n", stream_index); if (type == AVMEDIA_TYPE_VIDEO) { av_log(NULL, AV_LOG_DEBUG, "Going to reencode&filter the frame\n"); AVFrame* frame = av_frame_alloc(); if (!frame) { ret = AVERROR(ENOMEM); break; } av_packet_rescale_ts(&packet, video_ctx->streams[stream_index]->time_base, video_ctx->streams[stream_index]->codec->time_base); ret = avcodec_decode_video2(video_ctx->streams[stream_index]->codec, frame, &got_frame, &packet); if (ret < 0) { av_frame_free(&frame); av_log(NULL, AV_LOG_ERROR, "Decoding failed\n"); break; } if (got_frame) { AVFrame* pFrameRGB = av_frame_alloc(); int numBytes = avpicture_get_size(AV_PIX_FMT_RGB24, video_ctx->streams[stream_index]->codec->width, video_ctx->streams[stream_index]->codec->height);// Determine required buffer size and allocate buffer uint8_t* H264_out_buffer = (uint8_t*)av_malloc(numBytes * sizeof(uint8_t)); avpicture_fill((AVPicture*)pFrameRGB, H264_out_buffer, AV_PIX_FMT_RGB24, video_ctx->streams[stream_index]->codec->width, video_ctx->streams[stream_index]->codec->height);// Assign appropriate parts of buffer to image planes in pFrameRGB sws_scale(img_convert_ctx, frame->data, frame->linesize, 0, video_ctx->streams[stream_index]->codec->height, pFrameRGB->data, pFrameRGB->linesize); //Inference here: Mat img=WaterData(pFrameRGB, video_ctx->streams[stream_index]->codec->width, video_ctx->streams[stream_index]->codec->height); imshow("1", img); waitKey(1); } } }*/ //=============================================================================================== //3.設置輸出OpenOut: avformat_alloc_output_context2(&out_ctx, NULL, NULL, out_filename);//MP4的輸出類型 if (!out_ctx) { printf("Could not deduce output format from file extension: using MPEG.\n"); avformat_alloc_output_context2(&out_ctx, NULL, "mpeg", out_filename); } if (!out_ctx) { return 1; } out_fmt = out_ctx->oformat; //==================================================================== //3.設定編碼器(視頻) //視頻流(video_st) if (out_fmt->video_codec != AV_CODEC_ID_NONE) { //========================================= //用來告訴輸出端的輸入流 AVStream* in_stream; in_stream = video_ctx->streams[video_index]; AVCodecContext* dec_ctx= in_stream->codec; //========================================= //add_stream(&video_st, out_ctx, &video_Encoder, out_fmt->video_codec); //static void add_stream(OutputStream* ost, AVFormatContext* oc, AVCodec** codec, enum AVCodecID codec_id) AVCodecContext* c; int i; video_Encoder = avcodec_find_encoder(out_fmt->video_codec); if (!(video_Encoder)) { fprintf(stderr, "Could not find encoder for '%s'\n", avcodec_get_name(out_fmt->video_codec)); exit(1); } video_st.st = avformat_new_stream(out_ctx, NULL); if (!video_st.st) { fprintf(stderr, "Could not allocate stream\n"); exit(1); } video_st.st->id = out_ctx->nb_streams - 1; c = avcodec_alloc_context3(video_Encoder); if (!c) { fprintf(stderr, "Could not alloc an encoding context\n"); exit(1); } video_st.enc = c; //=========================================================================== //SWITCH內: c->codec_id = out_fmt->video_codec; c->bit_rate = dec_ctx->bit_rate; //解析度設定(必需為2的倍數) //c->width = dec_ctx->width; //c->height = dec_ctx->height; c->width = 1280; c->height = 720; // timebase: 這是基本時間單位(以秒為單位)表示其中的幀時間戳。 對於固定fps內容 //時基應為1 / framerate,時間戳增量應為1 //video_st.st->time_base = dec_ctx->time_base;//每秒60禎: {1001,6000} video_st.st->time_base = AVRational{ 1, STREAM_FRAME_RATE };//每秒多少楨 //video_st.st->time_base = AVRational{ 1, 30 }; c->time_base = video_st.st->time_base; c->gop_size = 12; /* emit one intra frame every twelve frames at most */ c->pix_fmt = STREAM_PIX_FMT; if (c->codec_id == AV_CODEC_ID_MPEG2VIDEO) { /* just for testing, we also add B-frames */ c->max_b_frames = 2; } if (c->codec_id == AV_CODEC_ID_MPEG1VIDEO) { //需要避免使用其中一些係數溢出的宏塊。 //普通視頻不會發生這種情況,因為 //色度平面的運動與亮度平面不匹配。 c->mb_decision = 2; } if (c->codec_id == AV_CODEC_ID_H264) { c->me_range = 1; c->max_qdiff = 3; c->qmin = 1; c->qmax = 20; c->qcompress = 0.9; c->noise_reduction = 0; } //=========================================================================== //某些格式希望流頭分開 if (out_ctx->oformat->flags & AVFMT_GLOBALHEADER) { c->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; } have_video = 1; encode_video = 1; } //============================================================================================================ //4.設定編碼器(音頻) if (out_fmt->audio_codec != AV_CODEC_ID_NONE) { //========================================= //用來告訴輸出端的輸入流 AVStream* in_stream; in_stream = audio_ctx->streams[audio_index];//聲音部分 AVCodecContext* dec_ctx = in_stream->codec; //========================================= //add_stream(&audio_st, out_ctx, &audio_Encoder, out_fmt->audio_codec); //static void add_stream(OutputStream* ost, AVFormatContext* oc, AVCodec** codec, enum AVCodecID codec_id) AVCodecContext* c; int i; //設定編碼器 audio_Encoder = avcodec_find_encoder(out_fmt->audio_codec); if (!(audio_Encoder)) { fprintf(stderr, "Could not find encoder for '%s'\n",avcodec_get_name(out_fmt->audio_codec)); exit(1); } audio_st.st = avformat_new_stream(out_ctx, NULL); if (!audio_st.st) { fprintf(stderr, "Could not allocate stream\n"); exit(1); } audio_st.st->id = out_ctx->nb_streams - 1; c = avcodec_alloc_context3(audio_Encoder); if (!c) { fprintf(stderr, "Could not alloc an encoding context\n"); exit(1); } audio_st.enc = c; //=========================================================================== //SWITCH內: c->sample_fmt = (audio_Encoder)->sample_fmts ? (audio_Encoder)->sample_fmts[0] : AV_SAMPLE_FMT_FLTP; c->bit_rate = dec_ctx->bit_rate;//128000 64000 //c->bit_rate = 12800; c->sample_rate = dec_ctx->sample_rate;//44100 if ((audio_Encoder)->supported_samplerates) { c->sample_rate = (audio_Encoder)->supported_samplerates[0]; for (i = 0; (audio_Encoder)->supported_samplerates[i]; i++) { if ((audio_Encoder)->supported_samplerates[i] == 44100) { c->sample_rate = 44100; } } } c->channels = av_get_channel_layout_nb_channels(c->channel_layout); c->channel_layout = AV_CH_LAYOUT_STEREO; if ((audio_Encoder)->channel_layouts) { c->channel_layout = (audio_Encoder)->channel_layouts[0]; for (i = 0; (audio_Encoder)->channel_layouts[i]; i++) { if ((audio_Encoder)->channel_layouts[i] == AV_CH_LAYOUT_STEREO) c->channel_layout = AV_CH_LAYOUT_STEREO; } } c->channels = av_get_channel_layout_nb_channels(c->channel_layout); audio_st.st->time_base = AVRational{ 1, c->sample_rate }; //=========================================================================== //某些格式希望流頭分開 if (out_ctx->oformat->flags & AVFMT_GLOBALHEADER) { c->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; } have_audio = 1; encode_audio = 1; } //現在已經設置了所有參數,我們可以打開音頻並 //正式打開視頻編解碼器(avcodec_open2),並分配必要的編碼緩衝區。 if (have_video) { open_video(out_ctx, video_Encoder, &video_st, opt); } if (have_audio) { open_audio(out_ctx, audio_Encoder, &audio_st, opt); } av_dump_format(out_ctx, 0, out_filename, 1); /* open the output file, if needed */ if (!(out_fmt->flags & AVFMT_NOFILE)) { ret = avio_open(&out_ctx->pb, out_filename, AVIO_FLAG_WRITE); if (ret < 0) { //fprintf(stderr, "Could not open '%s': %s\n", filename,av_err2str(ret)); return 1; } } //===================================================================================== //寫入輸出檔案的檔頭 ret = avformat_write_header(out_ctx, &opt); if (ret < 0) { //fprintf(stderr, "Error occurred when opening output file: %s\n",av_err2str(ret)); return 1; } //===================================================================================== while (encode_video || encode_audio) { /* select the stream to encode */ if (encode_video &&(!encode_audio || av_compare_ts(video_st.next_pts, video_st.enc->time_base,audio_st.next_pts, audio_st.enc->time_base) <= 0)) { encode_video = !write_video_frame(out_ctx, &video_st);//寫入影片 } else { encode_audio = !write_audio_frame(out_ctx, &audio_st);//寫入聲音 } } av_write_trailer(out_ctx); /* Close each codec. */ if (have_video) close_stream(out_ctx, &video_st); if (have_audio) close_stream(out_ctx, &audio_st); if (!(out_fmt->flags & AVFMT_NOFILE)) /* Close the output file. */ avio_closep(&out_ctx->pb); /* free the stream */ avformat_free_context(out_ctx); return 0; } unsigned int __stdcall captrue_video(void* param) { return 0; int ret(0); int got_frame(0); struct SwsContext* img_convert_ctx = NULL; struct SwsContext* img_convert_ctx2 = NULL; int stream_index(0); int w = video_ctx->streams[stream_index]->codec->width; int h = video_ctx->streams[stream_index]->codec->height; img_convert_ctx = sws_getContext(w, h, video_ctx->streams[stream_index]->codec->pix_fmt, w, h, AV_PIX_FMT_RGB24, 4, NULL, NULL, NULL); img_convert_ctx2 = sws_getContext(w, h, AV_PIX_FMT_RGB24, w, h, AV_PIX_FMT_YUV420P, SWS_FAST_BILINEAR, NULL, NULL, NULL); AVPacket packet; enum AVMediaType type; while (ret >= 0) { ret = av_read_frame(video_ctx, &packet); stream_index = packet.stream_index; type = video_ctx->streams[packet.stream_index]->codec->codec_type; av_log(NULL, AV_LOG_DEBUG, "Demuxer gave frame of stream_index %u\n", stream_index); if (type == AVMEDIA_TYPE_VIDEO) { av_log(NULL, AV_LOG_DEBUG, "Going to reencode&filter the frame\n"); AVFrame* frame = av_frame_alloc(); if (!frame) { ret = AVERROR(ENOMEM); break; } av_packet_rescale_ts(&packet,video_ctx->streams[stream_index]->time_base,video_ctx->streams[stream_index]->codec->time_base); ret = avcodec_decode_video2(video_ctx->streams[stream_index]->codec, frame, &got_frame, &packet); if (ret < 0) { av_frame_free(&frame); av_log(NULL, AV_LOG_ERROR, "Decoding failed\n"); break; } if (got_frame) { AVFrame* pFrameRGB = av_frame_alloc(); int numBytes = avpicture_get_size(AV_PIX_FMT_RGB24, video_ctx->streams[stream_index]->codec->width, video_ctx->streams[stream_index]->codec->height);// Determine required buffer size and allocate buffer uint8_t* H264_out_buffer = (uint8_t*)av_malloc(numBytes * sizeof(uint8_t)); avpicture_fill((AVPicture*)pFrameRGB, H264_out_buffer, AV_PIX_FMT_RGB24, video_ctx->streams[stream_index]->codec->width, video_ctx->streams[stream_index]->codec->height);// Assign appropriate parts of buffer to image planes in pFrameRGB sws_scale(img_convert_ctx, frame->data, frame->linesize, 0, video_ctx->streams[stream_index]->codec->height, pFrameRGB->data, pFrameRGB->linesize); //Inference here: Mat img = WaterData(pFrameRGB, video_ctx->streams[stream_index]->codec->width, video_ctx->streams[stream_index]->codec->height); imshow("1", img); waitKey(1); } } } return 0; }
8cc021468488fbe7848abc82977f6f4887a8653a
befc46a19f36d531e8ccd01418c01afc4f484f50
/test/generator/stubtest_generator.cpp
83ff4fc81ef0a8be61e773570f97da323baa177d
[ "MIT" ]
permissive
llhe/Halide
10dbb067f97c0045332b102ee1b827ca84d2af27
76e4ece926d845faaa3a048d207e402f374c5ac8
refs/heads/master
2021-08-08T11:44:39.459001
2017-11-09T15:16:55
2017-11-09T15:16:55
110,220,926
1
0
null
2017-11-10T08:13:41
2017-11-10T08:13:41
null
UTF-8
C++
false
false
3,903
cpp
#include "Halide.h" namespace { enum class BagType { Paper, Plastic }; template<typename Type, int size = 32, int dim = 3> Halide::Buffer<Type> make_image(int extra) { Halide::Buffer<Type> im(size, size, dim); for (int x = 0; x < size; x++) { for (int y = 0; y < size; y++) { for (int c = 0; c < dim; c++) { im(x, y, c) = static_cast<Type>(x + y + c + extra); } } } return im; } class StubTest : public Halide::Generator<StubTest> { public: GeneratorParam<Type> untyped_buffer_output_type{ "untyped_buffer_output_type", Float(32) }; GeneratorParam<float> float_param{ "float_param", 3.1415926535f }; GeneratorParam<BagType> bag_type{ "bag_type", BagType::Paper, { { "paper", BagType::Paper }, { "plastic", BagType::Plastic } } }; ScheduleParam<bool> vectorize{ "vectorize", true }; ScheduleParam<LoopLevel> intermediate_level{ "intermediate_level", LoopLevel::root() }; Input<Buffer<uint8_t>> typed_buffer_input{ "typed_buffer_input", 3 }; Input<Buffer<>> untyped_buffer_input{ "untyped_buffer_input" }; Input<Func> simple_input{ "simple_input", 3 }; // require a 3-dimensional Func but leave Type unspecified Input<Func[]> array_input{ "array_input", 3 }; // require a 3-dimensional Func but leave Type and ArraySize unspecified // Note that Input<Func> does not (yet) support Tuples Input<float> float_arg{ "float_arg", 1.0f, 0.0f, 100.0f }; Input<int32_t[]> int_arg{ "int_arg", 1 }; // leave ArraySize unspecified Output<Func> simple_output{ "simple_output", Float(32), 3}; Output<Func> tuple_output{"tuple_output", 3}; // require a 3-dimensional Func but leave Type(s) unspecified Output<Func[]> array_output{ "array_output", Int(16), 2}; // leave ArraySize unspecified Output<Buffer<float>> typed_buffer_output{ "typed_buffer_output" }; Output<Buffer<>> untyped_buffer_output{ "untyped_buffer_output" }; Output<Buffer<uint8_t>> static_compiled_buffer_output{ "static_compiled_buffer_output", 3 }; void generate() { simple_output(x, y, c) = cast<float>(simple_input(x, y, c)); typed_buffer_output(x, y, c) = cast<float>(typed_buffer_input(x, y, c)); // Note that if we are being invoked via a Stub, "untyped_buffer_output.type()" will // assert-fail, because there is no type constraint set: the type // will end up as whatever we infer from the values put into it. We'll use an // explicit GeneratorParam to allow us to set it. untyped_buffer_output(x, y, c) = cast(untyped_buffer_output_type, untyped_buffer_input(x, y, c)); // Gratuitous intermediate for the purpose of exercising // ScheduleParam<LoopLevel> intermediate(x, y, c) = simple_input(x, y, c) * float_arg; tuple_output(x, y, c) = Tuple( intermediate(x, y, c), intermediate(x, y, c) + int_arg[0]); array_output.resize(array_input.size()); for (size_t i = 0; i < array_input.size(); ++i) { array_output[i](x, y) = cast<int16_t>(array_input[i](x, y, 0) + int_arg[i]); } // This should be compiled into the Generator product itself, // and not produce another input for the Stub or AOT filter. Buffer<uint8_t> static_compiled_buffer = make_image<uint8_t>(42); static_compiled_buffer_output = static_compiled_buffer; } void schedule() { intermediate.compute_at(intermediate_level); intermediate.specialize(vectorize).vectorize(x, natural_vector_size<float>()); } private: Var x{"x"}, y{"y"}, c{"c"}; Func intermediate{"intermediate"}; }; } // namespace HALIDE_REGISTER_GENERATOR(StubTest, stubtest, StubNS1::StubNS2::StubTest)
79dc1d70a10a9f63159bf20d28e91b5b9aabbbc1
b757f878b35baa52d3ffb45d0361d8d08e55511b
/source/repos/The Game of Life 3D/The Game of Life 3D/The Game of Life 3D.cpp
c7eb54fdcdee28448415167d52ad4b4227909ec6
[]
no_license
IlyaPikin/The-Game-of-Life-3D
cd4f22ef15f8c246e6a0dc40b332a6fe1f886f03
d410bfe8750368a527028cfb017d5ef667214f78
refs/heads/master
2023-05-13T08:33:01.087836
2021-05-05T21:46:33
2021-05-05T21:46:33
364,716,077
0
0
null
null
null
null
UTF-8
C++
false
false
11,271
cpp
#include <iostream> #include <vector> #include <numeric> #include <algorithm> #include <random> #include <Windows.h> #include <conio.h> #include <time.h> using namespace std; COORD position; HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); struct iGame { int n=0, m=0, k=0; int seed = time(NULL); // случайная величина для генератора double probability=0; // вероятность того, что клетка живая virtual void runGame(int numIt) = 0; }; struct Game2d :iGame { char** field; char** fieldCopy; Game2d() {}; void setField() { field = new char* [n + 2]; fieldCopy = new char* [n + 2]; //поле копия for (int i = 0; i < n + 2; i++) { field[i] = new char[m + 2]; for (int j = 0; j < m + 2; j++) { if (i == 0 || i == n + 1 || j == 0 || j == m + 1) { field[i][j] = 'X'; } else { if (rand() % 100 <= probability*100) { field[i][j] = 'O'; } else { field[i][j] = '.'; } } } fieldCopy[i] = new char[m + 2]; //копия } } void draw() { for (int i = 0; i < n + 2; i++) { for (int j = 0; j < m + 2; j++) { position.X = i; position.Y = j; SetConsoleCursorPosition(hConsole, position); if (field[i][j] == 'X') { SetConsoleTextAttribute(hConsole, (WORD)((1 << 4) | 11)); putchar(field[i][j]); } else if (field[i][j] == 'O') { SetConsoleTextAttribute(hConsole, (WORD)((10 << 4) | 0)); putchar(field[i][j]); } else if (field[i][j] == '.') { SetConsoleTextAttribute(hConsole, (WORD)((1 << 4) | 6)); putchar(field[i][j]); } } } } int getCount(int x1, int y1) { int count = 0; for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { if (fieldCopy[x1 + i][y1 + j] == 'O') count++; } } return count; } void runGame(int numIt) override { srand(seed); setField(); system("cls"); draw(); Sleep(1000); // игра, проход numIt итераций for (int count = 0; count < numIt; count++) { // копирование поля for (int i = 0; i < n+2; i++) { for (int j = 0; j < m+2; j++) { fieldCopy[i][j] = field[i][j]; } } // анализ копии поля и заполнение основного поля for (int i = 1; i < n+1; i++) { for (int j = 1; j < m+1; j++) { if (fieldCopy[i][j] == 'O' && (getCount(i, j) == 3 || getCount(i, j) == 4)) { field[i][j] = 'O'; } else if (fieldCopy[i][j] == '.' && getCount(i, j) == 3) { field[i][j] = 'O'; } else { field[i][j] = '.'; } } } draw(); Sleep(100); } //draw(); } ~Game2d(){ for (int i = 0; i < n + 2; i++) { delete[] field[i]; delete[] fieldCopy[i]; } delete[] field; delete[] fieldCopy; } }; struct Game3d :iGame { char*** field; char*** fieldCopy; Game3d() {}; void setField() { field = new char** [n + 2]; fieldCopy = new char** [n + 2]; //поле копия for (int i = 0; i < n + 2; i++) { field[i] = new char*[m + 2]; fieldCopy[i] = new char* [m + 2]; //копия for (int j = 0; j < m + 2; j++) { field[i][j] = new char [k + 2]; fieldCopy[i][j] = new char [k + 2]; //копия for (int l=0; l < k+2; l++) { if (i == 0 || i == n + 1 || j == 0 || j == m + 1 || l==0 || l==k+1) { field[i][j][l] = 'X'; } else { if (rand() % 100 <= probability * 100) { field[i][j][l] = 'O'; } else { field[i][j][l] = '.'; } } } } } } void draw() { for (int z = 1; z < k + 1; z++) { for (int i = 0; i < n + 2; i++) { for (int j = 0; j < m + 2; j++) { position.X = j; position.Y = i + (n + 2) * (z - 1); // (n+2)*(z-1) - смещение по оси для отрисовки каждого отдельного слоя SetConsoleCursorPosition(hConsole, position); if (field[i][j][z] == 'X') { SetConsoleTextAttribute(hConsole, (WORD)((1 << 4) | 11)); putchar(field[i][j][z]); } else if (field[i][j][z] == 'O') { SetConsoleTextAttribute(hConsole, (WORD)((10 << 4) | 0)); putchar(field[i][j][z]); } else if (field[i][j][z] == '.') { SetConsoleTextAttribute(hConsole, (WORD)((1 << 4) | 6)); putchar(field[i][j][z]); } } } } } int getCount(int x1, int y1, int z1) { int count = 0; for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { for (int l = -1; l <= 1; l++) { if (fieldCopy[x1 + i][y1 + j][z1 + l] == 'O') count++; } } } return count; } void editing() { int x = 1, y = 1, z = 1; while (1) { char c = _getch(); if (c == 'a') { y = 1 + ((y - 1) - 1 + m) % m; } else if (c == 'd') { y = 1 + ((y - 1) + 1 + m) % m; } else if (c == 'w') { x = 1 + ((x - 1) - 1 + n) % n; } else if (c == 's') { x = 1 + ((x - 1) + 1 + n) % n; } else if (c=='e') { // e - вперёд по оси z z = 1+((z-1) + 1 + k) % k; } else if (c=='q') { // q - назад по оси z z = 1 + ((z-1) - 1 + k) % k; } else if (c == ' ' && (x >= 1) && (x <= n) && (y >= 1) && (y <= m) && z>=1 && z<=k) { if (field[x][y][z] == 'O') { field[x][y][z] = '.'; } else if (field[x][y][z] == '.') { field[x][y][z] = 'O'; } } else if (c == 13) // enter { break; } draw(); } } void runGame(int numIt) override { srand(seed); setField(); system("cls"); draw(); editing(); Sleep(1000); // игра, проход numIt итераций for (int count = 0; count < numIt; count++) { // копирование поля for (int i = 0; i < n + 2; i++) for (int j = 0; j < m + 2; j++) for(int l = 0; l < k + 2; l++) fieldCopy[i][j][l] = field[i][j][l]; // анализ копии поля и заполнение основного поля for (int i = 1; i < n + 1; i++) { for (int j = 1; j < m + 1; j++) { for (int l = 1; l < k + 1; l++) { if (fieldCopy[i][j][l] == 'O' && getCount(i, j, l) >= 6 && getCount(i, j, l) <= 11) { field[i][j][l] = 'O'; } else if (fieldCopy[i][j][l] == '.' && getCount(i, j, l) >= 7 && getCount(i, j, l) <= 9) { field[i][j][l] = 'O'; } else { field[i][j][l] = '.'; } } } } draw(); Sleep(100); } //draw(); } ~Game3d() { for (int i = 0; i < n + 2; i++) { for (int j = 0; j < m + 2; j++) { delete[] field[i][j]; delete[] fieldCopy[i][j]; } delete[] field[i]; delete[] fieldCopy[i]; } delete[] field; delete[] fieldCopy; } }; int main() { SetConsoleTitle(TEXT("The game of life")); system("color 1f"); setlocale(LC_ALL, "Russian"); cout << "__________Игра Жизнь__________" << endl<<"Выберете режим игры (WASD, ENTER):"; cout << endl << "1. 2D режим" << endl << "2. 3D режим"; position.X = 0; position.Y = 2; SetConsoleCursorPosition(hConsole, position); iGame* newGame = 0; while (1) { char c = _getch(); if (c == 'w') { position.Y = 2+(position.Y-1)%2; SetConsoleCursorPosition(hConsole, position); } else if (c == 's') { position.Y = 2 + (position.Y +1) % 2; SetConsoleCursorPosition(hConsole, position); } else if (c == 'a') { position.X = (position.X-1+11)%11; SetConsoleCursorPosition(hConsole, position); } else if (c == 'd') { position.X = (position.X + 1) % 11; SetConsoleCursorPosition(hConsole, position); } else if (c == 13) { if (position.Y==2) { newGame = new Game2d; system("cls"); cout << "__________Игра Жизнь__________" << endl << "Введите размеры поля:" << endl; cin >> newGame->n >> newGame->m; } else if (position.Y == 3) { newGame = new Game3d; system("cls"); cout << "__________Игра Жизнь__________" << endl << "Введите размеры поля:" << endl; cin >> newGame->n >> newGame->m >> newGame->k; } //SetConsoleCursorPosition(hConsole, position); break; } } cout << endl << "Введите число итераций:" << endl; int numIt; cin >> numIt; cout << endl << "Введите параметр вероятности генерации:" << endl; cin >> newGame->probability; newGame->runGame(numIt); return 0; }
e65038c4f2d5c3b8e7e0c8d5db0934cc4a60b790
134ee61b4ce03695adff227db0804c17f3193a51
/src/suicide.h
b0b594d744c13d0d37de1bb9c8aee63b3217a27c
[]
no_license
sayarghoshroy/Angry_Paper_Jet
2b92d3a5949fd48bead1f1450f813267d2465ae3
7b9dade0a7d5ec2d912c4b5940149b78da81fdba
refs/heads/master
2022-09-08T17:20:24.155884
2020-05-30T23:34:11
2020-05-30T23:34:11
267,707,647
0
0
null
null
null
null
UTF-8
C++
false
false
317
h
#include "main.h" #define GLM_ENABLE_EXPERIMENTAL #ifndef SUICIDE_H #define SUICIDE_H class Suicide { public: Suicide() {} Suicide(glm::vec3 plane_pos); void draw(glm::mat4 VP); void tick(glm::vec3 plane_pos); glm::vec3 position; float rotation; float speed; float size; private: VAO *object; }; #endif
4c4d3fee3a03a87f92edd47e295fa238b169ac4a
992503d1528b2c4e0477e571ae4194d5c40d5f9c
/xrtl/port/common/base/posix_debugging.cc
ff7fe40a665b82543f74ef23507582ea543538db
[ "Apache-2.0" ]
permissive
yoshipaulbrophy/xrtl
098fa002090a02740d338614f4c43238e6d071ca
d2bbabcaa7a3a72b400c0ee79d5d3b463fbddaef
refs/heads/master
2021-01-20T00:46:11.048372
2017-04-21T17:35:45
2017-04-21T21:01:46
89,184,875
1
0
null
2017-04-24T01:23:41
2017-04-24T01:23:41
null
UTF-8
C++
false
false
969
cc
// Copyright 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "xrtl/base/debugging.h" namespace xrtl { namespace debugging { bool is_console_attached() { // TODO(benvanik): console detection. return true; } bool AttachConsole() { // TODO(benvanik): console detection. return true; } bool is_debugger_attached() { // TODO(benvanik): debugger detection. return false; } } // namespace debugging } // namespace xrtl
70ab832fbcaa5114ea021a89c262ab4d34f089f7
1fbae920e99bed47582561b5ead7719962ed62e0
/99_TEMP/Julian/CalibResizing/ui_mainwindow.h
eb21d5b70e4009071780fc7d0ad33fafa0e51a42
[]
no_license
HassibShaq/VPJW17G5
6116f571fe1b8f6a7d061488d6b840655bf1dc4e
4423fbfd1658969664116162aa3eec5a3849e7b1
refs/heads/master
2021-08-31T11:37:24.645440
2017-12-21T07:16:07
2017-12-21T07:16:07
114,781,021
0
0
null
2017-12-19T15:25:05
2017-12-19T15:25:05
null
UTF-8
C++
false
false
4,753
h
/******************************************************************************** ** Form generated from reading UI file 'mainwindow.ui' ** ** Created by: Qt User Interface Compiler version 5.1.1 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_MAINWINDOW_H #define UI_MAINWINDOW_H #include <QtCore/QVariant> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QGridLayout> #include <QtWidgets/QHeaderView> #include <QtWidgets/QLabel> #include <QtWidgets/QMainWindow> #include <QtWidgets/QPushButton> #include <QtWidgets/QSlider> #include <QtWidgets/QSpinBox> #include <QtWidgets/QStatusBar> #include <QtWidgets/QWidget> QT_BEGIN_NAMESPACE class Ui_MainWindow { public: QWidget *centralWidget; QGridLayout *gridLayout; QPushButton *startCameraButton; QLabel *labelImage; QSlider *horizontalSliderMaxvalue; QPushButton *stopCameraButton; QSlider *horizontalSliderThreshold; QSpinBox *spinBoxCaptureID; QStatusBar *statusBar; void setupUi(QMainWindow *MainWindow) { if (MainWindow->objectName().isEmpty()) MainWindow->setObjectName(QStringLiteral("MainWindow")); MainWindow->resize(847, 670); centralWidget = new QWidget(MainWindow); centralWidget->setObjectName(QStringLiteral("centralWidget")); gridLayout = new QGridLayout(centralWidget); gridLayout->setSpacing(6); gridLayout->setContentsMargins(11, 11, 11, 11); gridLayout->setObjectName(QStringLiteral("gridLayout")); startCameraButton = new QPushButton(centralWidget); startCameraButton->setObjectName(QStringLiteral("startCameraButton")); gridLayout->addWidget(startCameraButton, 1, 0, 1, 1); labelImage = new QLabel(centralWidget); labelImage->setObjectName(QStringLiteral("labelImage")); QSizePolicy sizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); sizePolicy.setHorizontalStretch(0); sizePolicy.setVerticalStretch(0); sizePolicy.setHeightForWidth(labelImage->sizePolicy().hasHeightForWidth()); labelImage->setSizePolicy(sizePolicy); labelImage->setMinimumSize(QSize(20, 20)); labelImage->setAutoFillBackground(false); labelImage->setFrameShape(QFrame::Box); gridLayout->addWidget(labelImage, 0, 0, 1, 5); horizontalSliderMaxvalue = new QSlider(centralWidget); horizontalSliderMaxvalue->setObjectName(QStringLiteral("horizontalSliderMaxvalue")); horizontalSliderMaxvalue->setMaximum(255); horizontalSliderMaxvalue->setValue(128); horizontalSliderMaxvalue->setOrientation(Qt::Horizontal); horizontalSliderMaxvalue->setTickPosition(QSlider::TicksBelow); gridLayout->addWidget(horizontalSliderMaxvalue, 1, 4, 1, 1); stopCameraButton = new QPushButton(centralWidget); stopCameraButton->setObjectName(QStringLiteral("stopCameraButton")); gridLayout->addWidget(stopCameraButton, 1, 1, 1, 1); horizontalSliderThreshold = new QSlider(centralWidget); horizontalSliderThreshold->setObjectName(QStringLiteral("horizontalSliderThreshold")); horizontalSliderThreshold->setMaximum(255); horizontalSliderThreshold->setValue(128); horizontalSliderThreshold->setOrientation(Qt::Horizontal); horizontalSliderThreshold->setTickPosition(QSlider::TicksBelow); gridLayout->addWidget(horizontalSliderThreshold, 1, 3, 1, 1); spinBoxCaptureID = new QSpinBox(centralWidget); spinBoxCaptureID->setObjectName(QStringLiteral("spinBoxCaptureID")); spinBoxCaptureID->setMinimum(-1); gridLayout->addWidget(spinBoxCaptureID, 1, 2, 1, 1); MainWindow->setCentralWidget(centralWidget); statusBar = new QStatusBar(MainWindow); statusBar->setObjectName(QStringLiteral("statusBar")); MainWindow->setStatusBar(statusBar); retranslateUi(MainWindow); QMetaObject::connectSlotsByName(MainWindow); } // setupUi void retranslateUi(QMainWindow *MainWindow) { MainWindow->setWindowTitle(QApplication::translate("MainWindow", "Camera Calibration", 0)); startCameraButton->setText(QApplication::translate("MainWindow", "Start Camera (F5)", 0)); labelImage->setText(QString()); stopCameraButton->setText(QApplication::translate("MainWindow", "Stop Camera", 0)); } // retranslateUi }; namespace Ui { class MainWindow: public Ui_MainWindow {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_MAINWINDOW_H
8513d7a9fd252f365778cc8955db25452b66e26e
a998bfde47dc0f18382741212edd56e07c035070
/net/spdy/spdy_framer.h
99db36a417433fdf0406ff758308c073afa52638
[ "BSD-3-Clause" ]
permissive
dalecurtis/mojo
92c8ce2e339ae923d387e2bdab4591f2165a9e25
e8ee0eb8a26abe43299b95054275939da9defd14
refs/heads/master
2021-01-15T11:44:31.238006
2014-10-23T18:48:50
2014-10-23T18:48:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
34,252
h
// Copyright (c) 2012 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 NET_SPDY_SPDY_FRAMER_H_ #define NET_SPDY_SPDY_FRAMER_H_ #include <list> #include <map> #include <memory> #include <string> #include <utility> #include <vector> #include "base/basictypes.h" #include "base/gtest_prod_util.h" #include "base/memory/scoped_ptr.h" #include "base/strings/string_piece.h" #include "base/sys_byteorder.h" #include "net/base/net_export.h" #include "net/spdy/hpack_decoder.h" #include "net/spdy/hpack_encoder.h" #include "net/spdy/spdy_header_block.h" #include "net/spdy/spdy_protocol.h" // TODO(akalin): Remove support for CREDENTIAL frames. typedef struct z_stream_s z_stream; // Forward declaration for zlib. namespace net { class HttpProxyClientSocketPoolTest; class HttpNetworkLayer; class HttpNetworkTransactionTest; class SpdyHttpStreamTest; class SpdyNetworkTransactionTest; class SpdyProxyClientSocketTest; class SpdySessionTest; class SpdyStreamTest; class SpdyWebSocketStreamTest; class WebSocketJobTest; class SpdyFramer; class SpdyFrameBuilder; class SpdyFramerTest; namespace test { class TestSpdyVisitor; } // namespace test // A datastructure for holding a set of headers from a HEADERS, PUSH_PROMISE, // SYN_STREAM, or SYN_REPLY frame. typedef std::map<std::string, std::string> SpdyHeaderBlock; // A datastructure for holding the ID and flag fields for SETTINGS. // Conveniently handles converstion to/from wire format. class NET_EXPORT_PRIVATE SettingsFlagsAndId { public: static SettingsFlagsAndId FromWireFormat(SpdyMajorVersion version, uint32 wire); SettingsFlagsAndId() : flags_(0), id_(0) {} // TODO(hkhalil): restrict to enums instead of free-form ints. SettingsFlagsAndId(uint8 flags, uint32 id); uint32 GetWireFormat(SpdyMajorVersion version) const; uint32 id() const { return id_; } uint8 flags() const { return flags_; } private: static void ConvertFlagsAndIdForSpdy2(uint32* val); uint8 flags_; uint32 id_; }; // SettingsMap has unique (flags, value) pair for given SpdySettingsIds ID. typedef std::pair<SpdySettingsFlags, uint32> SettingsFlagsAndValue; typedef std::map<SpdySettingsIds, SettingsFlagsAndValue> SettingsMap; // Scratch space necessary for processing SETTINGS frames. struct NET_EXPORT_PRIVATE SpdySettingsScratch { SpdySettingsScratch() { Reset(); } void Reset() { setting_buf_len = 0; last_setting_id = -1; } // Buffer contains up to one complete key/value pair. char setting_buf[8]; // The amount of the buffer that is filled with valid data. size_t setting_buf_len; // The ID of the last setting that was processed in the current SETTINGS // frame. Used for detecting out-of-order or duplicate keys within a settings // frame. Set to -1 before first key/value pair is processed. int last_setting_id; }; // Scratch space necessary for processing ALTSVC frames. struct NET_EXPORT_PRIVATE SpdyAltSvcScratch { SpdyAltSvcScratch(); ~SpdyAltSvcScratch(); void Reset() { max_age = 0; port = 0; pid_len = 0; host_len = 0; origin_len = 0; pid_buf_len = 0; host_buf_len = 0; origin_buf_len = 0; protocol_id.reset(); host.reset(); origin.reset(); } uint32 max_age; uint16 port; uint8 pid_len; uint8 host_len; size_t origin_len; size_t pid_buf_len; size_t host_buf_len; size_t origin_buf_len; scoped_ptr<char[]> protocol_id; scoped_ptr<char[]> host; scoped_ptr<char[]> origin; }; // SpdyFramerVisitorInterface is a set of callbacks for the SpdyFramer. // Implement this interface to receive event callbacks as frames are // decoded from the framer. // // Control frames that contain SPDY header blocks (SYN_STREAM, SYN_REPLY, // HEADER, and PUSH_PROMISE) are processed in fashion that allows the // decompressed header block to be delivered in chunks to the visitor. // The following steps are followed: // 1. OnSynStream, OnSynReply, OnHeaders, or OnPushPromise is called. // 2. Repeated: OnControlFrameHeaderData is called with chunks of the // decompressed header block. In each call the len parameter is greater // than zero. // 3. OnControlFrameHeaderData is called with len set to zero, indicating // that the full header block has been delivered for the control frame. // During step 2 the visitor may return false, indicating that the chunk of // header data could not be handled by the visitor (typically this indicates // resource exhaustion). If this occurs the framer will discontinue // delivering chunks to the visitor, set a SPDY_CONTROL_PAYLOAD_TOO_LARGE // error, and clean up appropriately. Note that this will cause the header // decompressor to lose synchronization with the sender's header compressor, // making the SPDY session unusable for future work. The visitor's OnError // function should deal with this condition by closing the SPDY connection. class NET_EXPORT_PRIVATE SpdyFramerVisitorInterface { public: virtual ~SpdyFramerVisitorInterface() {} // Called if an error is detected in the SpdyFrame protocol. virtual void OnError(SpdyFramer* framer) = 0; // Called when a data frame header is received. The frame's data // payload will be provided via subsequent calls to // OnStreamFrameData(). virtual void OnDataFrameHeader(SpdyStreamId stream_id, size_t length, bool fin) = 0; // Called when data is received. // |stream_id| The stream receiving data. // |data| A buffer containing the data received. // |len| The length of the data buffer. // When the other side has finished sending data on this stream, // this method will be called with a zero-length buffer. virtual void OnStreamFrameData(SpdyStreamId stream_id, const char* data, size_t len, bool fin) = 0; // Called when a chunk of header data is available. This is called // after OnSynStream, OnSynReply, OnHeaders(), or OnPushPromise. // |stream_id| The stream receiving the header data. // |header_data| A buffer containing the header data chunk received. // |len| The length of the header data buffer. A length of zero indicates // that the header data block has been completely sent. // When this function returns true the visitor indicates that it accepted // all of the data. Returning false indicates that that an unrecoverable // error has occurred, such as bad header data or resource exhaustion. virtual bool OnControlFrameHeaderData(SpdyStreamId stream_id, const char* header_data, size_t len) = 0; // Called when a SYN_STREAM frame is received. // Note that header block data is not included. See // OnControlFrameHeaderData(). virtual void OnSynStream(SpdyStreamId stream_id, SpdyStreamId associated_stream_id, SpdyPriority priority, bool fin, bool unidirectional) = 0; // Called when a SYN_REPLY frame is received. // Note that header block data is not included. See // OnControlFrameHeaderData(). virtual void OnSynReply(SpdyStreamId stream_id, bool fin) = 0; // Called when a RST_STREAM frame has been parsed. virtual void OnRstStream(SpdyStreamId stream_id, SpdyRstStreamStatus status) = 0; // Called when a SETTINGS frame is received. // |clear_persisted| True if the respective flag is set on the SETTINGS frame. virtual void OnSettings(bool clear_persisted) {} // Called when a complete setting within a SETTINGS frame has been parsed and // validated. virtual void OnSetting(SpdySettingsIds id, uint8 flags, uint32 value) = 0; // Called when a SETTINGS frame is received with the ACK flag set. virtual void OnSettingsAck() {} // Called before and after parsing SETTINGS id and value tuples. virtual void OnSettingsEnd() = 0; // Called when a PING frame has been parsed. virtual void OnPing(SpdyPingId unique_id, bool is_ack) = 0; // Called when a GOAWAY frame has been parsed. virtual void OnGoAway(SpdyStreamId last_accepted_stream_id, SpdyGoAwayStatus status) = 0; // Called when a HEADERS frame is received. // Note that header block data is not included. See // OnControlFrameHeaderData(). virtual void OnHeaders(SpdyStreamId stream_id, bool fin, bool end) = 0; // Called when a WINDOW_UPDATE frame has been parsed. virtual void OnWindowUpdate(SpdyStreamId stream_id, uint32 delta_window_size) = 0; // Called when a goaway frame opaque data is available. // |goaway_data| A buffer containing the opaque GOAWAY data chunk received. // |len| The length of the header data buffer. A length of zero indicates // that the header data block has been completely sent. // When this function returns true the visitor indicates that it accepted // all of the data. Returning false indicates that that an error has // occurred while processing the data. Default implementation returns true. virtual bool OnGoAwayFrameData(const char* goaway_data, size_t len); // Called when rst_stream frame opaque data is available. // |rst_stream_data| A buffer containing the opaque RST_STREAM // data chunk received. // |len| The length of the header data buffer. A length of zero indicates // that the opaque data has been completely sent. // When this function returns true the visitor indicates that it accepted // all of the data. Returning false indicates that that an error has // occurred while processing the data. Default implementation returns true. virtual bool OnRstStreamFrameData(const char* rst_stream_data, size_t len); // Called when a BLOCKED frame has been parsed. virtual void OnBlocked(SpdyStreamId stream_id) {} // Called when a PUSH_PROMISE frame is received. // Note that header block data is not included. See // OnControlFrameHeaderData(). virtual void OnPushPromise(SpdyStreamId stream_id, SpdyStreamId promised_stream_id, bool end) = 0; // Called when a CONTINUATION frame is received. // Note that header block data is not included. See // OnControlFrameHeaderData(). virtual void OnContinuation(SpdyStreamId stream_id, bool end) = 0; // Called when an ALTSVC frame has been parsed. virtual void OnAltSvc(SpdyStreamId stream_id, uint32 max_age, uint16 port, base::StringPiece protocol_id, base::StringPiece host, base::StringPiece origin) {} // Called when a PRIORITY frame is received. virtual void OnPriority(SpdyStreamId stream_id, SpdyStreamId parent_stream_id, uint8 weight, bool exclusive) {} // Called when a frame type we don't recognize is received. // Return true if this appears to be a valid extension frame, false otherwise. // We distinguish between extension frames and nonsense by checking // whether the stream id is valid. virtual bool OnUnknownFrame(SpdyStreamId stream_id, int frame_type) = 0; }; // Optionally, and in addition to SpdyFramerVisitorInterface, a class supporting // SpdyFramerDebugVisitorInterface may be used in conjunction with SpdyFramer in // order to extract debug/internal information about the SpdyFramer as it // operates. // // Most SPDY implementations need not bother with this interface at all. class NET_EXPORT_PRIVATE SpdyFramerDebugVisitorInterface { public: virtual ~SpdyFramerDebugVisitorInterface() {} // Called after compressing a frame with a payload of // a list of name-value pairs. // |payload_len| is the uncompressed payload size. // |frame_len| is the compressed frame size. virtual void OnSendCompressedFrame(SpdyStreamId stream_id, SpdyFrameType type, size_t payload_len, size_t frame_len) {} // Called when a frame containing a compressed payload of // name-value pairs is received. // |frame_len| is the compressed frame size. virtual void OnReceiveCompressedFrame(SpdyStreamId stream_id, SpdyFrameType type, size_t frame_len) {} }; class NET_EXPORT_PRIVATE SpdyFramer { public: // SPDY states. // TODO(mbelshe): Can we move these into the implementation // and avoid exposing through the header. (Needed for test) enum SpdyState { SPDY_ERROR, SPDY_RESET, SPDY_AUTO_RESET, SPDY_READING_COMMON_HEADER, SPDY_CONTROL_FRAME_PAYLOAD, SPDY_READ_DATA_FRAME_PADDING_LENGTH, SPDY_CONSUME_PADDING, SPDY_IGNORE_REMAINING_PAYLOAD, SPDY_FORWARD_STREAM_FRAME, SPDY_CONTROL_FRAME_BEFORE_HEADER_BLOCK, SPDY_CONTROL_FRAME_HEADER_BLOCK, SPDY_GOAWAY_FRAME_PAYLOAD, SPDY_RST_STREAM_FRAME_PAYLOAD, SPDY_SETTINGS_FRAME_PAYLOAD, SPDY_ALTSVC_FRAME_PAYLOAD, }; // SPDY error codes. enum SpdyError { SPDY_NO_ERROR, SPDY_INVALID_CONTROL_FRAME, // Control frame is mal-formatted. SPDY_CONTROL_PAYLOAD_TOO_LARGE, // Control frame payload was too large. SPDY_ZLIB_INIT_FAILURE, // The Zlib library could not initialize. SPDY_UNSUPPORTED_VERSION, // Control frame has unsupported version. SPDY_DECOMPRESS_FAILURE, // There was an error decompressing. SPDY_COMPRESS_FAILURE, // There was an error compressing. SPDY_GOAWAY_FRAME_CORRUPT, // GOAWAY frame could not be parsed. SPDY_RST_STREAM_FRAME_CORRUPT, // RST_STREAM frame could not be parsed. SPDY_INVALID_DATA_FRAME_FLAGS, // Data frame has invalid flags. SPDY_INVALID_CONTROL_FRAME_FLAGS, // Control frame has invalid flags. SPDY_UNEXPECTED_FRAME, // Frame received out of order. LAST_ERROR, // Must be the last entry in the enum. }; // Constant for invalid (or unknown) stream IDs. static const SpdyStreamId kInvalidStream; // The maximum size of header data chunks delivered to the framer visitor // through OnControlFrameHeaderData. (It is exposed here for unit test // purposes.) static const size_t kHeaderDataChunkMaxSize; // Serializes a SpdyHeaderBlock. static void WriteHeaderBlock(SpdyFrameBuilder* frame, const SpdyMajorVersion spdy_version, const SpdyHeaderBlock* headers); // Retrieve serialized length of SpdyHeaderBlock. // TODO(hkhalil): Remove, or move to quic code. static size_t GetSerializedLength( const SpdyMajorVersion spdy_version, const SpdyHeaderBlock* headers); // Create a new Framer, provided a SPDY version. explicit SpdyFramer(SpdyMajorVersion version); virtual ~SpdyFramer(); // Set callbacks to be called from the framer. A visitor must be set, or // else the framer will likely crash. It is acceptable for the visitor // to do nothing. If this is called multiple times, only the last visitor // will be used. void set_visitor(SpdyFramerVisitorInterface* visitor) { visitor_ = visitor; } // Set debug callbacks to be called from the framer. The debug visitor is // completely optional and need not be set in order for normal operation. // If this is called multiple times, only the last visitor will be used. void set_debug_visitor(SpdyFramerDebugVisitorInterface* debug_visitor) { debug_visitor_ = debug_visitor; } // Pass data into the framer for parsing. // Returns the number of bytes consumed. It is safe to pass more bytes in // than may be consumed. size_t ProcessInput(const char* data, size_t len); // Resets the framer state after a frame has been successfully decoded. // TODO(mbelshe): can we make this private? void Reset(); // Check the state of the framer. SpdyError error_code() const { return error_code_; } SpdyState state() const { return state_; } bool HasError() const { return state_ == SPDY_ERROR; } // Given a buffer containing a decompressed header block in SPDY // serialized format, parse out a SpdyHeaderBlock, putting the results // in the given header block. // Returns number of bytes consumed if successfully parsed, 0 otherwise. size_t ParseHeaderBlockInBuffer(const char* header_data, size_t header_length, SpdyHeaderBlock* block) const; // Serialize a data frame. SpdySerializedFrame* SerializeData(const SpdyDataIR& data) const; // Serializes the data frame header and optionally padding length fields, // excluding actual data payload and padding. SpdySerializedFrame* SerializeDataFrameHeaderWithPaddingLengthField( const SpdyDataIR& data) const; // Serializes a SYN_STREAM frame. SpdySerializedFrame* SerializeSynStream(const SpdySynStreamIR& syn_stream); // Serialize a SYN_REPLY SpdyFrame. SpdySerializedFrame* SerializeSynReply(const SpdySynReplyIR& syn_reply); SpdySerializedFrame* SerializeRstStream( const SpdyRstStreamIR& rst_stream) const; // Serializes a SETTINGS frame. The SETTINGS frame is // used to communicate name/value pairs relevant to the communication channel. SpdySerializedFrame* SerializeSettings(const SpdySettingsIR& settings) const; // Serializes a PING frame. The unique_id is used to // identify the ping request/response. SpdySerializedFrame* SerializePing(const SpdyPingIR& ping) const; // Serializes a GOAWAY frame. The GOAWAY frame is used // prior to the shutting down of the TCP connection, and includes the // stream_id of the last stream the sender of the frame is willing to process // to completion. SpdySerializedFrame* SerializeGoAway(const SpdyGoAwayIR& goaway) const; // Serializes a HEADERS frame. The HEADERS frame is used // for sending additional headers outside of a SYN_STREAM/SYN_REPLY. SpdySerializedFrame* SerializeHeaders(const SpdyHeadersIR& headers); // Serializes a WINDOW_UPDATE frame. The WINDOW_UPDATE // frame is used to implement per stream flow control in SPDY. SpdySerializedFrame* SerializeWindowUpdate( const SpdyWindowUpdateIR& window_update) const; // Serializes a BLOCKED frame. The BLOCKED frame is used to // indicate to the remote endpoint that this endpoint believes itself to be // flow-control blocked but otherwise ready to send data. The BLOCKED frame // is purely advisory and optional. SpdySerializedFrame* SerializeBlocked(const SpdyBlockedIR& blocked) const; // Serializes a PUSH_PROMISE frame. The PUSH_PROMISE frame is used // to inform the client that it will be receiving an additional stream // in response to the original request. The frame includes synthesized // headers to explain the upcoming data. SpdySerializedFrame* SerializePushPromise( const SpdyPushPromiseIR& push_promise); // Serializes a CONTINUATION frame. The CONTINUATION frame is used // to continue a sequence of header block fragments. // TODO(jgraettinger): This implementation is incorrect. The continuation // frame continues a previously-begun HPACK encoding; it doesn't begin a // new one. Figure out whether it makes sense to keep SerializeContinuation(). SpdySerializedFrame* SerializeContinuation( const SpdyContinuationIR& continuation); // Serializes an ALTSVC frame. The ALTSVC frame advertises the // availability of an alternative service to the client. SpdySerializedFrame* SerializeAltSvc(const SpdyAltSvcIR& altsvc); // Serializes a PRIORITY frame. The PRIORITY frame advises a change in // the relative priority of the given stream. SpdySerializedFrame* SerializePriority(const SpdyPriorityIR& priority); // Serialize a frame of unknown type. SpdySerializedFrame* SerializeFrame(const SpdyFrameIR& frame); // NOTES about frame compression. // We want spdy to compress headers across the entire session. As long as // the session is over TCP, frames are sent serially. The client & server // can each compress frames in the same order and then compress them in that // order, and the remote can do the reverse. However, we ultimately want // the creation of frames to be less sensitive to order so that they can be // placed over a UDP based protocol and yet still benefit from some // compression. We don't know of any good compression protocol which does // not build its state in a serial (stream based) manner.... For now, we're // using zlib anyway. // Compresses a SpdyFrame. // On success, returns a new SpdyFrame with the payload compressed. // Compression state is maintained as part of the SpdyFramer. // Returned frame must be freed with "delete". // On failure, returns NULL. SpdyFrame* CompressFrame(const SpdyFrame& frame); // For ease of testing and experimentation we can tweak compression on/off. void set_enable_compression(bool value) { enable_compression_ = value; } // Used only in log messages. void set_display_protocol(const std::string& protocol) { display_protocol_ = protocol; } // Returns the (minimum) size of frames (sans variable-length portions). size_t GetDataFrameMinimumSize() const; size_t GetControlFrameHeaderSize() const; size_t GetSynStreamMinimumSize() const; size_t GetSynReplyMinimumSize() const; size_t GetRstStreamMinimumSize() const; size_t GetSettingsMinimumSize() const; size_t GetPingSize() const; size_t GetGoAwayMinimumSize() const; size_t GetHeadersMinimumSize() const; size_t GetWindowUpdateSize() const; size_t GetBlockedSize() const; size_t GetPushPromiseMinimumSize() const; size_t GetContinuationMinimumSize() const; size_t GetAltSvcMinimumSize() const; size_t GetPrioritySize() const; // Returns the minimum size a frame can be (data or control). size_t GetFrameMinimumSize() const; // Returns the maximum size a frame can be (data or control). size_t GetFrameMaximumSize() const; // Returns the maximum size that a control frame can be. size_t GetControlFrameMaximumSize() const; // Returns the maximum payload size of a DATA frame. size_t GetDataFrameMaximumPayload() const; // Returns the prefix length for the given frame type. size_t GetPrefixLength(SpdyFrameType type) const; // For debugging. static const char* StateToString(int state); static const char* ErrorCodeToString(int error_code); static const char* StatusCodeToString(int status_code); static const char* FrameTypeToString(SpdyFrameType type); SpdyMajorVersion protocol_version() const { return spdy_version_; } bool probable_http_response() const { return probable_http_response_; } SpdyStreamId expect_continuation() const { return expect_continuation_; } SpdyPriority GetLowestPriority() const { return spdy_version_ < SPDY3 ? 3 : 7; } SpdyPriority GetHighestPriority() const { return 0; } // Interpolates SpdyPriority values into SPDY4/HTTP2 priority weights, // and vice versa. uint8 MapPriorityToWeight(SpdyPriority priority); SpdyPriority MapWeightToPriority(uint8 weight); // Deliver the given control frame's compressed headers block to the visitor // in decompressed form, in chunks. Returns true if the visitor has // accepted all of the chunks. bool IncrementallyDecompressControlFrameHeaderData( SpdyStreamId stream_id, const char* data, size_t len); protected: // TODO(jgraettinger): Switch to test peer pattern. FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest, BasicCompression); FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest, ControlFrameSizesAreValidated); FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest, HeaderCompression); FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest, DecompressUncompressedFrame); FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest, ExpandBuffer_HeapSmash); FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest, HugeHeaderBlock); FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest, UnclosedStreamDataCompressors); FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest, UnclosedStreamDataCompressorsOneByteAtATime); FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest, UncompressLargerThanFrameBufferInitialSize); FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest, CreatePushPromiseThenContinuationUncompressed); FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest, ReadLargeSettingsFrame); FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest, ReadLargeSettingsFrameInSmallChunks); FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest, ControlFrameAtMaxSizeLimit); FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest, ControlFrameTooLarge); FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest, TooLargeHeadersFrameUsesContinuation); FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest, TooLargePushPromiseFrameUsesContinuation); friend class net::HttpNetworkLayer; // This is temporary for the server. friend class net::HttpNetworkTransactionTest; friend class net::HttpProxyClientSocketPoolTest; friend class net::SpdyHttpStreamTest; friend class net::SpdyNetworkTransactionTest; friend class net::SpdyProxyClientSocketTest; friend class net::SpdySessionTest; friend class net::SpdyStreamTest; friend class net::SpdyWebSocketStreamTest; friend class net::WebSocketJobTest; friend class test::TestSpdyVisitor; private: // Internal breakouts from ProcessInput. Each returns the number of bytes // consumed from the data. size_t ProcessCommonHeader(const char* data, size_t len); size_t ProcessControlFramePayload(const char* data, size_t len); size_t ProcessControlFrameBeforeHeaderBlock(const char* data, size_t len); // HPACK data is re-encoded as SPDY3 and re-entrantly delivered through // |ProcessControlFrameHeaderBlock()|. |is_hpack_header_block| controls // whether data is treated as HPACK- vs SPDY3-encoded. size_t ProcessControlFrameHeaderBlock(const char* data, size_t len, bool is_hpack_header_block); size_t ProcessDataFramePaddingLength(const char* data, size_t len); size_t ProcessFramePadding(const char* data, size_t len); size_t ProcessDataFramePayload(const char* data, size_t len); size_t ProcessGoAwayFramePayload(const char* data, size_t len); size_t ProcessRstStreamFramePayload(const char* data, size_t len); size_t ProcessSettingsFramePayload(const char* data, size_t len); size_t ProcessAltSvcFramePayload(const char* data, size_t len); size_t ProcessIgnoredControlFramePayload(/*const char* data,*/ size_t len); // TODO(jgraettinger): To be removed with migration to // SpdyHeadersHandlerInterface. // Serializes the last-processed header block of |hpack_decoder_| as // a SPDY3 format block, and delivers it to the visitor via reentrant // call to ProcessControlFrameHeaderBlock(). void DeliverHpackBlockAsSpdy3Block(); // Helpers for above internal breakouts from ProcessInput. void ProcessControlFrameHeader(uint16 control_frame_type_field); // Always passed exactly 1 setting's worth of data. bool ProcessSetting(const char* data); // Retrieve serialized length of SpdyHeaderBlock. If compression is enabled, a // maximum estimate is returned. size_t GetSerializedLength(const SpdyHeaderBlock& headers); // Get (and lazily initialize) the ZLib state. z_stream* GetHeaderCompressor(); z_stream* GetHeaderDecompressor(); // Get (and lazily initialize) the HPACK state. HpackEncoder* GetHpackEncoder(); HpackDecoder* GetHpackDecoder(); size_t GetNumberRequiredContinuationFrames(size_t size); void WritePayloadWithContinuation(SpdyFrameBuilder* builder, const std::string& hpack_encoding, SpdyStreamId stream_id, SpdyFrameType type, int padding_payload_len); private: // Deliver the given control frame's uncompressed headers block to the // visitor in chunks. Returns true if the visitor has accepted all of the // chunks. bool IncrementallyDeliverControlFrameHeaderData(SpdyStreamId stream_id, const char* data, size_t len); // Utility to copy the given data block to the current frame buffer, up // to the given maximum number of bytes, and update the buffer // data (pointer and length). Returns the number of bytes // read, and: // *data is advanced the number of bytes read. // *len is reduced by the number of bytes read. size_t UpdateCurrentFrameBuffer(const char** data, size_t* len, size_t max_bytes); void WriteHeaderBlockToZ(const SpdyHeaderBlock* headers, z_stream* out) const; void SerializeNameValueBlockWithoutCompression( SpdyFrameBuilder* builder, const SpdyNameValueBlock& name_value_block) const; // Compresses automatically according to enable_compression_. void SerializeNameValueBlock( SpdyFrameBuilder* builder, const SpdyFrameWithNameValueBlockIR& frame); // Set the error code and moves the framer into the error state. void set_error(SpdyError error); // The maximum size of the control frames that we support. // This limit is arbitrary. We can enforce it here or at the application // layer. We chose the framing layer, but this can be changed (or removed) // if necessary later down the line. size_t GetControlFrameBufferMaxSize() const { // The theoretical maximum for SPDY3 and earlier is (2^24 - 1) + // 8, since the length field does not count the size of the // header. if (spdy_version_ == SPDY2) { return 64 * 1024; } if (spdy_version_ == SPDY3) { return 16 * 1024 * 1024; } // Absolute maximum size of HTTP2 frame payload (section 4.2 "Frame size"). return (1<<14) - 1; } // TODO(jgraettinger): For h2-13 interop testing coverage, // fragment at smaller payload boundaries. size_t GetHeaderFragmentMaxSize() const { return GetControlFrameBufferMaxSize() >> 4; // 1023 bytes. } // The size of the control frame buffer. // Since this is only used for control frame headers, the maximum control // frame header size (SYN_STREAM) is sufficient; all remaining control // frame data is streamed to the visitor. static const size_t kControlFrameBufferSize; SpdyState state_; SpdyState previous_state_; SpdyError error_code_; // Note that for DATA frame, remaining_data_length_ is sum of lengths of // frame header, padding length field (optional), data payload (optional) and // padding payload (optional). size_t remaining_data_length_; // The length (in bytes) of the padding payload to be processed. size_t remaining_padding_payload_length_; // The number of bytes remaining to read from the current control frame's // headers. Note that header data blocks (for control types that have them) // are part of the frame's payload, and not the frame's headers. size_t remaining_control_header_; scoped_ptr<char[]> current_frame_buffer_; // Number of bytes read into the current_frame_buffer_. size_t current_frame_buffer_length_; // The type of the frame currently being read. SpdyFrameType current_frame_type_; // The flags field of the frame currently being read. uint8 current_frame_flags_; // The total length of the frame currently being read, including frame header. uint32 current_frame_length_; // The stream ID field of the frame currently being read, if applicable. SpdyStreamId current_frame_stream_id_; // Scratch space for handling SETTINGS frames. // TODO(hkhalil): Unify memory for this scratch space with // current_frame_buffer_. SpdySettingsScratch settings_scratch_; SpdyAltSvcScratch altsvc_scratch_; bool enable_compression_; // Controls all compression // SPDY header compressors. scoped_ptr<z_stream> header_compressor_; scoped_ptr<z_stream> header_decompressor_; scoped_ptr<HpackEncoder> hpack_encoder_; scoped_ptr<HpackDecoder> hpack_decoder_; SpdyFramerVisitorInterface* visitor_; SpdyFramerDebugVisitorInterface* debug_visitor_; std::string display_protocol_; // The major SPDY version to be spoken/understood by this framer. const SpdyMajorVersion spdy_version_; // Tracks if we've ever gotten far enough in framing to see a control frame of // type SYN_STREAM or SYN_REPLY. // // If we ever get something which looks like a data frame before we've had a // SYN, we explicitly check to see if it looks like we got an HTTP response // to a SPDY request. This boolean lets us do that. bool syn_frame_processed_; // If we ever get a data frame before a SYN frame, we check to see if it // starts with HTTP. If it does, we likely have an HTTP response. This // isn't guaranteed though: we could have gotten a settings frame and then // corrupt data that just looks like HTTP, but deterministic checking requires // a lot more state. bool probable_http_response_; // Set this to the current stream when we receive a HEADERS, PUSH_PROMISE, or // CONTINUATION frame without the END_HEADERS(0x4) bit set. These frames must // be followed by a CONTINUATION frame, or else we throw a PROTOCOL_ERROR. // A value of 0 indicates that we are not expecting a CONTINUATION frame. SpdyStreamId expect_continuation_; // If a HEADERS frame is followed by a CONTINUATION frame, the FIN/END_STREAM // flag is still carried in the HEADERS frame. If it's set, flip this so that // we know to terminate the stream when the entire header block has been // processed. bool end_stream_when_done_; }; } // namespace net #endif // NET_SPDY_SPDY_FRAMER_H_
1413b551efcaa96a72e9d6f122eae61b501a68c6
6fdd9f2cf50457851776a6991b51d9550f644aac
/tests/box.cpp
73cf44e5a5eb6f91af3e8e5fbd007cb0b6f60bad
[ "BSD-3-Clause" ]
permissive
gouarin/cafes
62008aa5e0f55d74681b9851d20552ae28a9bada
5c9abe85a0a6440b47bcd356690c933df5c95988
refs/heads/master
2022-07-24T01:59:14.925626
2020-03-27T14:11:11
2020-03-27T14:11:11
62,560,133
5
2
NOASSERTION
2022-03-30T09:20:09
2016-07-04T12:22:20
C
UTF-8
C++
false
false
1,166
cpp
#include <particle/geometry/box.hpp> #include <particle/geometry/super_ellipsoid.hpp> #include <cassert> #include <iostream> int main() { { using pt = cafes::geometry::super_ellipsoid<2>::position_type; using st = cafes::geometry::super_ellipsoid<2>::shapes_type; cafes::geometry::super_ellipsoid<2> se{ {0.,0.}, {1.,1.}, 1. }; cafes::geometry::box<2, double> b1=se.bounding_box(), b2{{-2.,-2.}, {5., .5}}, b3; std::cout << b1.bottom_left[0] << ", " << b1.bottom_left[1] << "\n"; std::cout << b1.upper_right[0] << ", " << b1.upper_right[1] << "\n"; std::cout << b2.bottom_left[0] << ", " << b2.bottom_left[1] << "\n"; std::cout << b2.upper_right[0] << ", " << b2.upper_right[1] << "\n"; b3 = overlap_box(b1, b2); std::cout << b3.bottom_left[0] << ", " << b3.bottom_left[1] << "\n"; std::cout << b3.upper_right[0] << ", " << b3.upper_right[1] << "\n"; cafes::geometry::box<2, int> bi1{{0, 0}, {2, 2}}, bi2{{1, 1}, {3, 3}}, bi3{{-2, -2}, {-1, -1}}; assert(cafes::geometry::intersect(bi1, bi2)); assert(!cafes::geometry::intersect(bi1, bi3)); //assert( se.is_outside({1. ,1.}) ); } return 0; }
7daabc26aa7a87bacb40e6af0313ab62ae93a7cb
dcf4162869feab76e0de62971c2f5ae48cd0ba87
/test/mt_realloc.cpp
a1c4579ffa0eed45928bed71ad37becafe200916
[]
no_license
YehorDzhurynskyi/ftmalloc
ec032418ae54f270bde6dbb23276589a14e2c07c
2361b1d695a32c096ba13644919b1db4d82ccd03
refs/heads/master
2021-01-01T00:48:40.906466
2020-02-19T18:23:28
2020-02-19T18:23:28
239,104,337
0
0
null
null
null
null
UTF-8
C++
false
false
7,738
cpp
#include <cstdlib> #include <ctime> #include <cassert> #ifdef WIN32 #include <windows.h> #include <process.h> #endif #include "malloctest.h" #define SIZE 20000 #define MAXSIZE (1024 * 10) #define MT #define DECLARE_PARAMS(prefix)\ \ alloc_params prefix##_alloc_params;\ {\ prefix##_alloc_params.cluster = prefix##_cluster;\ prefix##_alloc_params.size = prefix##_size;\ prefix##_alloc_params.min_alloc = prefix##_min;\ prefix##_alloc_params.max_alloc = prefix##_max;\ }\ \ realloc_params prefix##_realloc_params;\ {\ prefix##_realloc_params.cluster = prefix##_cluster;\ prefix##_realloc_params.size = prefix##_size;\ prefix##_realloc_params.reallocated = prefix##_reallocated;\ }\ \ dealloc_params prefix##_dealloc_params;\ {\ prefix##_dealloc_params.cluster = prefix##_cluster;\ prefix##_dealloc_params.size = prefix##_size;\ prefix##_dealloc_params.reallocated = prefix##_reallocated;\ }\ \ #ifdef MT #ifdef WIN32 # define DECLARE_WORKERS(prefix)\ \ DECLARE_PARAMS(prefix)\ \ HANDLE prefix##_alloc_thread = (HANDLE)_beginthread(\ alloc_worker,\ 0,\ &prefix##_alloc_params\ );\ \ HANDLE prefix##_realloc_thread = (HANDLE)_beginthread(\ realloc_worker,\ 0,\ &prefix##_realloc_params\ );\ \ HANDLE prefix##_dealloc_thread = (HANDLE)_beginthread(\ dealloc_worker,\ 0,\ &prefix##_dealloc_params\ );\ #else #include <pthread.h> typedef pthread_t HANDLE; # define DECLARE_WORKERS(prefix)\ \ DECLARE_PARAMS(prefix)\ \ HANDLE prefix##_alloc_thread;\ pthread_create(\ &prefix##_alloc_thread,\ NULL,\ (void * _Nullable (* _Nonnull)(void * _Nullable))alloc_worker,\ &prefix##_alloc_params\ );\ \ HANDLE prefix##_realloc_thread;\ pthread_create(\ &prefix##_realloc_thread,\ NULL,\ (void * _Nullable (* _Nonnull)(void * _Nullable))realloc_worker,\ &prefix##_realloc_params\ );\ \ HANDLE prefix##_dealloc_thread;\ pthread_create(\ &prefix##_dealloc_thread,\ NULL,\ (void * _Nullable (* _Nonnull)(void * _Nullable))dealloc_worker,\ &prefix##_dealloc_params\ );\ #endif #endif typedef struct { void **cluster; size_t *size; size_t min_alloc; size_t max_alloc; } alloc_params; typedef struct { void **cluster; size_t *size; t_bool *reallocated; } realloc_params; typedef struct { void **cluster; size_t *size; t_bool *reallocated; } dealloc_params; static void alloc_worker(void *p) { alloc_params* params = (alloc_params*)p; for (volatile int i = 0; i < SIZE; ++i) { size_t alloc_size = rand() % params->max_alloc; alloc_size = alloc_size < params->min_alloc ? params->min_alloc : alloc_size; char *alloc = (char*)ftmalloc(alloc_size); assert(alloc != NULL); #if 1 for (unsigned int j = 0; j < alloc_size; ++j) { alloc[j] = (char)(rand() % 256); } #else char ch = 'A'; for (unsigned int j = 0; j < alloc_size; ++j) { alloc[j] = ch; ch = (ch + 1) % ('H' + 1); if (ch == 0) ch = 'A'; } #endif params->cluster[i] = alloc; params->size[i] = alloc_size; } } #define NREALLOC 1 static void realloc_worker(void *p) { realloc_params* params = (realloc_params*)p; int c = 0; while (c < NREALLOC * SIZE) { volatile int i = rand() % SIZE; if (params->cluster[i] != NULL && params->reallocated[i] < NREALLOC) { void* old = malloc(params->size[i]); memcpy(old, params->cluster[i], params->size[i]); volatile size_t alloc_size = rand() % MAXSIZE; alloc_size = alloc_size > 1 ? alloc_size : 1; params->cluster[i] = (char*)ftrealloc(params->cluster[i], alloc_size); assert(params->cluster[i] != NULL); params->size[i] = alloc_size; params->reallocated[i]++; ++c; free(old); } } } static void dealloc_worker(void *p) { dealloc_params* params = (dealloc_params*)p; int c = 0; while (c < SIZE) { volatile int i = rand() % SIZE; assert(params->reallocated[i] <= NREALLOC); if (params->cluster[i] != NULL && params->reallocated[i] == NREALLOC) { ftfree(params->cluster[i]); params->cluster[i] = NULL; ++c; } } } namespace { TEST_F(FTMallocTest, MTMallocReallocFree) { #ifdef FTMALLOC_POSIX_API return; #endif setenv(FTMALLOC_ENV_SCRIBBLE, "1", 1); setenv(FTMALLOC_ENV_CHECK_HEAP_RELAXED, "1", 1); setenv(FTMALLOC_ENV_CHECK_HEAP_FULLY, "1", 1); assert(getenv(FTMALLOC_ENV_SCRIBBLE)); assert(getenv(FTMALLOC_ENV_CHECK_HEAP_RELAXED)); assert(getenv(FTMALLOC_ENV_CHECK_HEAP_FULLY)); srand(time(NULL)); void **sm_cluster = (void**)calloc(SIZE, sizeof(void*)); void **md_cluster = (void**)calloc(SIZE, sizeof(void*)); void **lg_cluster = (void**)calloc(SIZE, sizeof(void*)); t_bool *sm_reallocated = (t_bool*)calloc(SIZE, sizeof(t_bool)); t_bool *md_reallocated = (t_bool*)calloc(SIZE, sizeof(t_bool)); t_bool *lg_reallocated = (t_bool*)calloc(SIZE, sizeof(t_bool)); size_t *sm_size = (size_t*)calloc(SIZE, sizeof(size_t)); size_t *md_size = (size_t*)calloc(SIZE, sizeof(size_t)); size_t *lg_size = (size_t*)calloc(SIZE, sizeof(size_t)); const size_t sm_min = 1; const size_t sm_max = FTMALLOC_BIN_ITEM_MAX_ALLOC_SIZE_SMALL - FTMALLOC_CHUNK_SZ + 1; const size_t md_min = FTMALLOC_BIN_ITEM_MAX_ALLOC_SIZE_SMALL - FTMALLOC_CHUNK_SZ + 1; const size_t md_max = FTMALLOC_BIN_ITEM_MAX_ALLOC_SIZE_MEDIUM - FTMALLOC_CHUNK_SZ + 1; const size_t lg_min = FTMALLOC_BIN_ITEM_MAX_ALLOC_SIZE_MEDIUM - FTMALLOC_CHUNK_SZ + 1; const size_t lg_max = MAXSIZE; #ifndef MT DECLARE_PARAMS(sm) DECLARE_PARAMS(md) DECLARE_PARAMS(lg) alloc_worker(&sm_alloc_params); alloc_worker(&md_alloc_params); alloc_worker(&lg_alloc_params); dealloc_worker(&sm_dealloc_params); dealloc_worker(&md_dealloc_params); dealloc_worker(&lg_dealloc_params); alloc_worker(&sm_alloc_params); dealloc_worker(&sm_dealloc_params); alloc_worker(&md_alloc_params); dealloc_worker(&md_dealloc_params); alloc_worker(&lg_alloc_params); dealloc_worker(&lg_dealloc_params); #else DECLARE_WORKERS(sm) DECLARE_WORKERS(md) DECLARE_WORKERS(lg) HANDLE threads[] = { sm_alloc_thread, sm_dealloc_thread, sm_realloc_thread, md_alloc_thread, md_dealloc_thread, md_realloc_thread, lg_alloc_thread, lg_dealloc_thread, lg_realloc_thread }; #ifdef WIN32 WaitForMultipleObjects(sizeof(threads) / sizeof(threads[0]), threads, TRUE, INFINITE); #else for (unsigned int i = 0; i < sizeof(threads) / sizeof(threads[0]); ++i) { pthread_join(threads[i], NULL); } #endif #endif free(sm_cluster); free(md_cluster); free(lg_cluster); free(sm_reallocated); free(md_reallocated); free(lg_reallocated); free(sm_size); free(md_size); free(lg_size); unsetenv(FTMALLOC_ENV_SCRIBBLE); unsetenv(FTMALLOC_ENV_CHECK_HEAP_RELAXED); unsetenv(FTMALLOC_ENV_CHECK_HEAP_FULLY); assert(!getenv(FTMALLOC_ENV_SCRIBBLE)); assert(!getenv(FTMALLOC_ENV_CHECK_HEAP_RELAXED)); assert(!getenv(FTMALLOC_ENV_CHECK_HEAP_FULLY)); } }
06d829fa152b270ba4b2ccfd4cce4e38abfdc5d4
b7359a11eb0b4db687f52cf616a76d8e8c95dfae
/src/core/kext/RemapFunc/RemapFuncBase.hpp
1a6c386727296e2c5f316aaede129f3c02bc5092
[ "Unlicense" ]
permissive
ausdruck/Karabiner
aa41bfd54b16f8a4cd892c92b26265121dec14c1
116086461fc19dce34434b070ead238ff2e2aa00
refs/heads/master
2021-01-15T09:38:14.846272
2015-05-10T13:02:26
2015-05-10T13:02:26
35,535,965
1
0
null
2015-05-13T08:00:23
2015-05-13T08:00:22
null
UTF-8
C++
false
false
2,614
hpp
#ifndef REMAPFUNCBASE_HPP #define REMAPFUNCBASE_HPP #include "bridge.h" #include "EventOutputQueue.hpp" #include "FromEvent.hpp" #include "IOLogWrapper.hpp" #include "KeyCode.hpp" #include "ListHookedKeyboard.hpp" #include "RemapFuncClasses.hpp" #include "ToEvent.hpp" #include "WeakPointer.hpp" namespace org_pqrs_Karabiner { class RemapSimultaneousKeyPressesResult { public: enum Value { NOT_CHANGED, // __SimultaneousKeyPresses__ has been applied. // And KeyCode::VK_SIMULTANEOUSKEYPRESSES_* has been pushed. APPLIED, // __SimultaneousKeyPresses__ has been applied. // But no KeyCode::VK_SIMULTANEOUSKEYPRESSES_* has been pushed. // This result will be returned when key up event and some keys remain pressed. // // We need to continue remap_simultaneouskeypresses in EventInputQueue but // do not change active_SimultaneousButtonPresses_ in RemapClass::Item. QUEUE_CHANGED, }; }; namespace RemapFunc { DECLARE_WEAKPOINTER(RemapFuncBase); class RemapFuncBase { protected: RemapFuncBase(unsigned int type, AutogenId autogenId) : type_(type), ignorePassThrough_(false), autogenId_(autogenId) { WeakPointerManager_RemapFuncBase::add(this); } public: virtual ~RemapFuncBase(void) { WeakPointerManager_RemapFuncBase::remove(this); } virtual void add(AddDataType datatype, AddValue newval) = 0; // Clean up internal state before `remap`. // For example, send short period key event in HoldingKeyToKey. virtual void prepare(RemapParams& remapParams) {} virtual bool remap(RemapParams& remapParams) { return false; } virtual void cancelEventOutputQueueItems(EventOutputQueue::Item& item) {} virtual RemapSimultaneousKeyPressesResult::Value remapSimultaneousKeyPresses(void) { return RemapSimultaneousKeyPressesResult::NOT_CHANGED; } virtual bool remapSetKeyboardType(KeyboardType& keyboardType) { return false; } virtual bool remapForceNumLockOn(ListHookedKeyboard::Item* item) { return false; } virtual const FromEvent* getBlockUntilKeyUpFromEvent(void) const { return nullptr; } virtual bool isActive(bool iskeydown) { return iskeydown; } unsigned int getType(void) const { return type_; } void setIgnorePassThrough(bool v) { ignorePassThrough_ = v; } bool getIgnorePassThrough(void) const { return ignorePassThrough_; } AutogenId getAutogenId(void) { return autogenId_; } private: unsigned int type_; bool ignorePassThrough_; protected: const AutogenId autogenId_; }; } } #endif
db67980be2855e9dba92a3278776f38ecee89459
122287275ec1666cc27a6b6d06bab4f8b1c4ff33
/z3/src/tactic/arith/lia2pb_tactic.cpp
8d200c80d3468eba4d4db02319d3fbed21320055
[ "MIT" ]
permissive
NJUCWL/symbolic_tools
f036691918b147019c99584efb4dcbe1228ae6c0
669f549b0a97045de4cd95b1df43de93b1462e45
refs/heads/main
2023-05-09T12:00:57.836897
2021-06-01T13:34:40
2021-06-01T13:34:40
370,017,201
2
0
null
null
null
null
UTF-8
C++
false
false
12,694
cpp
/*++ Copyright (c) 2012 Microsoft Corporation Module Name: lia2pb_tactic.cpp Abstract: Reduce bounded LIA benchmark into 0-1 LIA benchmark. Author: Leonardo de Moura (leonardo) 2012-02-07. Revision History: --*/ #include"tactical.h" #include"bound_manager.h" #include"th_rewriter.h" #include"for_each_expr.h" #include"extension_model_converter.h" #include"filter_model_converter.h" #include"arith_decl_plugin.h" #include"expr_substitution.h" #include"ast_smt2_pp.h" class lia2pb_tactic : public tactic { struct imp { ast_manager & m; bound_manager m_bm; arith_util m_util; expr_dependency_ref_vector m_new_deps; th_rewriter m_rw; bool m_produce_models; bool m_produce_unsat_cores; bool m_partial_lia2pb; unsigned m_max_bits; unsigned m_total_bits; imp(ast_manager & _m, params_ref const & p): m(_m), m_bm(m), m_util(m), m_new_deps(m), m_rw(m, p) { updt_params(p); } void updt_params_core(params_ref const & p) { m_partial_lia2pb = p.get_bool("lia2pb_partial", false); m_max_bits = p.get_uint("lia2pb_max_bits", 32); m_total_bits = p.get_uint("lia2pb_total_bits", 2048); } void updt_params(params_ref const & p) { m_rw.updt_params(p); updt_params_core(p); } void set_cancel(bool f) { m_rw.set_cancel(f); } bool is_target_core(expr * n, rational & u) { if (!is_uninterp_const(n)) return false; rational l; bool s; if (m_bm.has_lower(n, l, s) && m_bm.has_upper(n, u, s) && l.is_zero() && !u.is_neg() && u.get_num_bits() <= m_max_bits) { return true; } return false; } bool is_bounded(expr * n) { rational u; return is_target_core(n, u); } bool is_target(expr * n) { rational u; return is_target_core(n, u) && u > rational(1); } struct failed {}; struct visitor { imp & m_owner; visitor(imp & o):m_owner(o) {} void throw_failed(expr * n) { TRACE("lia2pb", tout << "Failed at:\n" << mk_ismt2_pp(n, m_owner.m) << "\n";); throw failed(); } void operator()(var * n) { throw_failed(n); } void operator()(app * n) { family_id fid = n->get_family_id(); if (fid == m_owner.m.get_basic_family_id()) { // all basic family ops are OK } else if (fid == m_owner.m_util.get_family_id()) { // check if linear switch (n->get_decl_kind()) { case OP_LE: case OP_GE: case OP_LT: case OP_GT: case OP_ADD: case OP_NUM: return; case OP_MUL: if (n->get_num_args() != 2) throw_failed(n); if (!m_owner.m_util.is_numeral(n->get_arg(0))) throw_failed(n); return; default: throw_failed(n); } } else if (is_uninterp_const(n)) { if (m_owner.m_util.is_real(n)) { if (!m_owner.m_partial_lia2pb) throw_failed(n); } else if (m_owner.m_util.is_int(n)) { if (!m_owner.m_partial_lia2pb && !m_owner.is_bounded(n)) throw_failed(n); } } else { sort * s = m_owner.m.get_sort(n); if (s->get_family_id() == m_owner.m_util.get_family_id()) throw_failed(n); } } void operator()(quantifier * n) { throw_failed(n); } }; bool check(goal const & g) { try { expr_fast_mark1 visited; visitor proc(*this); unsigned sz = g.size(); for (unsigned i = 0; i < sz; i++) { expr * f = g.form(i); for_each_expr_core<visitor, expr_fast_mark1, true, true>(proc, visited, f); } return true; } catch (failed) { return false; } } bool has_target() { bound_manager::iterator it = m_bm.begin(); bound_manager::iterator end = m_bm.end(); for (; it != end; ++it) { if (is_target(*it)) return true; } return false; } bool check_num_bits() { unsigned num_bits = 0; rational u; bound_manager::iterator it = m_bm.begin(); bound_manager::iterator end = m_bm.end(); for (; it != end; ++it) { expr * x = *it; if (is_target_core(x, u) && u > rational(1)) { num_bits += u.get_num_bits(); if (num_bits > m_total_bits) return false; } } return true; } virtual void operator()(goal_ref const & g, goal_ref_buffer & result, model_converter_ref & mc, proof_converter_ref & pc, expr_dependency_ref & core) { SASSERT(g->is_well_sorted()); fail_if_proof_generation("lia2pb", g); m_produce_models = g->models_enabled(); m_produce_unsat_cores = g->unsat_core_enabled(); mc = 0; pc = 0; core = 0; result.reset(); tactic_report report("lia2pb", *g); m_bm.reset(); m_rw.reset(); m_new_deps.reset(); if (g->inconsistent()) { result.push_back(g.get()); return; } m_bm(*g); TRACE("lia2pb", m_bm.display(tout);); // check if there is some variable to be converted if (!has_target()) { // nothing to be done g->inc_depth(); result.push_back(g.get()); return; } if (!check(*g)) throw tactic_exception("goal is in a fragment unsupported by lia2pb"); if (!check_num_bits()) throw tactic_exception("lia2pb failed, number of necessary bits exceeds specified threshold (use option :lia2pb-total-bits to increase threshold)"); extension_model_converter * mc1 = 0; filter_model_converter * mc2 = 0; if (m_produce_models) { mc1 = alloc(extension_model_converter, m); mc2 = alloc(filter_model_converter, m); mc = concat(mc2, mc1); } expr_ref zero(m); expr_ref one(m); zero = m_util.mk_numeral(rational(0), true); one = m_util.mk_numeral(rational(1), true); unsigned num_converted = 0; expr_substitution subst(m, m_produce_unsat_cores, false); rational u; ptr_buffer<expr> def_args; bound_manager::iterator it = m_bm.begin(); bound_manager::iterator end = m_bm.end(); for (; it != end; ++it) { expr * x = *it; if (is_target_core(x, u) && u > rational(1)) { num_converted++; def_args.reset(); rational a(1); unsigned num_bits = u.get_num_bits(); for (unsigned i = 0; i < num_bits; i++) { app * x_prime = m.mk_fresh_const(0, m_util.mk_int()); g->assert_expr(m_util.mk_le(zero, x_prime)); g->assert_expr(m_util.mk_le(x_prime, one)); if (a.is_one()) def_args.push_back(x_prime); else def_args.push_back(m_util.mk_mul(m_util.mk_numeral(a, true), x_prime)); if (m_produce_models) mc2->insert(x_prime->get_decl()); a *= rational(2); } SASSERT(def_args.size() > 1); expr * def = m_util.mk_add(def_args.size(), def_args.c_ptr()); expr_dependency * dep = 0; if (m_produce_unsat_cores) { dep = m.mk_join(m_bm.lower_dep(x), m_bm.upper_dep(x)); if (dep != 0) m_new_deps.push_back(dep); } TRACE("lia2pb", tout << mk_ismt2_pp(x, m) << " -> " << dep << "\n";); subst.insert(x, def, 0, dep); if (m_produce_models) mc1->insert(to_app(x)->get_decl(), def); } } report_tactic_progress(":converted-lia2pb", num_converted); m_rw.set_substitution(&subst); expr_ref new_curr(m); proof_ref new_pr(m); unsigned size = g->size(); for (unsigned idx = 0; idx < size; idx++) { expr * curr = g->form(idx); expr_dependency * dep = 0; m_rw(curr, new_curr, new_pr); if (m_produce_unsat_cores) { dep = m.mk_join(m_rw.get_used_dependencies(), g->dep(idx)); m_rw.reset_used_dependencies(); } if (m.proofs_enabled()) { new_pr = m.mk_modus_ponens(g->pr(idx), new_pr); } g->update(idx, new_curr, new_pr, dep); } g->inc_depth(); result.push_back(g.get()); TRACE("lia2pb", g->display(tout);); SASSERT(g->is_well_sorted()); } }; imp * m_imp; params_ref m_params; public: lia2pb_tactic(ast_manager & m, params_ref const & p): m_params(p) { m_imp = alloc(imp, m, p); } virtual tactic * translate(ast_manager & m) { return alloc(lia2pb_tactic, m, m_params); } virtual ~lia2pb_tactic() { dealloc(m_imp); } virtual void updt_params(params_ref const & p) { m_params = p; m_imp->updt_params(p); } virtual void collect_param_descrs(param_descrs & r) { r.insert("lia2pb_partial", CPK_BOOL, "(default: false) partial lia2pb conversion."); r.insert("lia2pb_max_bits", CPK_UINT, "(default: 32) maximum number of bits to be used (per variable) in lia2pb."); r.insert("lia2pb_total_bits", CPK_UINT, "(default: 2048) total number of bits to be used (per problem) in lia2pb."); } virtual void operator()(goal_ref const & in, goal_ref_buffer & result, model_converter_ref & mc, proof_converter_ref & pc, expr_dependency_ref & core) { try { (*m_imp)(in, result, mc, pc, core); } catch (rewriter_exception & ex) { throw tactic_exception(ex.msg()); } } virtual void cleanup() { imp * d = alloc(imp, m_imp->m, m_params); #pragma omp critical (tactic_cancel) { std::swap(d, m_imp); } dealloc(d); } protected: virtual void set_cancel(bool f) { if (m_imp) m_imp->set_cancel(f); } }; tactic * mk_lia2pb_tactic(ast_manager & m, params_ref const & p) { return clean(alloc(lia2pb_tactic, m, p)); }
6c4240af646c26fce9c7dedf33b50dc626e21cca
70378e0d46b1c4a25ba796f7d705096f0ca8b13b
/include/music.cpp
d0d51fd5c3f6808344eb7a939107b9344e221a4e
[]
no_license
jackrobotics/kb-honeylemon
1056f33cde07d0a9224f0d469eddc62f4ba3a19b
a9edf87a4457d1920da8eb36c2471db4dd2ba414
refs/heads/master
2020-12-20T07:51:28.567861
2020-01-24T13:41:55
2020-01-24T13:41:55
236,006,937
0
0
null
null
null
null
UTF-8
C++
false
false
680
cpp
#include "music.h" void music::begin(void) { // ledcSetup(0, 5000, 27); } void music::tone(unsigned int frequency, unsigned long duration) { if (ledcRead(0)) { log_e("Tone channel %d is already in use", ledcRead(0)); return; } ledcAttachPin(27, 0); ledcWriteTone(0, frequency); if (duration) { delay(duration); noTone(); } } void music::noTone() { ledcDetachPin(27); ledcWrite(0, 0); } void music::song(std::vector<int>notes,int duration) { for(int freq : notes){ if(freq == -1){ noTone(); delay(duration); }else{ tone(freq,duration); } } }
1c503b2c71d29a1a00123976af4ccb708e5e22f9
ca56965a4b410ad1e66da520b3a9d859a402fb09
/gazebo/gazebo/gui/DataLogger_TEST.cc
5e85e95eb94b10bebc232f4c4e6dd908842d6e6f
[ "Apache-2.0" ]
permissive
UWARG/simSPIKE
46866b0a33b364e91fc4fda3662a03ae4652e4e5
69a5da0f409816e318a16da4e1a2b7b3efab6364
refs/heads/master
2021-05-04T10:32:15.667935
2016-11-06T04:17:38
2016-11-06T04:17:38
48,701,706
1
0
null
null
null
null
UTF-8
C++
false
false
5,239
cc
/* * Copyright (C) 2012-2014 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <boost/filesystem.hpp> #include "gazebo/common/SystemPaths.hh" #include "gazebo/gui/DataLogger.hh" #include "gazebo/gui/DataLogger_TEST.hh" #include "gazebo/math/Rand.hh" ///////////////////////////////////////////////// void DataLogger_TEST::RecordButton() { QBENCHMARK { this->Load("worlds/empty.world"); // Create a new data logger widget gazebo::gui::DataLogger *dataLogger = new gazebo::gui::DataLogger; dataLogger->show(); QCoreApplication::processEvents(); // Get the record button QToolButton *recordButton = dataLogger->findChild<QToolButton*>( "dataLoggerRecordButton"); // Get the destination label QLineEdit *destPathLabel = dataLogger->findChild<QLineEdit*>( "dataLoggerDestnationPathLabel"); // Get the time label QLabel *timeLabel = dataLogger->findChild<QLabel*>("dataLoggerTimeLabel"); // Get the status label QLabel *statusLabel = dataLogger->findChild<QLabel*>("dataLoggerStatusLabel"); // Get the size label QLabel *sizeLabel = dataLogger->findChild<QLabel*>("dataLoggerSizeLabel"); QVERIFY(recordButton != NULL); QVERIFY(destPathLabel != NULL); QVERIFY(sizeLabel != NULL); QVERIFY(timeLabel != NULL); QVERIFY(statusLabel != NULL); // Toggle the record button, which starts logging. recordButton->toggle(); // Wait for a log status return message while (destPathLabel->text().toStdString().empty()) { // The following line tell QT to process its events. This is vital for // all tests, but it must be run in the main thread. QCoreApplication::processEvents(); gazebo::common::Time::MSleep(100); } std::string txt; // Make sure the destination log file is correct. txt = destPathLabel->text().toStdString(); QVERIFY(txt.find("test/state.log") != std::string::npos); // Make sure the initial size is zero txt = sizeLabel->text().toStdString(); QVERIFY(txt == "0.00 B"); // Make sure the initial time is zero txt = timeLabel->text().toStdString(); QVERIFY(txt == "00:00:00.000"); // Make sure the status label says "Recording" txt = statusLabel->text().toStdString(); QVERIFY(txt == "Recording"); // Toggle the record button, which stops logging. recordButton->toggle(); // Make sure the initial size is zero txt = sizeLabel->text().toStdString(); QVERIFY(txt == "0.00 B"); // Make sure the initial time is zero txt = timeLabel->text().toStdString(); QVERIFY(txt == "00:00:00.000"); // Make sure the status label says "Ready" txt = statusLabel->text().toStdString(); QVERIFY(txt == "Ready"); dataLogger->hide(); } } ///////////////////////////////////////////////// void DataLogger_TEST::StressTest() { QBENCHMARK { gazebo::common::SystemPaths *paths = gazebo::common::SystemPaths::Instance(); // Cleanup test directory. boost::filesystem::remove_all(paths->GetDefaultTestPath()); this->Load("worlds/empty.world"); // Cleanup test directory. boost::filesystem::remove_all(paths->GetDefaultTestPath()); gazebo::transport::NodePtr node; gazebo::transport::PublisherPtr pub; // Create a node from communication. node = gazebo::transport::NodePtr(new gazebo::transport::Node()); node->Init(); pub = node->Advertise<gazebo::msgs::LogControl>("~/log/control"); gazebo::msgs::LogControl msg; msg.set_base_path(paths->GetDefaultTestPath()); pub->Publish(msg); // Create a new data logger widget gazebo::gui::DataLogger *dataLogger = new gazebo::gui::DataLogger; // Get the record button QToolButton *recordButton = dataLogger->findChild<QToolButton*>( "dataLoggerRecordButton"); unsigned int count = 100; // Toggle the record button many times with sleeps for (unsigned int i = 0; i < count; ++i) { recordButton->toggle(); // Sleep for random times gazebo::common::Time::MSleep(gazebo::math::Rand::GetIntUniform(10, 500)); } // There should be (count * 0.5) log directories in $TMP/gazebo_test // due to the record button being toggled. unsigned int dirCount = 0; for (boost::filesystem::directory_iterator iter(paths->GetDefaultTestPath()); iter != boost::filesystem::directory_iterator(); ++iter, ++dirCount) { } // Cleanup after ourselves. boost::filesystem::remove_all(paths->GetDefaultTestPath()); QVERIFY(dirCount == count / 2); } } // Generate a main function for the test QTEST_MAIN(DataLogger_TEST)
487e1c56a130ece0d240e4092c0a1e4c5e1d9817
40e136eccaeb639e0450c4d8cbd40d2769105e62
/Basics/Lab 02.cpp
d4c07db7c892cd15113e99f1c8a55ed525c67b3b
[]
no_license
patriciom2/LP1
357d4c76f505c49be3f9f3547cdab4e0b6e9a2d4
ff99f14b306f9dc1b6660a9e8cac92d3426dea1c
refs/heads/master
2020-05-03T06:28:51.400498
2019-05-09T17:29:32
2019-05-09T17:29:32
178,473,926
0
0
null
null
null
null
UTF-8
C++
false
false
223
cpp
#include <iostream> using namespace std; int main(){ int length =20; int width=40; int area=length*width; length=99; {int perimerter=(length+width)*2; } {int perimeter=length*2+width*2; } return 0; }
3d1f8008242fe6b73620c216c16a5bd91f005dde
1d60862290bde068d23bae55971942fa1479787e
/NewTank/Grass.h
b7c80f6599fbfd55fc53f311dd7f5f1956328baf
[]
no_license
NENCAO/TANK
a653855a885d0502beccb57958c9f70593114744
1b865a900174014df1e80b03dad903fac97442ae
refs/heads/master
2020-04-11T12:58:58.228138
2018-12-14T15:07:44
2018-12-14T15:07:44
161,798,796
0
0
null
null
null
null
UTF-8
C++
false
false
263
h
#pragma once #include "Item.h" class CGrass : public CItem { public: CGrass(int x, int y) { m_Pos.SetX(x); m_Pos.SetY(y); m_bDisapper = false; m_color = GREEN; this->CalculateSphere(); }; ~CGrass(); };
11be07ea45e9da9d35867d71a06c2f1faa70c009
6f811c09de0d2a582edbca26ecc7d054fcc380ed
/cpps/cpps_class.h
dc822c102dae3a82d3047d6cb93396a07554dec1
[]
no_license
akzi/cpps
5d80f2402eeea6d8c84a7d37449d2fedcd9719ab
ae577c01b6608ba0eebe882f59b9c7e0732cb7ad
refs/heads/master
2020-09-06T13:34:40.899864
2017-01-14T04:58:28
2017-01-14T04:58:28
null
0
0
null
null
null
null
GB18030
C++
false
false
1,593
h
#ifndef CPPS_CLASS_CPPS_HEAD_ #define CPPS_CLASS_CPPS_HEAD_ //=================================== //@Author : Johnson //@Email : [email protected] //@Date : 2015/12/10 (yy/mm/dd) //@Module : CPPS_CLASS //@Description : Cpps、C++类注册 //@website : http://cpps.wiki //================================== namespace cpps { struct cpps_cppsclassvar; template <class C> struct cpps_classvar; struct cpps_cppsclass : public cpps_domain { cpps_cppsclass(std::string _classname, Node *_o, cpps_domain* p, char type) :cpps_domain(p,type,_classname) { o = _o; classname = _classname; } virtual cpps_cppsclassvar * create(bool alloc = true) { return (new cpps_cppsclassvar(getClassName(), this, cpps_domain_type_classvar, alloc)); } std::string getClassName() { return classname; } Node *o; //定义的变量 std::string classname; }; template <class C> struct cpps_class : public cpps_cppsclass { cpps_class(std::string _classname,cpps_domain* p, char type) :cpps_cppsclass(_classname, NULL, p, type) { } virtual cpps_cppsclassvar * create(bool alloc = true) { return new cpps_classvar<C>(getClassName(),this, cpps_domain_type_classvar, alloc); } }; template <class C> struct cpps_class_singleton { cpps_class_singleton() { v = NULL; } void setsls(cpps_cppsclass *_v) { v = _v; } cpps_cppsclass *getcls() { return v; } static cpps_class_singleton<C>* getSingletonPtr() { static cpps_class_singleton<C> t; return &t; } cpps_cppsclass *v; }; } #endif // CPPS_CLASS_CPPS_HEAD_
7ce2a2064e201996468622f74a2629b0f665b5c8
b4e2870e505b3a576115fa9318aabfb971535aef
/zParserExtender/ZenGin/Gothic_II_Addon/API/zRndD3d_Init.h
518f3c339a5d48a66b03a3ad77cf93b5aa058613
[]
no_license
Gratt-5r2/zParserExtender
4289ba2e71748bbac0c929dd1941d151cdde46ff
ecf51966e4d8b4dc27e3bfaff06848fab69ec9f1
refs/heads/master
2023-01-07T07:35:15.720162
2022-10-08T15:58:41
2022-10-08T15:58:41
208,900,373
6
1
null
2023-01-02T21:53:03
2019-09-16T21:21:28
C++
UTF-8
C++
false
false
641
h
// Supported with union (c) 2018 Union team #ifndef __ZRND_D3D__INIT_H__VER3__ #define __ZRND_D3D__INIT_H__VER3__ #include "zRndD3d.h" namespace Gothic_II_Addon { struct dxDEVICE { public: char name[256]; char desc[256]; char DeviceName[256]; unsigned long hardware; unsigned long number; unsigned long dxguidflag; GUID guid; GUID dxguid; }; struct dxDDMODE { public: int w; int h; int bpp; }; struct zD3DTEX { public: int mode; zCTex_D3D* texture; // user API #include "zD3DTEX.inl" }; } // namespace Gothic_II_Addon #endif // __ZRND_D3D__INIT_H__VER3__
ed18f58fbbdf2f230db781bf34dc3ec992c4adae
2a420e00748482676374ef995942c2354e38e11c
/src/driver.cpp
15b76b8677c9f8a8b053bd827df39edb79fa925d
[]
no_license
Rowan-Gudmundsson/webasm-compiler
95387ec497d9d40a2d5352602c35c37619d0a1b0
e7810f66d81c1ce516e063ffd694cdbf7140b5a6
refs/heads/master
2020-04-14T03:47:07.906392
2019-01-05T04:11:02
2019-01-05T04:11:02
163,616,663
1
0
null
null
null
null
UTF-8
C++
false
false
1,060
cpp
#include "driver.h" int main(int argc, char** argv) { std::string input, output; if (argc > 1) { if (commandLineArgs(argc--, argv++, input, output)) { yyin = fopen(input.c_str(), "r"); try { // yydebug = 1; yyparse(); } catch (const SymbolError& err) { std::cout << "Symbol error exception thrown: " << err.what() << std::endl; } catch (...) { std::cout << "Threw from somewhere." << std::endl; } } else { std::cout << "Failed to open files" << std::endl; } } return 0; } int yyerror(char* err) { std::cout << "Parser error: " << err << std::endl << "At line: " << line_num << ", column: " << col_num << std::endl; return 1; } bool commandLineArgs(int argc, char** argv, std::string& input, std::string& output) { for (unsigned i = 0; i < argc; i++) { std::string arg = argv[i]; if (arg == "-o") { if (i < argc - 1) { output = argv[i + 1]; } else { return false; } } else if (i == argc - 1) { input = argv[i]; } } return true; }
088253b85934534f613aea12fbd1502ddc065dbd
dd6c7ebd047aa67aa266dfc7ef3f125dcaf9ed3a
/hazelcast/include/hazelcast/util/ConcurrentSet.h
8fac43f5361ea2b614929746dba9ae5295c5d101
[ "Apache-2.0" ]
permissive
skyend/hazelcast-cpp-client
e81009fa2b27cb53f33fe188b3205498ea7b5e11
a62e1ce20e17cf2a69e236918860c467e03babba
refs/heads/master
2020-04-22T00:17:51.954274
2019-02-13T09:17:54
2019-02-13T09:17:54
169,974,434
0
0
Apache-2.0
2019-02-10T12:13:36
2019-02-10T12:13:36
null
UTF-8
C++
false
false
4,216
h
/* * Copyright (c) 2008-2018, Hazelcast, Inc. 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. */ #ifndef HAZELCAST_UTIL_CONCURRENTSET_H_ #define HAZELCAST_UTIL_CONCURRENTSET_H_ #include "hazelcast/util/HazelcastDll.h" #include "hazelcast/util/LockGuard.h" #include "hazelcast/util/Mutex.h" #include <set> #include <vector> #include <boost/foreach.hpp> #if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) #pragma warning(push) #pragma warning(disable: 4251) //for dll export #endif namespace hazelcast { namespace util { template <typename T> class ConcurrentSet { public: ConcurrentSet() { } /** * Adds the specified element to this set if it is not already present * (optional operation). More formally, adds the specified element * <tt>e</tt> to this set if the set contains no element <tt>e2</tt> * such that * <tt>(e==e2)</tt>. * If this set already contains the element, the call leaves the set * unchanged and returns <tt>false</tt>. In combination with the * restriction on constructors, this ensures that sets never contain * duplicate elements. * * * @param e element to be added to this set * @return <tt>true</tt> if this set did not already contain the specified * element */ bool add(const T &e) { util::LockGuard lg(m); return internalSet.insert(e).second; } /** * Returns the number of elements in this set (its cardinality). * * @return the number of elements in this set (its cardinality) */ size_t size() { util::LockGuard lg(m); return internalSet.size(); } /** * Returns <tt>true</tt> if this set contains no elements. * * @return <tt>true</tt> if this set contains no elements */ bool isEmpty() { util::LockGuard lg(m); return internalSet.empty(); } /** * Returns an array containing all of the elements in this set. * If this set makes any guarantees as to what order its elements * are returned by its iterator, this method must return the * elements in the same order. * * <p>The returned array will be "safe" in that no references to it * are maintained by this set. (In other words, this method must * allocate a new array even if this set is backed by an array). * The caller is thus free to modify the returned array. * * @return an array containing all the elements in this set */ std::vector<T> toArray() { util::LockGuard lg(m); std::vector<T> result; BOOST_FOREACH(const typename std::set<T>::value_type &value , internalSet) { result.push_back(value); } return result; } void clear() { util::LockGuard lg(m); internalSet.clear(); } private: util::Mutex m; std::set<T> internalSet; }; } } #if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) #pragma warning(pop) #endif #endif //HAZELCAST_UTIL_CONCURRENTSET_H_
f3fefafe091ea6b0aad988b70dcc3f7da24f3914
2863fa5fe44cbf3008583dc44ef3925e6b599df4
/typedefs.h
3f94d23ece29ad91a0e446f9c93ab1a8058c45d3
[]
no_license
lsem/ipcmessaging
4af20e43119fce3cc7d54fed5eb75fe229457e25
15205c3d4aa9f4cb41fdc8789a54ab72a18dd11c
refs/heads/master
2021-06-07T17:25:12.602098
2015-04-21T19:43:13
2015-04-21T19:43:13
34,348,446
0
0
null
null
null
null
UTF-8
C++
false
false
497
h
#pragma once class HandlerBase { }; typedef unsigned typeid_t; template <class TMessage> class IHandle : public HandlerBase { public: virtual void Handle(const TMessage &message) = 0; }; template <class TMessage> struct TypeIdResolver { public: static int constexpr getType(); }; #define DEFINE_TYPE_ID_FOR(XMessageClassName, XMessageClassId) \ template<> struct TypeIdResolver<XMessageClassName> { \ static int constexpr getType() { return XMessageClassId; } \ };
3e929acb723c454c948bc2ed1e2bdc48188c19d0
ccd1fce7642521ba5e4b5ad5038f23ef2844174b
/src/List.h
5304bf3551c1ef41efe5248f168a26126681dd2a
[]
no_license
rzepkamichal/Nibbles-Game
a0d72e7f62b431f7540d83b74564c69121d8cd54
cba96b8e821783c62269ffb49f4c332d884e6916
refs/heads/master
2020-04-26T20:37:02.457452
2019-03-04T20:28:16
2019-03-04T20:28:16
173,815,952
1
0
null
null
null
null
UTF-8
C++
false
false
2,518
h
#ifndef NIBBELS_LIST_H #define NIBBELS_LIST_H #include "Node.h" #include <iostream> using namespace std; template <class T> class List{ private: //Wskaźnik na głowę listy typu T Node<T>* head; //rozmiar listy int size; public: /*Konstruktor domyślny. *Ustawia wartość head na nullptr. *Ustawia wartość size na 0. */ List(); /*Domyślny destruktor *Usuwa elementy listy. */ ~List(); /*isEmpty *zwraca: * - true, jeżeli size jest równe zero * - false w przeciwnym przypadku */ bool isEmpty(); /*PushBack *Dodaje element o wartości item typu T na koniec listy. *Inkrementuje pole size. */ void PushBack(T item); /*getNode *Zwraca przez referencję obiekt listy o indeksie index. */ T& getNode(int index); /*getLast *Zwraca przez referencję ostatni obiekt listy. */ T& getLast(); /*getSize *Zwraca wartość size. */ int getSize(); //void clear(); }; template<class T> List<T>::List() { head = nullptr; this->size = 0; } template<class T> bool List<T>::isEmpty() { return head == nullptr; } template<class T> void List<T>::PushBack(T item) { Node<T>* newNode = new Node<T>(); newNode->item = item; newNode->pNext = nullptr; if(isEmpty()){ head = newNode; }else{ Node<T>* pNode = head; while(pNode->pNext){ pNode = pNode->pNext; } pNode->pNext = newNode; } size++; } template<class T> T& List<T>::getNode(int index) { Node<T>* pNode = head; for(int i=0; i<index;i++){ pNode = pNode->pNext; } return pNode->item; } template<class T> List<T>::~List() { //cout << "i'm in destructor" << endl; Node<T>* pNode = head; Node<T>* nextNode; while(pNode){ nextNode = pNode->pNext; delete pNode; pNode = nextNode; } } /* template<class T> void List<T>::clear() { Node<T>* pNode = head; Node<T>* nextNode; head = nullptr; while(pNode){ nextNode = pNode->pNext; delete pNode; pNode = nullptr; //cout << "node deleted!" << endl; pNode = nextNode; } size = 0; }*/ template<class T> int List<T>::getSize() { return this->size; } template<class T> T &List<T>::getLast() { Node<T>* pNode = head; for(int i=0; i<size-1;i++){ pNode = pNode->pNext; } return pNode->item;; } #endif
6a2133d2ec7e9cbb7b2c36765f1a906bcfe94288
e655e6f46cc6d4de96e0d6367469716d824b6063
/src/SalesDepartmentModule/test/SalesmanTest.cpp
44b9341dfce2f2dfde20861e600465c192dd8b80
[ "MIT" ]
permissive
imefisto/catchcmake-modular
2879159601b9037671e3a9d09c0219d8d9ab15bc
9bf063d191a00a603aca57d2b87405d77171fcfb
refs/heads/master
2021-01-17T21:11:58.396264
2016-06-30T21:38:13
2016-06-30T21:38:13
62,343,430
0
0
null
null
null
null
UTF-8
C++
false
false
374
cpp
#include "catch.hpp" #include "SalesDepartmentModule/Salesman.h" SCENARIO( "Salesman Entity", "[SalesDepartmentModule]" ) { GIVEN( "A salesman" ) { WHEN( "it is created" ) { SalesDepartmentModule::Salesman salesMan; THEN("getVendorCode should return an empty string") { REQUIRE(salesMan.getVendorCode().length() == 0 ); } } } }
334ae172ddae48eb42c790907dfc3374dcf708d6
989885eef1dbe1fa5cc884dea27a77be123ce3ad
/visual_words.cpp
4e5eb2efaf0842b2e1bfefbe5f821f96c0fe4792
[]
no_license
aidiary/visual_words
777188e9a7aef138ead5e06b17bf41885d31c8a8
40caf3b57f399962f4722ade8043b027d29d8173
refs/heads/master
2021-01-12T04:07:34.858418
2016-12-28T06:07:53
2016-12-28T06:07:53
77,507,533
0
0
null
null
null
null
UTF-8
C++
false
false
7,669
cpp
#include <cv.h> #include <highgui.h> #include <iostream> #include <fstream> #include <dirent.h> using namespace std; const char* IMAGE_DIR = "caltech10"; const int DIM = 128; const int SURF_PARAM = 400; const int MAX_CLUSTER = 500; // クラスタ数 = Visual Wordsの次元数 /** * 画像ファイルからSURF特徴量を抽出する * @param[in] filename 画像ファイル名 * @param[out] imageKeypoints キーポイント * @param[out] imageDescriptors 各キーポイントのSURF特徴量 * @param[out] storage メモリ領域 * @return 成功なら0、失敗なら1 */ int extractSURF(const char* filename, CvSeq** keypoints, CvSeq** descriptors, CvMemStorage** storage) { // グレースケールで画像をロードする IplImage* img = cvLoadImage(filename, CV_LOAD_IMAGE_GRAYSCALE); if (img == NULL) { cerr << "cannot load image: " << filename << endl; return 1; } *storage = cvCreateMemStorage(0); CvSURFParams params = cvSURFParams(SURF_PARAM, 1); cvExtractSURF(img, 0, keypoints, descriptors, *storage, params); return 0; } /** * IMAGE_DIRにある全画像から局所特徴量を抽出し行列へ格納する * @param[out] samples 局所特徴量の行列 * @param[out] data samplesのデータ領域 * @return 成功なら0、失敗なら1 */ int loadDescriptors(CvMat& samples, vector<float>& data) { // IMAGE_DIRを開く DIR* dp; if ((dp = opendir(IMAGE_DIR)) == NULL) { cerr << "cannot open directory: " << IMAGE_DIR << endl; return 1; } // IMAGE_DIRの画像ファイル名を走査 struct dirent* entry; while ((entry = readdir(dp)) != NULL) { char* filename = entry->d_name; if (strcmp(filename, ".") == 0 || strcmp(filename, "..") == 0) { continue; } // パス名に変換 // XXX.jpg -> IMAGE_DIR/XXX.jpg char filepath[256]; snprintf(filepath, sizeof filepath, "%s/%s", IMAGE_DIR, filename); // SURFを抽出 CvSeq* keypoints = NULL; CvSeq* descriptors = NULL; CvMemStorage* storage = NULL; int ret = extractSURF(filepath, &keypoints, &descriptors, &storage); if (ret != 0) { cerr << "error in extractSURF" << endl; return 1; } // ファイル名と局所特徴点の数を表示 cout << filepath << "\t" << descriptors->total << endl; // 特徴量を構造化せずにdataへ追加 for (int i = 0; i < descriptors->total; i++) { float* d = (float*)cvGetSeqElem(descriptors, i); // 128次元ベクトル for (int j = 0; j < DIM; j++) { data.push_back(d[j]); } } cvClearSeq(keypoints); cvClearSeq(descriptors); cvReleaseMemStorage(&storage); } // dataをCvMat形式に変換 // CvMatはdataを参照するためdataは解放されないので注意 int rows = data.size() / DIM; // CvMatの行数(=DIM次元特徴ベクトルの本数) cvInitMatHeader(&samples, rows, DIM, CV_32FC1, &data[0]); return 0; } /** * IMAEG_DIRの全画像をヒストグラムに変換して出力 * 各画像の各局所特徴量を一番近いVisual Wordsに投票してヒストグラムを作成する * @param[in] visualWords Visual Words * @return 成功なら0、失敗なら1 */ int calcHistograms(CvMat* visualWords) { // 一番近いVisual Wordsを高速検索できるようにvisualWordsをkd-treeでインデキシング CvFeatureTree* ft = cvCreateKDTree(visualWords); // 各画像のヒストグラムを出力するファイルを開く fstream fout; fout.open("histograms.txt", ios::out); if (!fout.is_open()) { cerr << "cannot open file: histograms.txt" << endl; return 1; } // IMAGE_DIRの各画像をヒストグラムに変換 DIR* dp; if ((dp = opendir(IMAGE_DIR)) == NULL) { cerr << "cannot open directory: " << IMAGE_DIR << endl; return 1; } struct dirent* entry; while ((entry = readdir(dp)) != NULL) { char* filename = entry->d_name; if (strcmp(filename, ".") == 0 || strcmp(filename, "..") == 0) { continue; } char filepath[256]; snprintf(filepath, sizeof filepath, "%s/%s", IMAGE_DIR, filename); // ヒストグラムを初期化 int* histogram = new int[visualWords->rows]; for (int i = 0; i < visualWords->rows; i++) { histogram[i] = 0; } // SURFを抽出 CvSeq* keypoints = NULL; CvSeq* descriptors = NULL; CvMemStorage* storage = NULL; int ret = extractSURF(filepath, &keypoints, &descriptors, &storage); if (ret != 0) { cerr << "error in extractSURF" << endl; return 1; } // kd-treeで高速検索できるように特徴ベクトルをCvMatに展開 CvMat* mat = cvCreateMat(descriptors->total, DIM, CV_32FC1); CvSeqReader reader; float* ptr = mat->data.fl; cvStartReadSeq(descriptors, &reader); for (int i = 0; i < descriptors->total; i++) { float* desc = (float*)reader.ptr; CV_NEXT_SEQ_ELEM(reader.seq->elem_size, reader); memcpy(ptr, desc, DIM*sizeof(float)); ptr += DIM; } // 各局所特徴点についてもっとも類似したVisual Wordsを見つけて投票 int k = 1; // 1-NN CvMat* indices = cvCreateMat(keypoints->total, k, CV_32SC1); // もっとも近いVisual Wordsのインデックス CvMat* dists = cvCreateMat(keypoints->total, k, CV_64FC1); // その距離 cvFindFeatures(ft, mat, indices, dists, k, 250); for (int i = 0; i < indices->rows; i++) { int idx = CV_MAT_ELEM(*indices, int, i, 0); histogram[idx] += 1; } // ヒストグラムをファイルに出力 fout << filepath << "\t"; for (int i = 0; i < visualWords->rows; i++) { fout << float(histogram[i]) / float(descriptors->total) << "\t"; } fout << endl; // 後始末 delete[] histogram; cvClearSeq(keypoints); cvClearSeq(descriptors); cvReleaseMemStorage(&storage); cvReleaseMat(&mat); cvReleaseMat(&indices); cvReleaseMat(&dists); } fout.close(); cvReleaseFeatureTree(ft); return 0; } int main() { int ret; // IMAGE_DIRの各画像から局所特徴量を抽出 cout << "Load Descriptors ..." << endl; CvMat samples; vector<float> data; ret = loadDescriptors(samples, data); // 局所特徴量をクラスタリングして各クラスタのセントロイドを計算 cout << "Clustering ..." << endl; CvMat* labels = cvCreateMat(samples.rows, 1, CV_32S); // 各サンプル点が割り当てられたクラスタのラベル CvMat* centroids = cvCreateMat(MAX_CLUSTER, DIM, CV_32FC1); // 各クラスタの中心(セントロイド) DIM次元ベクトル cvKMeans2(&samples, MAX_CLUSTER, labels, cvTermCriteria(CV_TERMCRIT_EPS+CV_TERMCRIT_ITER, 10, 1.0), 1, 0, 0, centroids, 0); cvReleaseMat(&labels); // ラベルは使わない // 各画像をVisual Wordsのヒストグラムに変換する // 各クラスターの中心ベクトル、centroidsがそれぞれVisual Wordsになる cout << "Calc Histograms ..." << endl; calcHistograms(centroids); cvReleaseMat(&centroids); return 0; }
75fa0311de00f5471dae5381050afd984ef850d6
560090526e32e009e2e9331e8a2b4f1e7861a5e8
/Compiled/blaze-3.2/blazetest/src/mathtest/smatsmatmult/DCaMCa.cpp
b4ba12053032c7b262170de935ef0378e9ccf1f5
[ "BSD-3-Clause" ]
permissive
jcd1994/MatlabTools
9a4c1f8190b5ceda102201799cc6c483c0a7b6f7
2cc7eac920b8c066338b1a0ac495f0dbdb4c75c1
refs/heads/master
2021-01-18T03:05:19.351404
2018-02-14T02:17:07
2018-02-14T02:17:07
84,264,330
2
0
null
null
null
null
UTF-8
C++
false
false
5,152
cpp
//================================================================================================= /*! // \file src/mathtest/smatsmatmult/DCaMCa.cpp // \brief Source file for the DCaMCa sparse matrix/sparse matrix multiplication math test // // Copyright (C) 2012-2017 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. */ //================================================================================================= //************************************************************************************************* // Includes //************************************************************************************************* #include <cstdlib> #include <iostream> #include <blaze/math/CompressedMatrix.h> #include <blaze/math/DiagonalMatrix.h> #include <blazetest/mathtest/Creator.h> #include <blazetest/mathtest/smatsmatmult/OperationTest.h> #include <blazetest/system/MathTest.h> //================================================================================================= // // MAIN FUNCTION // //================================================================================================= //************************************************************************************************* int main() { std::cout << " Running 'DCaMCa'..." << std::endl; using blazetest::mathtest::TypeA; try { // Matrix type definitions typedef blaze::DiagonalMatrix< blaze::CompressedMatrix<TypeA> > DCa; typedef blaze::CompressedMatrix<TypeA> MCa; // Creator type definitions typedef blazetest::Creator<DCa> CDCa; typedef blazetest::Creator<MCa> CMCa; // Running tests with small matrices for( size_t i=0UL; i<=6UL; ++i ) { for( size_t j=0UL; j<=6UL; ++j ) { RUN_SMATSMATMULT_OPERATION_TEST( CDCa( i, 0UL ), CMCa( i, j, 0UL ) ); RUN_SMATSMATMULT_OPERATION_TEST( CDCa( i, 0UL ), CMCa( i, j, 0.3*i*j ) ); RUN_SMATSMATMULT_OPERATION_TEST( CDCa( i, 0UL ), CMCa( i, j, i*j ) ); RUN_SMATSMATMULT_OPERATION_TEST( CDCa( i, 0.5*i ), CMCa( i, j, 0UL ) ); RUN_SMATSMATMULT_OPERATION_TEST( CDCa( i, 0.5*i ), CMCa( i, j, 0.3*i*j ) ); RUN_SMATSMATMULT_OPERATION_TEST( CDCa( i, 0.5*i ), CMCa( i, j, i*j ) ); RUN_SMATSMATMULT_OPERATION_TEST( CDCa( i, i ), CMCa( i, j, 0UL ) ); RUN_SMATSMATMULT_OPERATION_TEST( CDCa( i, i ), CMCa( i, j, 0.3*i*j ) ); RUN_SMATSMATMULT_OPERATION_TEST( CDCa( i, i ), CMCa( i, j, i*j ) ); } } // Running tests with large matrices RUN_SMATSMATMULT_OPERATION_TEST( CDCa( 15UL, 7UL ), CMCa( 15UL, 37UL, 7UL ) ); RUN_SMATSMATMULT_OPERATION_TEST( CDCa( 37UL, 7UL ), CMCa( 37UL, 37UL, 7UL ) ); RUN_SMATSMATMULT_OPERATION_TEST( CDCa( 63UL, 13UL ), CMCa( 63UL, 37UL, 13UL ) ); RUN_SMATSMATMULT_OPERATION_TEST( CDCa( 16UL, 8UL ), CMCa( 16UL, 32UL, 8UL ) ); RUN_SMATSMATMULT_OPERATION_TEST( CDCa( 32UL, 8UL ), CMCa( 32UL, 32UL, 8UL ) ); RUN_SMATSMATMULT_OPERATION_TEST( CDCa( 64UL, 16UL ), CMCa( 64UL, 32UL, 16UL ) ); } catch( std::exception& ex ) { std::cerr << "\n\n ERROR DETECTED during sparse matrix/sparse matrix multiplication:\n" << ex.what() << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; } //*************************************************************************************************
fafcdf912d27504803ce02946ea82bc57befbf0e
8196646272f1f4ecb0f40da8244e5e939d9e810d
/libs/ledger/include/ledger/dag/dag.hpp
5fa9237d6005e326ba47df3dcdf82119d271107c
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "LicenseRef-scancode-unknown" ]
permissive
cyenyxe/ledger
8301afb23eec536ca58c68ad5ebe768195ec7861
6b42c3a3a5c78d257a02634437f9e00d1439690b
refs/heads/master
2020-08-03T20:03:57.083802
2019-10-09T16:36:53
2019-10-09T16:36:53
211,869,302
0
0
Apache-2.0
2019-11-04T11:56:34
2019-09-30T13:42:35
C++
UTF-8
C++
false
false
8,148
hpp
#pragma once //------------------------------------------------------------------------------ // // Copyright 2018-2019 Fetch.AI Limited // // 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 "core/byte_array/byte_array.hpp" #include "core/byte_array/const_byte_array.hpp" #include "core/mutex.hpp" #include "core/serializers/base_types.hpp" #include "core/serializers/main_serializer.hpp" #include "crypto/ecdsa.hpp" #include "crypto/fnv.hpp" #include "crypto/identity.hpp" #include "crypto/sha256.hpp" #include "ledger/dag/dag_epoch.hpp" #include "ledger/dag/dag_interface.hpp" #include "ledger/dag/dag_node.hpp" #include "ledger/upow/work.hpp" #include "storage/object_store.hpp" #include <cstdint> #include <deque> #include <limits> #include <list> #include <queue> #include <unordered_map> #include <unordered_set> #include <utility> #include <vector> namespace fetch { namespace crypto { class Prover; } namespace ledger { struct DAGTip { using ConstByteArray = byte_array::ConstByteArray; DAGTip(ConstByteArray dag_node_ref, uint64_t epoch, uint64_t wei) : dag_node_reference{std::move(dag_node_ref)} , oldest_epoch_referenced{epoch} , weight{wei} { static uint64_t ids = 1; id = ids++; } ConstByteArray dag_node_reference; // Refers to a DagNode that has no references to it uint64_t oldest_epoch_referenced = 0; uint64_t weight = 0; uint64_t id = 0; }; /** * DAG implementation. */ class DAG : public DAGInterface { private: using ByteArray = byte_array::ByteArray; using ConstByteArray = byte_array::ConstByteArray; using EpochStore = fetch::storage::ObjectStore<DAGEpoch>; using DAGNodeStore = fetch::storage::ObjectStore<DAGNode>; using NodeHash = ConstByteArray; using EpochHash = ConstByteArray; using EpochStackStore = fetch::storage::ObjectStore<EpochHash>; using DAGTipID = uint64_t; using DAGTipPtr = std::shared_ptr<DAGTip>; using DAGNodePtr = std::shared_ptr<DAGNode>; using Mutex = std::recursive_mutex; using CertificatePtr = std::shared_ptr<crypto::Prover>; using DAGTypes = DAGInterface::DAGTypes; public: using MissingNodeHashes = std::set<NodeHash>; using MissingNodes = std::set<DAGNode>; DAG() = delete; DAG(std::string db_name, bool load, CertificatePtr certificate); DAG(DAG const &rhs) = delete; DAG(DAG &&rhs) = delete; DAG &operator=(DAG const &rhs) = delete; DAG &operator=(DAG &&rhs) = delete; static constexpr char const *LOGGING_NAME = "DAG"; static const uint64_t PARAMETER_REFERENCES_TO_BE_TIP = 2; // Must be > 1 as 1 reference signifies pointing at a DAGEpoch static const uint64_t EPOCH_VALIDITY_PERIOD = 2; static const uint64_t LOOSE_NODE_LIFETIME = EPOCH_VALIDITY_PERIOD; static const uint64_t MAX_TIPS_IN_EPOCH = 30; // Interface for adding what internally becomes a dag node. Easy to modify this interface // so do as you like with it Ed void AddTransaction(Transaction const &tx, DAGTypes type) override; void AddWork(Work const &solution) override; void AddArbitrary(ConstByteArray const &payload) override; // Create an epoch based on the current DAG (not committal) DAGEpoch CreateEpoch(uint64_t block_number) override; // Commit the state of the DAG as this node believes it (using an epoch) bool CommitEpoch(DAGEpoch new_epoch) override; // Revert to a previous/forward epoch bool RevertToEpoch(uint64_t epoch_bn_to_revert) override; uint64_t CurrentEpoch() const override; bool HasEpoch(EpochHash const &hash) override; // Make sure that the dag has all nodes for a certain epoch bool SatisfyEpoch(DAGEpoch const &epoch) override; std::vector<DAGNode> GetLatest(bool previous_epoch_only) override; /////////////////////////////////////// // Fns used for syncing // Recently added DAG nodes by this miner (not seen by network yet) std::vector<DAGNode> GetRecentlyAdded() override; // DAG node hashes this miner knows should exist MissingNodeHashes GetRecentlyMissing() override; bool GetDAGNode(ConstByteArray const &hash, DAGNode &node) override; bool GetWork(ConstByteArray const &hash, Work &work) override; // TXs and epochs will be added here when they are broadcast in bool AddDAGNode(DAGNode node) override; private: // Long term storage uint64_t most_recent_epoch_ = 0; DAGEpoch previous_epoch_; // Most recent epoch, not in deque for convenience std::deque<DAGEpoch> previous_epochs_; // N - 1 still relevant epochs EpochStackStore epochs_; // Past less-relevant epochs as a stack (key = index, value = hash) EpochStore all_stored_epochs_; // All epochs, including from non-winning forks (key = epoch hash, // val = epoch) DAGNodeStore finalised_dag_nodes_; // Once an epoch arrives, all dag nodes in between go here // clang-format off // volatile state std::unordered_map<DAGTipID, DAGTipPtr> all_tips_; // All tips are here std::unordered_map<NodeHash, DAGTipPtr> tips_; // lookup tips of the dag pointing at a certain node hash std::unordered_map<NodeHash, DAGNodePtr> node_pool_; // dag nodes that are not finalised but are still valid std::unordered_map<NodeHash, DAGNodePtr> loose_nodes_; // nodes that are missing one or more references (waiting on NodeHash) std::unordered_map<NodeHash, std::vector<DAGNodePtr>> loose_nodes_lookup_; // nodes that are missing one or more references (waiting on NodeHash) // clang-format on // TODO(1642): loose nodes management scheme // std::unordered_map<NodeHash, uint64_t> loose_nodes_ttl_; // Used for sync purposes std::vector<DAGNode> recently_added_; // nodes that have been recently added std::set<NodeHash> missing_; // node hashes that we know are missing // Internal functions don't need locking and can recursively call themselves etc. bool PushInternal(DAGNodePtr const &node); bool AlreadySeenInternal(DAGNodePtr const &node) const; bool TooOldInternal(uint64_t oldest_reference) const; bool IsLooseInternal(DAGNodePtr const &node) const; void SetReferencesInternal(DAGNodePtr const &node); void AdvanceTipsInternal(DAGNodePtr const &node); bool HashInPrevEpochsInternal(ConstByteArray const &hash) const; void AddLooseNodeInternal(DAGNodePtr const &node); void HealLooseBlocksInternal(ConstByteArray const &added_hash); void UpdateStaleTipsInternal(); bool NodeInvalidInternal(DAGNodePtr const &node); DAGNodePtr GetDAGNodeInternal(ConstByteArray const &hash, bool including_loose, bool &was_loose); // const void TraverseFromTips(std::set<ConstByteArray> const & tip_hashes, std::function<void(NodeHash)> const &on_node, std::function<bool(NodeHash)> const &terminating_condition); bool GetEpochFromStorage(std::string const &identifier, DAGEpoch &epoch); bool SetEpochInStorage(std::string const & /*unused*/, DAGEpoch const &epoch, bool is_head); void Flush(); void DeleteTip(DAGTipID tip_id); void DeleteTip(NodeHash const &hash); std::string db_name_; CertificatePtr certificate_; mutable Mutex mutex_; }; } // namespace ledger } // namespace fetch
8d6cd426d5a450f176c22d96b20bea6942980172
0ac047a44db9e8634568a00876bc66d78e30b404
/lxc0201/lxc0201/源.cpp
2e3f9dcd4b80994a5e591724fab742e59cc3c7c5
[]
no_license
Y1231/test1
2a7dd1d2834f0c79349b073acc46412352fbad71
9fd0099dc663958525d4d131a6a067af7ee3bdb7
refs/heads/master
2022-04-12T16:29:55.787166
2020-02-01T07:29:25
2020-02-01T07:29:25
null
0
0
null
null
null
null
GB18030
C++
false
false
1,300
cpp
//好久没打码,真是太颓废了,今天决定打个码,熟悉一下生 #include<stdio.h> #include<stdlib.h> #include<time.h> #define SUITS 4 #define FACES 13 #define CARDS 52 //prototypes void shuffle(unsigned int wDeck[][FACES]); void deal(unsigned int wDeck[][FACES], const char *wFace[], const char *wSuit[]); int main(void) { unsigned int deck[SUITS][FACES] = { 0 }; srand(time(NULL)); shuffle(deck); const char *suit[SUITS] = { "Hearts", "Diamonds", "Clubs", "Spades" }; const char *face[FACES] = { "Ace", "Deuce", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King" }; deal(deck, face, suit); } void shuffle(unsigned int wDeck[][FACES]) { for (size_t card = 1; card <= CARDS; ++card){ size_t row; size_t column; do{ row = rand() % SUITS; column = rand() % FACES; } while (wDeck[row][column] != 0); wDeck[row][column] = card; } } void deal(unsigned int wDeck[][FACES], const char *wFace[], const char *wSuit[]) { for (size_t card = 1; card <= CARDS; ++card){ for (size_t row = 0; row <= SUITS; ++row){ for (size_t column = 0; column < FACES; ++column){ if (wDeck[row][column] == card){ printf("%5s of %-8s%c", wFace[column], wSuit[row], card % 2 == 0 ? '\n' : '\t'); } } } } }
64619e3c8e4e1a54cf9dba3ad7174a2a0776351c
1d0abd14aa46816c2cfa81a28efd5a17e359c356
/dbms/src/Common/ZooKeeper/ZooKeeperImpl.cpp
0d8bc8de72565a0ddf9ad8c8a0903f5bd11435c9
[ "Apache-2.0" ]
permissive
hustjieke/ClickHouse
26cac1ddf3ab59b771a924d0e102a60f5432ef75
7f294007cbdc2df819ca1e58c4409eec7926e82f
refs/heads/master
2020-03-20T03:33:11.260936
2018-06-13T00:51:23
2018-06-13T00:51:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
46,848
cpp
#include <Common/ZooKeeper/ZooKeeperImpl.h> #include <Common/Exception.h> #include <Common/ProfileEvents.h> #include <Common/setThreadName.h> #include <Common/typeid_cast.h> #include <IO/WriteHelpers.h> #include <IO/ReadHelpers.h> #include <IO/Operators.h> #include <IO/WriteBufferFromString.h> #include <Poco/Exception.h> #include <Poco/Net/NetException.h> #include <array> namespace DB { namespace ErrorCodes { extern const int KEEPER_EXCEPTION; } } namespace ProfileEvents { extern const Event ZooKeeperExceptions; extern const Event ZooKeeperInit; extern const Event ZooKeeperTransactions; extern const Event ZooKeeperCreate; extern const Event ZooKeeperRemove; extern const Event ZooKeeperExists; extern const Event ZooKeeperMulti; extern const Event ZooKeeperGet; extern const Event ZooKeeperSet; extern const Event ZooKeeperList; extern const Event ZooKeeperCheck; extern const Event ZooKeeperClose; extern const Event ZooKeeperWaitMicroseconds; extern const Event ZooKeeperBytesSent; extern const Event ZooKeeperBytesReceived; extern const Event ZooKeeperWatchResponse; } namespace CurrentMetrics { extern const Metric ZooKeeperRequest; extern const Metric ZooKeeperWatch; } /** ZooKeeper wire protocol. Debugging example: strace -t -f -e trace=network -s1000 -x ./clickhouse-zookeeper-cli localhost:2181 All numbers are in network byte order (big endian). Sizes are 32 bit. Numbers are signed. zxid - incremental transaction number at server side. xid - unique request number at client side. Client connects to one of the specified hosts. Client sends: int32_t sizeof_connect_req; \x00\x00\x00\x2c (44 bytes) struct connect_req { int32_t protocolVersion; \x00\x00\x00\x00 (Currently zero) int64_t lastZxidSeen; \x00\x00\x00\x00\x00\x00\x00\x00 (Zero at first connect) int32_t timeOut; \x00\x00\x75\x30 (Session timeout in milliseconds: 30000) int64_t sessionId; \x00\x00\x00\x00\x00\x00\x00\x00 (Zero at first connect) int32_t passwd_len; \x00\x00\x00\x10 (16) char passwd[16]; \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00 (Zero at first connect) }; Server replies: struct prime_struct { int32_t len; \x00\x00\x00\x24 (36 bytes) int32_t protocolVersion; \x00\x00\x00\x00 int32_t timeOut; \x00\x00\x75\x30 int64_t sessionId; \x01\x62\x2c\x3d\x82\x43\x00\x27 int32_t passwd_len; \x00\x00\x00\x10 char passwd[16]; \x3b\x8c\xe0\xd4\x1f\x34\xbc\x88\x9c\xa7\x68\x69\x78\x64\x98\xe9 }; Client remembers session id and session password. Client may send authentication request (optional). Each one third of timeout, client sends heartbeat: int32_t length_of_heartbeat_request \x00\x00\x00\x08 (8) int32_t ping_xid \xff\xff\xff\xfe (-2, constant) int32_t ping_op \x00\x00\x00\x0b ZOO_PING_OP 11 Server replies: int32_t length_of_heartbeat_response \x00\x00\x00\x10 int32_t ping_xid \xff\xff\xff\xfe int64 zxid \x00\x00\x00\x00\x00\x01\x87\x98 (incremental server generated number) int32_t err \x00\x00\x00\x00 Client sends requests. For example, create persistent node '/hello' with value 'world'. int32_t request_length \x00\x00\x00\x3a int32_t xid \x5a\xad\x72\x3f Arbitary number. Used for identification of requests/responses. libzookeeper uses unix timestamp for first xid and then autoincrement to that value. int32_t op_num \x00\x00\x00\x01 ZOO_CREATE_OP 1 int32_t path_length \x00\x00\x00\x06 path \x2f\x68\x65\x6c\x6c\x6f /hello int32_t data_length \x00\x00\x00\x05 data \x77\x6f\x72\x6c\x64 world ACLs: int32_t num_acls \x00\x00\x00\x01 ACL: int32_t permissions \x00\x00\x00\x1f string scheme \x00\x00\x00\x05 \x77\x6f\x72\x6c\x64 world string id \x00\x00\x00\x06 \x61\x6e\x79\x6f\x6e\x65 anyone int32_t flags \x00\x00\x00\x00 Server replies: int32_t response_length \x00\x00\x00\x1a int32_t xid \x5a\xad\x72\x3f int64 zxid \x00\x00\x00\x00\x00\x01\x87\x99 int32_t err \x00\x00\x00\x00 string path_created \x00\x00\x00\x06 \x2f\x68\x65\x6c\x6c\x6f /hello - may differ to original path in case of sequential nodes. Client may place a watch in their request. For example, client sends "exists" request with watch: request length \x00\x00\x00\x12 xid \x5a\xae\xb2\x0d op_num \x00\x00\x00\x03 path \x00\x00\x00\x05 \x2f\x74\x65\x73\x74 /test bool watch \x01 Server will send response as usual. And later, server may send special watch event. struct WatcherEvent { int32_t type; int32_t state; char * path; }; response length \x00\x00\x00\x21 special watch xid \xff\xff\xff\xff special watch zxid \xff\xff\xff\xff\xff\xff\xff\xff err \x00\x00\x00\x00 type \x00\x00\x00\x02 DELETED_EVENT_DEF 2 state \x00\x00\x00\x03 CONNECTED_STATE_DEF 3 path \x00\x00\x00\x05 \x2f\x74\x65\x73\x74 /test Example of multi request: request length \x00\x00\x00\x82 130 xid \x5a\xae\xd6\x16 op_num \x00\x00\x00\x0e 14 for every command: int32_t type; \x00\x00\x00\x01 create bool done; \x00 false int32_t err; \xff\xff\xff\xff -1 path \x00\x00\x00\x05 \x2f\x74\x65\x73\x74 /test data \x00\x00\x00\x06 \x6d\x75\x6c\x74\x69\x31 multi1 acl \x00\x00\x00\x01 \x00\x00\x00\x1f \x00\x00\x00\x05 \x77\x6f\x72\x6c\x64 world \x00\x00\x00\x06 \x61\x6e\x79\x6f\x6e\x65 anyone flags \x00\x00\x00\x00 int32_t type; \x00\x00\x00\x05 set bool done \x00 false int32_t err; \xff\xff\xff\xff -1 path \x00\x00\x00\x05 \x2f\x74\x65\x73\x74 data \x00\x00\x00\x06 \x6d\x75\x6c\x74\x69\x32 multi2 version \xff\xff\xff\xff int32_t type \x00\x00\x00\x02 remove bool done \x00 int32_t err \xff\xff\xff\xff -1 path \x00\x00\x00\x05 \x2f\x74\x65\x73\x74 version \xff\xff\xff\xff after commands: int32_t type \xff\xff\xff\xff -1 bool done \x01 true int32_t err \xff\xff\xff\xff Example of multi response: response length \x00\x00\x00\x81 129 xid \x5a\xae\xd6\x16 zxid \x00\x00\x00\x00\x00\x01\x87\xe1 err \x00\x00\x00\x00 in a loop: type \x00\x00\x00\x01 create done \x00 err \x00\x00\x00\x00 path_created \x00\x00\x00\x05 \x2f\x74\x65\x73\x74 type \x00\x00\x00\x05 set done \x00 err \x00\x00\x00\x00 stat \x00\x00\x00\x00\x00\x01\x87\xe1 \x00\x00\x00\x00\x00\x01\x87\xe1 \x00\x00\x01\x62\x3a\xf4\x35\x0c \x00\x00\x01\x62\x3a\xf4\x35\x0c \x00\x00\x00\x01 \x00\x00\x00\x00 \x00\x00\x00\x00 \x00\x00\x00\x00\x00\x00\x00\x00 \x00\x00\x00\x06 \x00\x00\x00\x00 \x00\x00\x00\x00\x00\x01\x87\xe1 type \x00\x00\x00\x02 remove done \x00 err \x00\x00\x00\x00 after: type \xff\xff\xff\xff done \x01 err \xff\xff\xff\xff */ namespace ZooKeeperImpl { Exception::Exception(const std::string & msg, const int32_t code, int) : DB::Exception(msg, DB::ErrorCodes::KEEPER_EXCEPTION), code(code) { ProfileEvents::increment(ProfileEvents::ZooKeeperExceptions); } Exception::Exception(const std::string & msg, const int32_t code) : Exception(msg + " (" + ZooKeeperImpl::ZooKeeper::errorMessage(code) + ")", code, 0) { } Exception::Exception(const int32_t code) : Exception(ZooKeeperImpl::ZooKeeper::errorMessage(code), code, 0) { } Exception::Exception(const int32_t code, const std::string & path) : Exception(std::string{ZooKeeperImpl::ZooKeeper::errorMessage(code)} + ", path: " + path, code, 0) { } Exception::Exception(const Exception & exc) : DB::Exception(exc), code(exc.code) { } using namespace DB; /// Assuming we are at little endian. void write(int64_t x, WriteBuffer & out) { x = __builtin_bswap64(x); writeBinary(x, out); } void write(int32_t x, WriteBuffer & out) { x = __builtin_bswap32(x); writeBinary(x, out); } void write(bool x, WriteBuffer & out) { writeBinary(x, out); } void write(const String & s, WriteBuffer & out) { write(int32_t(s.size()), out); out.write(s.data(), s.size()); } template <size_t N> void write(std::array<char, N> s, WriteBuffer & out) { write(int32_t(N), out); out.write(s.data(), N); } template <typename T> void write(const std::vector<T> & arr, WriteBuffer & out) { write(int32_t(arr.size()), out); for (const auto & elem : arr) write(elem, out); } void write(const ZooKeeper::ACL & acl, WriteBuffer & out) { acl.write(out); } void ZooKeeper::ACL::write(WriteBuffer & out) const { ZooKeeperImpl::write(permissions, out); ZooKeeperImpl::write(scheme, out); ZooKeeperImpl::write(id, out); } void read(int64_t & x, ReadBuffer & in) { readBinary(x, in); x = __builtin_bswap64(x); } void read(int32_t & x, ReadBuffer & in) { readBinary(x, in); x = __builtin_bswap32(x); } void read(bool & x, ReadBuffer & in) { readBinary(x, in); } void read(String & s, ReadBuffer & in) { static constexpr int32_t max_string_size = 1 << 20; int32_t size = 0; read(size, in); if (size < 0) /// TODO Actually it means that zookeeper node has NULL value. Maybe better to treat it like empty string. throw Exception("Negative size while reading string from ZooKeeper", ZooKeeper::ZMARSHALLINGERROR); if (size > max_string_size) throw Exception("Too large string size while reading from ZooKeeper", ZooKeeper::ZMARSHALLINGERROR); s.resize(size); in.read(&s[0], size); } template <size_t N> void read(std::array<char, N> & s, ReadBuffer & in) { int32_t size = 0; read(size, in); if (size != N) throw Exception("Unexpected array size while reading from ZooKeeper", ZooKeeper::ZMARSHALLINGERROR); in.read(&s[0], N); } void read(ZooKeeper::Stat & stat, ReadBuffer & in) { stat.read(in); } void ZooKeeper::Stat::read(ReadBuffer & in) { ZooKeeperImpl::read(czxid, in); ZooKeeperImpl::read(mzxid, in); ZooKeeperImpl::read(ctime, in); ZooKeeperImpl::read(mtime, in); ZooKeeperImpl::read(version, in); ZooKeeperImpl::read(cversion, in); ZooKeeperImpl::read(aversion, in); ZooKeeperImpl::read(ephemeralOwner, in); ZooKeeperImpl::read(dataLength, in); ZooKeeperImpl::read(numChildren, in); ZooKeeperImpl::read(pzxid, in); } template <typename T> void read(std::vector<T> & arr, ReadBuffer & in) { static constexpr int32_t max_array_size = 1 << 20; int32_t size = 0; read(size, in); if (size < 0) throw Exception("Negative size while reading array from ZooKeeper", ZooKeeper::ZMARSHALLINGERROR); if (size > max_array_size) throw Exception("Too large array size while reading from ZooKeeper", ZooKeeper::ZMARSHALLINGERROR); arr.resize(size); for (auto & elem : arr) read(elem, in); } template <typename T> void ZooKeeper::write(const T & x) { ZooKeeperImpl::write(x, *out); } template <typename T> void ZooKeeper::read(T & x) { ZooKeeperImpl::read(x, *in); } void addRootPath(String & path, const String & root_path) { if (path.empty()) throw Exception("Path cannot be empty", ZooKeeper::ZBADARGUMENTS); if (path[0] != '/') throw Exception("Path must begin with /", ZooKeeper::ZBADARGUMENTS); if (root_path.empty()) return; if (path.size() == 1) /// "/" path = root_path; else path = root_path + path; } void removeRootPath(String & path, const String & root_path) { if (root_path.empty()) return; if (path.size() <= root_path.size()) throw Exception("Received path is not longer than root_path", ZooKeeper::ZDATAINCONSISTENCY); path = path.substr(root_path.size()); } static constexpr int32_t protocol_version = 0; static constexpr ZooKeeper::XID watch_xid = -1; static constexpr ZooKeeper::XID ping_xid = -2; static constexpr ZooKeeper::XID auth_xid = -4; static constexpr ZooKeeper::XID close_xid = 0x7FFFFFFF; const char * ZooKeeper::errorMessage(int32_t code) { switch (code) { case ZOK: return "Ok"; case ZSYSTEMERROR: return "System error"; case ZRUNTIMEINCONSISTENCY: return "Run time inconsistency"; case ZDATAINCONSISTENCY: return "Data inconsistency"; case ZCONNECTIONLOSS: return "Connection loss"; case ZMARSHALLINGERROR: return "Marshalling error"; case ZUNIMPLEMENTED: return "Unimplemented"; case ZOPERATIONTIMEOUT: return "Operation timeout"; case ZBADARGUMENTS: return "Bad arguments"; case ZINVALIDSTATE: return "Invalid zhandle state"; case ZAPIERROR: return "API error"; case ZNONODE: return "No node"; case ZNOAUTH: return "Not authenticated"; case ZBADVERSION: return "Bad version"; case ZNOCHILDRENFOREPHEMERALS: return "No children for ephemerals"; case ZNODEEXISTS: return "Node exists"; case ZNOTEMPTY: return "Not empty"; case ZSESSIONEXPIRED: return "Session expired"; case ZINVALIDCALLBACK: return "Invalid callback"; case ZINVALIDACL: return "Invalid ACL"; case ZAUTHFAILED: return "Authentication failed"; case ZCLOSING: return "ZooKeeper is closing"; case ZNOTHING: return "(not error) no server responses to process"; case ZSESSIONMOVED: return "Session moved to another server, so operation is ignored"; } if (code > 0) return strerror(code); return "unknown error"; } ZooKeeper::~ZooKeeper() { try { finalize(false, false); if (send_thread.joinable()) send_thread.join(); if (receive_thread.joinable()) receive_thread.join(); } catch (...) { tryLogCurrentException(__PRETTY_FUNCTION__); } } ZooKeeper::ZooKeeper( const Addresses & addresses, const String & root_path_, const String & auth_scheme, const String & auth_data, Poco::Timespan session_timeout, Poco::Timespan connection_timeout, Poco::Timespan operation_timeout) : root_path(root_path_), session_timeout(session_timeout), operation_timeout(std::min(operation_timeout, session_timeout)) { if (!root_path.empty()) { if (root_path.back() == '/') root_path.pop_back(); } if (auth_scheme.empty()) { ACL acl; acl.permissions = ACL::All; acl.scheme = "world"; acl.id = "anyone"; default_acls.emplace_back(std::move(acl)); } else { ACL acl; acl.permissions = ACL::All; acl.scheme = "auth"; acl.id = ""; default_acls.emplace_back(std::move(acl)); } connect(addresses, connection_timeout); if (!auth_scheme.empty()) sendAuth(auth_scheme, auth_data); send_thread = std::thread([this] { sendThread(); }); receive_thread = std::thread([this] { receiveThread(); }); ProfileEvents::increment(ProfileEvents::ZooKeeperInit); } void ZooKeeper::connect( const Addresses & addresses, Poco::Timespan connection_timeout) { if (addresses.empty()) throw Exception("No addresses passed to ZooKeeperImpl constructor", ZBADARGUMENTS); static constexpr size_t num_tries = 3; bool connected = false; WriteBufferFromOwnString fail_reasons; for (size_t try_no = 0; try_no < num_tries; ++try_no) { for (const auto & address : addresses) { try { socket = Poco::Net::StreamSocket(); /// Reset the state of previous attempt. socket.connect(address, connection_timeout); socket.setReceiveTimeout(operation_timeout); socket.setSendTimeout(operation_timeout); socket.setNoDelay(true); in.emplace(socket); out.emplace(socket); sendHandshake(); receiveHandshake(); connected = true; break; } catch (const Poco::Net::NetException & e) { fail_reasons << "\n" << getCurrentExceptionMessage(false) << ", " << address.toString(); } catch (const Poco::TimeoutException & e) { fail_reasons << "\n" << getCurrentExceptionMessage(false); } } if (connected) break; } if (!connected) { WriteBufferFromOwnString out; out << "All connection tries failed while connecting to ZooKeeper. Addresses: "; bool first = true; for (const auto & address : addresses) { if (first) first = false; else out << ", "; out << address.toString(); } out << fail_reasons.str() << "\n"; throw Exception(out.str(), ZCONNECTIONLOSS); } } void ZooKeeper::sendHandshake() { int32_t handshake_length = 44; int64_t last_zxid_seen = 0; int32_t timeout = session_timeout.totalMilliseconds(); int64_t session_id = 0; constexpr int32_t passwd_len = 16; std::array<char, passwd_len> passwd {}; write(handshake_length); write(protocol_version); write(last_zxid_seen); write(timeout); write(session_id); write(passwd); out->next(); } void ZooKeeper::receiveHandshake() { int32_t handshake_length; int32_t protocol_version_read; int32_t timeout; constexpr int32_t passwd_len = 16; std::array<char, passwd_len> passwd; read(handshake_length); if (handshake_length != 36) throw Exception("Unexpected handshake length received: " + toString(handshake_length), ZMARSHALLINGERROR); read(protocol_version_read); if (protocol_version_read != protocol_version) throw Exception("Unexpected protocol version: " + toString(protocol_version_read), ZMARSHALLINGERROR); read(timeout); if (timeout != session_timeout.totalMilliseconds()) throw Exception("Received different session timeout from server: " + toString(timeout), ZMARSHALLINGERROR); read(session_id); read(passwd); } void ZooKeeper::sendAuth(const String & scheme, const String & data) { AuthRequest request; request.scheme = scheme; request.data = data; request.xid = auth_xid; request.write(*out); int32_t length; XID xid; int64_t zxid; int32_t err; read(length); size_t count_before_event = in->count(); read(xid); read(zxid); read(err); if (xid != auth_xid) throw Exception("Unexpected event recieved in reply to auth request: " + toString(xid), ZMARSHALLINGERROR); int32_t actual_length = in->count() - count_before_event; if (length != actual_length) throw Exception("Response length doesn't match. Expected: " + toString(length) + ", actual: " + toString(actual_length), ZMARSHALLINGERROR); if (err) throw Exception("Error received in reply to auth request. Code: " + toString(err) + ". Message: " + String(errorMessage(err)), ZMARSHALLINGERROR); } void ZooKeeper::sendThread() { setThreadName("ZooKeeperSend"); auto prev_heartbeat_time = clock::now(); try { while (!expired) { auto prev_bytes_sent = out->count(); auto now = clock::now(); auto next_heartbeat_time = prev_heartbeat_time + std::chrono::milliseconds(session_timeout.totalMilliseconds() / 3); if (next_heartbeat_time > now) { /// Wait for the next request in queue. No more than operation timeout. No more than until next heartbeat time. UInt64 max_wait = std::min( std::chrono::duration_cast<std::chrono::milliseconds>(next_heartbeat_time - now).count(), operation_timeout.totalMilliseconds()); RequestInfo info; if (requests_queue.tryPop(info, max_wait)) { /// After we popped element from the queue, we must register callbacks (even in the case when expired == true right now), /// because they must not be lost (callbacks must be called because the user will wait for them). if (info.request->xid != close_xid) { CurrentMetrics::add(CurrentMetrics::ZooKeeperRequest); std::lock_guard lock(operations_mutex); operations[info.request->xid] = info; } if (info.watch) { info.request->has_watch = true; CurrentMetrics::add(CurrentMetrics::ZooKeeperWatch); std::lock_guard lock(watches_mutex); watches[info.request->getPath()].emplace_back(std::move(info.watch)); } if (expired) break; info.request->addRootPath(root_path); info.request->write(*out); if (info.request->xid == close_xid) break; } } else { /// Send heartbeat. prev_heartbeat_time = clock::now(); HeartbeatRequest request; request.xid = ping_xid; request.write(*out); } ProfileEvents::increment(ProfileEvents::ZooKeeperBytesSent, out->count() - prev_bytes_sent); } } catch (...) { tryLogCurrentException(__PRETTY_FUNCTION__); finalize(true, false); } } void ZooKeeper::receiveThread() { setThreadName("ZooKeeperRecv"); try { Int64 waited = 0; while (!expired) { auto prev_bytes_received = in->count(); clock::time_point now = clock::now(); UInt64 max_wait = operation_timeout.totalMicroseconds(); std::optional<RequestInfo> earliest_operation; { std::lock_guard lock(operations_mutex); if (!operations.empty()) { /// Operations are ordered by xid (and consequently, by time). earliest_operation = operations.begin()->second; auto earliest_operation_deadline = earliest_operation->time + std::chrono::microseconds(operation_timeout.totalMicroseconds()); if (now > earliest_operation_deadline) throw Exception("Operation timeout (deadline already expired) for path: " + earliest_operation->request->getPath(), ZOPERATIONTIMEOUT); max_wait = std::chrono::duration_cast<std::chrono::microseconds>(earliest_operation_deadline - now).count(); } } if (in->poll(max_wait)) { if (expired) break; receiveEvent(); waited = 0; } else { if (earliest_operation) throw Exception("Operation timeout (no response) for path: " + earliest_operation->request->getPath(), ZOPERATIONTIMEOUT); waited += max_wait; if (waited > session_timeout.totalMicroseconds()) throw Exception("Nothing is received in session timeout", ZOPERATIONTIMEOUT); } ProfileEvents::increment(ProfileEvents::ZooKeeperBytesReceived, in->count() - prev_bytes_received); } } catch (...) { tryLogCurrentException(__PRETTY_FUNCTION__); finalize(false, true); } } void ZooKeeper::Request::write(WriteBuffer & out) const { /// Excessive copy to calculate length. WriteBufferFromOwnString buf; ZooKeeperImpl::write(xid, buf); ZooKeeperImpl::write(getOpNum(), buf); writeImpl(buf); ZooKeeperImpl::write(buf.str(), out); out.next(); } ZooKeeper::ResponsePtr ZooKeeper::HeartbeatRequest::makeResponse() const { return std::make_shared<HeartbeatResponse>(); } ZooKeeper::ResponsePtr ZooKeeper::AuthRequest::makeResponse() const { return std::make_shared<AuthResponse>(); } ZooKeeper::ResponsePtr ZooKeeper::CreateRequest::makeResponse() const { return std::make_shared<CreateResponse>(); } ZooKeeper::ResponsePtr ZooKeeper::RemoveRequest::makeResponse() const { return std::make_shared<RemoveResponse>(); } ZooKeeper::ResponsePtr ZooKeeper::ExistsRequest::makeResponse() const { return std::make_shared<ExistsResponse>(); } ZooKeeper::ResponsePtr ZooKeeper::GetRequest::makeResponse() const { return std::make_shared<GetResponse>(); } ZooKeeper::ResponsePtr ZooKeeper::SetRequest::makeResponse() const { return std::make_shared<SetResponse>(); } ZooKeeper::ResponsePtr ZooKeeper::ListRequest::makeResponse() const { return std::make_shared<ListResponse>(); } ZooKeeper::ResponsePtr ZooKeeper::CheckRequest::makeResponse() const { return std::make_shared<CheckResponse>(); } ZooKeeper::ResponsePtr ZooKeeper::MultiRequest::makeResponse() const { return std::make_shared<MultiResponse>(requests); } ZooKeeper::ResponsePtr ZooKeeper::CloseRequest::makeResponse() const { return std::make_shared<CloseResponse>(); } void ZooKeeper::CreateRequest::addRootPath(const String & root_path) { ZooKeeperImpl::addRootPath(path, root_path); } void ZooKeeper::RemoveRequest::addRootPath(const String & root_path) { ZooKeeperImpl::addRootPath(path, root_path); } void ZooKeeper::ExistsRequest::addRootPath(const String & root_path) { ZooKeeperImpl::addRootPath(path, root_path); } void ZooKeeper::GetRequest::addRootPath(const String & root_path) { ZooKeeperImpl::addRootPath(path, root_path); } void ZooKeeper::SetRequest::addRootPath(const String & root_path) { ZooKeeperImpl::addRootPath(path, root_path); } void ZooKeeper::ListRequest::addRootPath(const String & root_path) { ZooKeeperImpl::addRootPath(path, root_path); } void ZooKeeper::CheckRequest::addRootPath(const String & root_path) { ZooKeeperImpl::addRootPath(path, root_path); } void ZooKeeper::MultiRequest::addRootPath(const String & root_path) { for (auto & request : requests) request->addRootPath(root_path); } void ZooKeeper::CreateResponse::removeRootPath(const String & root_path) { ZooKeeperImpl::removeRootPath(path_created, root_path); } void ZooKeeper::WatchResponse::removeRootPath(const String & root_path) { ZooKeeperImpl::removeRootPath(path, root_path); } void ZooKeeper::MultiResponse::removeRootPath(const String & root_path) { for (auto & response : responses) response->removeRootPath(root_path); } void ZooKeeper::receiveEvent() { int32_t length; XID xid; int64_t zxid; int32_t err; read(length); size_t count_before_event = in->count(); read(xid); read(zxid); read(err); RequestInfo request_info; ResponsePtr response; if (xid == ping_xid) { if (err) throw Exception("Received error in heartbeat response: " + String(errorMessage(err)), ZRUNTIMEINCONSISTENCY); response = std::make_shared<HeartbeatResponse>(); } else if (xid == watch_xid) { ProfileEvents::increment(ProfileEvents::ZooKeeperWatchResponse); response = std::make_shared<WatchResponse>(); request_info.callback = [this](const Response & response) { const WatchResponse & watch_response = static_cast<const WatchResponse &>(response); std::lock_guard lock(watches_mutex); auto it = watches.find(watch_response.path); if (it == watches.end()) { /// This is Ok. /// Because watches are identified by path. /// And there may exist many watches for single path. /// And watch is added to the list of watches on client side /// slightly before than it is registered by the server. /// And that's why new watch may be already fired by old event, /// but then the server will actually register new watch /// and will send event again later. } else { for (auto & callback : it->second) if (callback) callback(watch_response); /// NOTE We may process callbacks not under mutex. CurrentMetrics::sub(CurrentMetrics::ZooKeeperWatch, it->second.size()); watches.erase(it); } }; } else { { std::lock_guard lock(operations_mutex); auto it = operations.find(xid); if (it == operations.end()) throw Exception("Received response for unknown xid", ZRUNTIMEINCONSISTENCY); request_info = std::move(it->second); operations.erase(it); CurrentMetrics::sub(CurrentMetrics::ZooKeeperRequest); } response = request_info.request->makeResponse(); auto elapsed_microseconds = std::chrono::duration_cast<std::chrono::microseconds>(clock::now() - request_info.time).count(); ProfileEvents::increment(ProfileEvents::ZooKeeperWaitMicroseconds, elapsed_microseconds); } if (err) response->error = err; else { response->readImpl(*in); response->removeRootPath(root_path); } int32_t actual_length = in->count() - count_before_event; if (length != actual_length) throw Exception("Response length doesn't match. Expected: " + toString(length) + ", actual: " + toString(actual_length), ZMARSHALLINGERROR); /// NOTE: Exception in callback will propagate to receiveThread and will lead to session expiration. This is Ok. if (request_info.callback) request_info.callback(*response); } void ZooKeeper::finalize(bool error_send, bool error_receive) { { std::lock_guard lock(push_request_mutex); if (expired) return; expired = true; } active_session_metric_increment.destroy(); try { if (!error_send) { /// Send close event. This also signals sending thread to wakeup and then stop. try { close(); } catch (...) { /// This happens for example, when "Cannot push request to queue within operation timeout". tryLogCurrentException(__PRETTY_FUNCTION__); } send_thread.join(); } try { /// This will also wakeup the receiving thread. socket.shutdown(); } catch (...) { /// We must continue to execute all callbacks, because the user is waiting for them. tryLogCurrentException(__PRETTY_FUNCTION__); } if (!error_receive) receive_thread.join(); { std::lock_guard lock(operations_mutex); for (auto & op : operations) { RequestInfo & request_info = op.second; ResponsePtr response = request_info.request->makeResponse(); response->error = ZSESSIONEXPIRED; if (request_info.callback) { try { request_info.callback(*response); } catch (...) { /// We must continue to all other callbacks, because the user is waiting for them. tryLogCurrentException(__PRETTY_FUNCTION__); } } } CurrentMetrics::sub(CurrentMetrics::ZooKeeperRequest, operations.size()); operations.clear(); } { std::lock_guard lock(watches_mutex); for (auto & path_watches : watches) { WatchResponse response; response.type = SESSION; response.state = EXPIRED_SESSION; response.error = ZSESSIONEXPIRED; for (auto & callback : path_watches.second) { if (callback) { try { callback(response); } catch (...) { tryLogCurrentException(__PRETTY_FUNCTION__); } } } } CurrentMetrics::sub(CurrentMetrics::ZooKeeperWatch, watches.size()); watches.clear(); } /// Drain queue RequestInfo info; while (requests_queue.tryPop(info)) { if (info.callback) { ResponsePtr response = info.request->makeResponse(); response->error = ZSESSIONEXPIRED; try { info.callback(*response); } catch (...) { tryLogCurrentException(__PRETTY_FUNCTION__); } } if (info.watch) { WatchResponse response; response.type = SESSION; response.state = EXPIRED_SESSION; response.error = ZSESSIONEXPIRED; try { info.watch(response); } catch (...) { tryLogCurrentException(__PRETTY_FUNCTION__); } } } } catch (...) { tryLogCurrentException(__PRETTY_FUNCTION__); } } void ZooKeeper::AuthRequest::writeImpl(WriteBuffer & out) const { ZooKeeperImpl::write(type, out); ZooKeeperImpl::write(scheme, out); ZooKeeperImpl::write(data, out); } void ZooKeeper::CreateRequest::writeImpl(WriteBuffer & out) const { ZooKeeperImpl::write(path, out); ZooKeeperImpl::write(data, out); ZooKeeperImpl::write(acls, out); int32_t flags = 0; if (is_ephemeral) flags |= 1; if (is_sequential) flags |= 2; ZooKeeperImpl::write(flags, out); } void ZooKeeper::RemoveRequest::writeImpl(WriteBuffer & out) const { ZooKeeperImpl::write(path, out); ZooKeeperImpl::write(version, out); } void ZooKeeper::ExistsRequest::writeImpl(WriteBuffer & out) const { ZooKeeperImpl::write(path, out); ZooKeeperImpl::write(has_watch, out); } void ZooKeeper::GetRequest::writeImpl(WriteBuffer & out) const { ZooKeeperImpl::write(path, out); ZooKeeperImpl::write(has_watch, out); } void ZooKeeper::SetRequest::writeImpl(WriteBuffer & out) const { ZooKeeperImpl::write(path, out); ZooKeeperImpl::write(data, out); ZooKeeperImpl::write(version, out); } void ZooKeeper::ListRequest::writeImpl(WriteBuffer & out) const { ZooKeeperImpl::write(path, out); ZooKeeperImpl::write(has_watch, out); } void ZooKeeper::CheckRequest::writeImpl(WriteBuffer & out) const { ZooKeeperImpl::write(path, out); ZooKeeperImpl::write(version, out); } void ZooKeeper::MultiRequest::writeImpl(WriteBuffer & out) const { for (const auto & request : requests) { bool done = false; int32_t error = -1; ZooKeeperImpl::write(request->getOpNum(), out); ZooKeeperImpl::write(done, out); ZooKeeperImpl::write(error, out); request->writeImpl(out); } OpNum op_num = -1; bool done = true; int32_t error = -1; ZooKeeperImpl::write(op_num, out); ZooKeeperImpl::write(done, out); ZooKeeperImpl::write(error, out); } void ZooKeeper::WatchResponse::readImpl(ReadBuffer & in) { ZooKeeperImpl::read(type, in); ZooKeeperImpl::read(state, in); ZooKeeperImpl::read(path, in); } void ZooKeeper::CreateResponse::readImpl(ReadBuffer & in) { ZooKeeperImpl::read(path_created, in); } void ZooKeeper::ExistsResponse::readImpl(ReadBuffer & in) { ZooKeeperImpl::read(stat, in); } void ZooKeeper::GetResponse::readImpl(ReadBuffer & in) { ZooKeeperImpl::read(data, in); ZooKeeperImpl::read(stat, in); } void ZooKeeper::SetResponse::readImpl(ReadBuffer & in) { ZooKeeperImpl::read(stat, in); } void ZooKeeper::ListResponse::readImpl(ReadBuffer & in) { ZooKeeperImpl::read(names, in); ZooKeeperImpl::read(stat, in); } void ZooKeeper::ErrorResponse::readImpl(ReadBuffer & in) { int32_t read_error; ZooKeeperImpl::read(read_error, in); if (read_error != error) throw Exception("Error code in ErrorResponse (" + toString(read_error) + ") doesn't match error code in header (" + toString(error) + ")", ZMARSHALLINGERROR); } void ZooKeeper::CloseResponse::readImpl(ReadBuffer &) { throw Exception("Received response for close request", ZRUNTIMEINCONSISTENCY); } ZooKeeper::MultiResponse::MultiResponse(const Requests & requests) { responses.reserve(requests.size()); for (const auto & request : requests) responses.emplace_back(request->makeResponse()); } void ZooKeeper::MultiResponse::readImpl(ReadBuffer & in) { for (auto & response : responses) { OpNum op_num; bool done; int32_t op_error; ZooKeeperImpl::read(op_num, in); ZooKeeperImpl::read(done, in); ZooKeeperImpl::read(op_error, in); if (done) throw Exception("Not enough results received for multi transaction", ZMARSHALLINGERROR); /// op_num == -1 is special for multi transaction. /// For unknown reason, error code is duplicated in header and in response body. if (op_num == -1) response = std::make_shared<ErrorResponse>(); if (op_error) { response->error = op_error; /// Set error for whole transaction. /// If some operations fail, ZK send global error as zero and then send details about each operation. /// It will set error code for first failed operation and it will set special "runtime inconsistency" code for other operations. if (!error && op_error != ZRUNTIMEINCONSISTENCY) error = op_error; } if (!op_error || op_num == -1) response->readImpl(in); } /// Footer. { OpNum op_num; bool done; int32_t error; ZooKeeperImpl::read(op_num, in); ZooKeeperImpl::read(done, in); ZooKeeperImpl::read(error, in); if (!done) throw Exception("Too many results received for multi transaction", ZMARSHALLINGERROR); if (op_num != -1) throw Exception("Unexpected op_num received at the end of results for multi transaction", ZMARSHALLINGERROR); if (error != -1) throw Exception("Unexpected error value received at the end of results for multi transaction", ZMARSHALLINGERROR); } } void ZooKeeper::pushRequest(RequestInfo && info) { try { info.time = clock::now(); if (!info.request->xid) { info.request->xid = xid.fetch_add(1); if (info.request->xid < 0) throw Exception("XID overflow", ZSESSIONEXPIRED); } /// We must serialize 'pushRequest' and 'finalize' (from sendThread, receiveThread) calls /// to avoid forgotten operations in the queue when session is expired. /// Invariant: when expired, no new operations will be pushed to the queue in 'pushRequest' /// and the queue will be drained in 'finalize'. std::lock_guard lock(push_request_mutex); if (expired) throw Exception("Session expired", ZSESSIONEXPIRED); if (!requests_queue.tryPush(std::move(info), operation_timeout.totalMilliseconds())) throw Exception("Cannot push request to queue within operation timeout", ZOPERATIONTIMEOUT); } catch (...) { finalize(false, false); throw; } ProfileEvents::increment(ProfileEvents::ZooKeeperTransactions); } void ZooKeeper::create( const String & path, const String & data, bool is_ephemeral, bool is_sequential, const ACLs & acls, CreateCallback callback) { CreateRequest request; request.path = path; request.data = data; request.is_ephemeral = is_ephemeral; request.is_sequential = is_sequential; request.acls = acls.empty() ? default_acls : acls; RequestInfo request_info; request_info.request = std::make_shared<CreateRequest>(std::move(request)); request_info.callback = [callback](const Response & response) { callback(typeid_cast<const CreateResponse &>(response)); }; pushRequest(std::move(request_info)); ProfileEvents::increment(ProfileEvents::ZooKeeperCreate); } void ZooKeeper::remove( const String & path, int32_t version, RemoveCallback callback) { RemoveRequest request; request.path = path; request.version = version; RequestInfo request_info; request_info.request = std::make_shared<RemoveRequest>(std::move(request)); request_info.callback = [callback](const Response & response) { callback(typeid_cast<const RemoveResponse &>(response)); }; pushRequest(std::move(request_info)); ProfileEvents::increment(ProfileEvents::ZooKeeperRemove); } void ZooKeeper::exists( const String & path, ExistsCallback callback, WatchCallback watch) { ExistsRequest request; request.path = path; RequestInfo request_info; request_info.request = std::make_shared<ExistsRequest>(std::move(request)); request_info.callback = [callback](const Response & response) { callback(typeid_cast<const ExistsResponse &>(response)); }; request_info.watch = watch; pushRequest(std::move(request_info)); ProfileEvents::increment(ProfileEvents::ZooKeeperExists); } void ZooKeeper::get( const String & path, GetCallback callback, WatchCallback watch) { GetRequest request; request.path = path; RequestInfo request_info; request_info.request = std::make_shared<GetRequest>(std::move(request)); request_info.callback = [callback](const Response & response) { callback(typeid_cast<const GetResponse &>(response)); }; request_info.watch = watch; pushRequest(std::move(request_info)); ProfileEvents::increment(ProfileEvents::ZooKeeperGet); } void ZooKeeper::set( const String & path, const String & data, int32_t version, SetCallback callback) { SetRequest request; request.path = path; request.data = data; request.version = version; RequestInfo request_info; request_info.request = std::make_shared<SetRequest>(std::move(request)); request_info.callback = [callback](const Response & response) { callback(typeid_cast<const SetResponse &>(response)); }; pushRequest(std::move(request_info)); ProfileEvents::increment(ProfileEvents::ZooKeeperSet); } void ZooKeeper::list( const String & path, ListCallback callback, WatchCallback watch) { ListRequest request; request.path = path; RequestInfo request_info; request_info.request = std::make_shared<ListRequest>(std::move(request)); request_info.callback = [callback](const Response & response) { callback(typeid_cast<const ListResponse &>(response)); }; request_info.watch = watch; pushRequest(std::move(request_info)); ProfileEvents::increment(ProfileEvents::ZooKeeperList); } void ZooKeeper::check( const String & path, int32_t version, CheckCallback callback) { CheckRequest request; request.path = path; request.version = version; RequestInfo request_info; request_info.request = std::make_shared<CheckRequest>(std::move(request)); request_info.callback = [callback](const Response & response) { callback(typeid_cast<const CheckResponse &>(response)); }; pushRequest(std::move(request_info)); ProfileEvents::increment(ProfileEvents::ZooKeeperCheck); } void ZooKeeper::multi( const Requests & requests, MultiCallback callback) { MultiRequest request; request.requests = requests; for (auto & elem : request.requests) if (CreateRequest * create = typeid_cast<CreateRequest *>(elem.get())) if (create->acls.empty()) create->acls = default_acls; RequestInfo request_info; request_info.request = std::make_shared<MultiRequest>(std::move(request)); request_info.callback = [callback](const Response & response) { callback(typeid_cast<const MultiResponse &>(response)); }; pushRequest(std::move(request_info)); ProfileEvents::increment(ProfileEvents::ZooKeeperMulti); } void ZooKeeper::close() { CloseRequest request; request.xid = close_xid; RequestInfo request_info; request_info.request = std::make_shared<CloseRequest>(std::move(request)); if (!requests_queue.tryPush(std::move(request_info), operation_timeout.totalMilliseconds())) throw Exception("Cannot push close request to queue within operation timeout", ZOPERATIONTIMEOUT); ProfileEvents::increment(ProfileEvents::ZooKeeperClose); } }
afe491599ed74f494307fffa02ac2999ca5659ba
fd69253efd87de9760cbf572d0e927bbce834421
/src/walletdb.cpp
6902fa470d8399c154b5d6f2626c0b689a4c0858
[ "MIT" ]
permissive
apcplatform/apcc
4c4f331837180184a5d080876c90a9022cd3af81
bcbd94748156b74904eac879c153cd113c101959
refs/heads/master
2021-05-14T23:07:24.932442
2017-10-01T05:33:13
2017-10-01T05:33:13
98,450,305
0
0
null
null
null
null
UTF-8
C++
false
false
32,341
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 "walletdb.h" #include "wallet.h" #include "base58.h" #include <iostream> #include <fstream> #include <boost/version.hpp> #include <boost/filesystem.hpp> #include <boost/algorithm/string.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/lexical_cast.hpp> #include <boost/variant/get.hpp> #include <boost/algorithm/string.hpp> using namespace std; using namespace boost; static uint64_t nAccountingEntryNumber = 0; extern bool fWalletUnlockMintOnly; // // CWalletDB // bool CWalletDB::WriteName(const string& strAddress, const string& strName) { nWalletDBUpdated++; return Write(make_pair(string("name"), strAddress), strName); } bool CWalletDB::EraseName(const string& strAddress) { // This should only be used for sending addresses, never for receiving addresses, // receiving addresses must always have an address book entry if they're not change return. nWalletDBUpdated++; return Erase(make_pair(string("name"), strAddress)); } bool CWalletDB::ReadAccount(const string& strAccount, CAccount& account) { account.SetNull(); return Read(make_pair(string("acc"), strAccount), account); } bool CWalletDB::WriteAccount(const string& strAccount, const CAccount& account) { return Write(make_pair(string("acc"), strAccount), account); } bool CWalletDB::WriteAccountingEntry(const uint64_t nAccEntryNum, const CAccountingEntry& acentry) { return Write(boost::make_tuple(string("acentry"), acentry.strAccount, nAccEntryNum), acentry); } bool CWalletDB::WriteAccountingEntry(const CAccountingEntry& acentry) { return WriteAccountingEntry(++nAccountingEntryNumber, acentry); } int64_t CWalletDB::GetAccountCreditDebit(const string& strAccount) { list<CAccountingEntry> entries; ListAccountCreditDebit(strAccount, entries); int64_t nCreditDebit = 0; BOOST_FOREACH (const CAccountingEntry& entry, entries) nCreditDebit += entry.nCreditDebit; return nCreditDebit; } void CWalletDB::ListAccountCreditDebit(const string& strAccount, list<CAccountingEntry>& entries) { bool fAllAccounts = (strAccount == "*"); Dbc* pcursor = GetCursor(); if (!pcursor) throw runtime_error("CWalletDB::ListAccountCreditDebit() : cannot create DB cursor"); unsigned int fFlags = DB_SET_RANGE; while (true) { // Read next record CDataStream ssKey(SER_DISK, CLIENT_VERSION); if (fFlags == DB_SET_RANGE) ssKey << boost::make_tuple(string("acentry"), (fAllAccounts? string("") : strAccount), uint64_t(0)); CDataStream ssValue(SER_DISK, CLIENT_VERSION); int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags); fFlags = DB_NEXT; if (ret == DB_NOTFOUND) break; else if (ret != 0) { pcursor->close(); throw runtime_error("CWalletDB::ListAccountCreditDebit() : error scanning DB"); } // Unserialize string strType; ssKey >> strType; if (strType != "acentry") break; CAccountingEntry acentry; ssKey >> acentry.strAccount; if (!fAllAccounts && acentry.strAccount != strAccount) break; ssValue >> acentry; ssKey >> acentry.nEntryNo; entries.push_back(acentry); } pcursor->close(); } DBErrors CWalletDB::ReorderTransactions(CWallet* pwallet) { LOCK(pwallet->cs_wallet); // Old wallets didn't have any defined order for transactions // Probably a bad idea to change the output of this // First: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap. typedef pair<CWalletTx*, CAccountingEntry*> TxPair; typedef multimap<int64_t, TxPair > TxItems; TxItems txByTime; for (map<uint256, CWalletTx>::iterator it = pwallet->mapWallet.begin(); it != pwallet->mapWallet.end(); ++it) { CWalletTx* wtx = &((*it).second); txByTime.insert(make_pair(wtx->nTimeReceived, TxPair(wtx, (CAccountingEntry*)0))); } list<CAccountingEntry> acentries; ListAccountCreditDebit("", acentries); BOOST_FOREACH(CAccountingEntry& entry, acentries) { txByTime.insert(make_pair(entry.nTime, TxPair((CWalletTx*)0, &entry))); } int64_t& nOrderPosNext = pwallet->nOrderPosNext; nOrderPosNext = 0; std::vector<int64_t> nOrderPosOffsets; for (TxItems::iterator it = txByTime.begin(); it != txByTime.end(); ++it) { CWalletTx *const pwtx = (*it).second.first; CAccountingEntry *const pacentry = (*it).second.second; int64_t& nOrderPos = (pwtx != 0) ? pwtx->nOrderPos : pacentry->nOrderPos; if (nOrderPos == -1) { nOrderPos = nOrderPosNext++; nOrderPosOffsets.push_back(nOrderPos); if (pacentry) // Have to write accounting regardless, since we don't keep it in memory if (!WriteAccountingEntry(pacentry->nEntryNo, *pacentry)) return DB_LOAD_FAIL; } else { int64_t nOrderPosOff = 0; BOOST_FOREACH(const int64_t& nOffsetStart, nOrderPosOffsets) { if (nOrderPos >= nOffsetStart) ++nOrderPosOff; } nOrderPos += nOrderPosOff; nOrderPosNext = std::max(nOrderPosNext, nOrderPos + 1); if (!nOrderPosOff) continue; // Since we're changing the order, write it back if (pwtx) { if (!WriteTx(pwtx->GetHash(), *pwtx)) return DB_LOAD_FAIL; } else if (!WriteAccountingEntry(pacentry->nEntryNo, *pacentry)) return DB_LOAD_FAIL; } } return DB_LOAD_OK; } class CWalletScanState { public: unsigned int nKeys; unsigned int nCKeys; unsigned int nKeyMeta; bool fIsEncrypted; bool fAnyUnordered; int nFileVersion; vector<uint256> vWalletUpgrade; CWalletScanState() { nKeys = nCKeys = nKeyMeta = 0; fIsEncrypted = false; fAnyUnordered = false; nFileVersion = 0; } }; bool ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue, CWalletScanState &wss, string& strType, string& strErr) { try { // Unserialize // Taking advantage of the fact that pair serialization // is just the two items serialized one after the other ssKey >> strType; if (strType == "name") { string strAddress; ssKey >> strAddress; ssValue >> pwallet->mapAddressBook[CBitcoinAddress(strAddress).Get()]; } else if (strType == "tx") { uint256 hash; ssKey >> hash; CWalletTx& wtx = pwallet->mapWallet[hash]; ssValue >> wtx; if (wtx.CheckTransaction() && (wtx.GetHash() == hash)) wtx.BindWallet(pwallet); else { pwallet->mapWallet.erase(hash); return false; } // Undo serialize changes in 31600 if (31404 <= wtx.fTimeReceivedIsTxTime && wtx.fTimeReceivedIsTxTime <= 31703) { if (!ssValue.empty()) { char fTmp; char fUnused; ssValue >> fTmp >> fUnused >> wtx.strFromAccount; strErr = strprintf("LoadWallet() upgrading tx ver=%d %d '%s' %s", wtx.fTimeReceivedIsTxTime, fTmp, wtx.strFromAccount.c_str(), hash.ToString().c_str()); wtx.fTimeReceivedIsTxTime = fTmp; } else { strErr = strprintf("LoadWallet() repairing tx ver=%d %s", wtx.fTimeReceivedIsTxTime, hash.ToString().c_str()); wtx.fTimeReceivedIsTxTime = 0; } wss.vWalletUpgrade.push_back(hash); } if (wtx.nOrderPos == -1) wss.fAnyUnordered = true; //// debug print //printf("LoadWallet %s\n", wtx.GetHash().ToString().c_str()); //printf(" %12"PRId64" %s %s %s\n", // wtx.vout[0].nValue, // DateTimeStrFormat("%x %H:%M:%S", wtx.GetBlockTime()).c_str(), // wtx.hashBlock.ToString().substr(0,20).c_str(), // wtx.mapValue["message"].c_str()); } else if (strType == "acentry") { string strAccount; ssKey >> strAccount; uint64_t nNumber; ssKey >> nNumber; if (nNumber > nAccountingEntryNumber) nAccountingEntryNumber = nNumber; if (!wss.fAnyUnordered) { CAccountingEntry acentry; ssValue >> acentry; if (acentry.nOrderPos == -1) wss.fAnyUnordered = true; } } else if (strType == "watchs") { CScript script; ssKey >> script; char fYes; ssValue >> fYes; if (fYes == '1') pwallet->LoadWatchOnly(script); // Watch-only addresses have no birthday information for now, // so set the wallet birthday to the beginning of time. pwallet->nTimeFirstKey = 1; } else if (strType == "key" || strType == "wkey") { vector<unsigned char> vchPubKey; ssKey >> vchPubKey; CKey key; if (strType == "key") { wss.nKeys++; CPrivKey pkey; ssValue >> pkey; key.SetPubKey(vchPubKey); if (!key.SetPrivKey(pkey)) { strErr = "Error reading wallet database: CPrivKey corrupt"; return false; } if (key.GetPubKey() != vchPubKey) { strErr = "Error reading wallet database: CPrivKey pubkey inconsistency"; return false; } if (!key.IsValid()) { strErr = "Error reading wallet database: invalid CPrivKey"; return false; } } else { CWalletKey wkey; ssValue >> wkey; key.SetPubKey(vchPubKey); if (!key.SetPrivKey(wkey.vchPrivKey)) { strErr = "Error reading wallet database: CPrivKey corrupt"; return false; } if (key.GetPubKey() != vchPubKey) { strErr = "Error reading wallet database: CWalletKey pubkey inconsistency"; return false; } if (!key.IsValid()) { strErr = "Error reading wallet database: invalid CWalletKey"; return false; } } if (!pwallet->LoadKey(key)) { strErr = "Error reading wallet database: LoadKey failed"; return false; } } else if (strType == "mkey") { unsigned int nID; ssKey >> nID; CMasterKey kMasterKey; ssValue >> kMasterKey; if(pwallet->mapMasterKeys.count(nID) != 0) { strErr = strprintf("Error reading wallet database: duplicate CMasterKey id %u", nID); return false; } pwallet->mapMasterKeys[nID] = kMasterKey; if (pwallet->nMasterKeyMaxID < nID) pwallet->nMasterKeyMaxID = nID; } else if (strType == "ckey") { wss.nCKeys++; vector<unsigned char> vchPubKey; ssKey >> vchPubKey; vector<unsigned char> vchPrivKey; ssValue >> vchPrivKey; if (!pwallet->LoadCryptedKey(vchPubKey, vchPrivKey)) { strErr = "Error reading wallet database: LoadCryptedKey failed"; return false; } wss.fIsEncrypted = true; } else if (strType == "keymeta") { CPubKey vchPubKey; ssKey >> vchPubKey; CKeyMetadata keyMeta; ssValue >> keyMeta; wss.nKeyMeta++; pwallet->LoadKeyMetadata(vchPubKey, keyMeta); // find earliest key creation time, as wallet birthday if (!pwallet->nTimeFirstKey || (keyMeta.nCreateTime < pwallet->nTimeFirstKey)) pwallet->nTimeFirstKey = keyMeta.nCreateTime; } else if (strType == "defaultkey") { ssValue >> pwallet->vchDefaultKey; } else if (strType == "pool") { int64_t nIndex; ssKey >> nIndex; CKeyPool keypool; ssValue >> keypool; pwallet->setKeyPool.insert(nIndex); // If no metadata exists yet, create a default with the pool key's // creation time. Note that this may be overwritten by actually // stored metadata for that key later, which is fine. CKeyID keyid = keypool.vchPubKey.GetID(); if (pwallet->mapKeyMetadata.count(keyid) == 0) pwallet->mapKeyMetadata[keyid] = CKeyMetadata(keypool.nTime); } else if (strType == "version") { ssValue >> wss.nFileVersion; if (wss.nFileVersion == 10300) wss.nFileVersion = 300; } else if (strType == "cscript") { uint160 hash; ssKey >> hash; CScript script; ssValue >> script; if (!pwallet->LoadCScript(script)) { strErr = "Error reading wallet database: LoadCScript failed"; return false; } } else if (strType == "orderposnext") { ssValue >> pwallet->nOrderPosNext; } } catch (...) { return false; } return true; } static bool IsKeyType(string strType) { return (strType== "key" || strType == "wkey" || strType == "mkey" || strType == "ckey"); } DBErrors CWalletDB::LoadWallet(CWallet* pwallet) { pwallet->vchDefaultKey = CPubKey(); CWalletScanState wss; bool fNoncriticalErrors = false; DBErrors result = DB_LOAD_OK; try { LOCK(pwallet->cs_wallet); int nMinVersion = 0; if (Read((string)"minversion", nMinVersion)) { if (nMinVersion > CLIENT_VERSION) return DB_TOO_NEW; pwallet->LoadMinVersion(nMinVersion); } // Get cursor Dbc* pcursor = GetCursor(); if (!pcursor) { printf("Error getting wallet database cursor\n"); return DB_CORRUPT; } while (true) { // Read next record CDataStream ssKey(SER_DISK, CLIENT_VERSION); CDataStream ssValue(SER_DISK, CLIENT_VERSION); int ret = ReadAtCursor(pcursor, ssKey, ssValue); if (ret == DB_NOTFOUND) break; else if (ret != 0) { printf("Error reading next record from wallet database\n"); return DB_CORRUPT; } // Try to be tolerant of single corrupt records: string strType, strErr; if (!ReadKeyValue(pwallet, ssKey, ssValue, wss, strType, strErr)) { // losing keys is considered a catastrophic error, anything else // we assume the user can live with: if (IsKeyType(strType)) result = DB_CORRUPT; else { // Leave other errors alone, if we try to fix them we might make things worse. fNoncriticalErrors = true; // ... but do warn the user there is something wrong. if (strType == "tx") // Rescan if there is a bad transaction record: SoftSetBoolArg("-rescan", true); } } if (!strErr.empty()) printf("%s\n", strErr.c_str()); } pcursor->close(); } catch (...) { result = DB_CORRUPT; } if (fNoncriticalErrors && result == DB_LOAD_OK) result = DB_NONCRITICAL_ERROR; // Any wallet corruption at all: skip any rewriting or // upgrading, we don't want to make it worse. if (result != DB_LOAD_OK) return result; printf("nFileVersion = %d\n", wss.nFileVersion); printf("Keys: %u plaintext, %u encrypted, %u w/ metadata, %u total\n", wss.nKeys, wss.nCKeys, wss.nKeyMeta, wss.nKeys + wss.nCKeys); // nTimeFirstKey is only reliable if all keys have metadata if ((wss.nKeys + wss.nCKeys) != wss.nKeyMeta) pwallet->nTimeFirstKey = 1; // 0 would be considered 'no value' BOOST_FOREACH(uint256 hash, wss.vWalletUpgrade) WriteTx(hash, pwallet->mapWallet[hash]); // Rewrite encrypted wallets of versions 0.4.0 and 0.5.0rc: if (wss.fIsEncrypted && (wss.nFileVersion == 40000 || wss.nFileVersion == 50000)) return DB_NEED_REWRITE; if (wss.nFileVersion < CLIENT_VERSION) // Update WriteVersion(CLIENT_VERSION); if (wss.fAnyUnordered) result = ReorderTransactions(pwallet); return result; } DBErrors CWalletDB::FindWalletTx(CWallet* pwallet, vector<uint256>& vTxHash) { pwallet->vchDefaultKey = CPubKey(); CWalletScanState wss; bool fNoncriticalErrors = false; DBErrors result = DB_LOAD_OK; try { LOCK(pwallet->cs_wallet); int nMinVersion = 0; if (Read((string)"minversion", nMinVersion)) { if (nMinVersion > CLIENT_VERSION) return DB_TOO_NEW; pwallet->LoadMinVersion(nMinVersion); } // Get cursor Dbc* pcursor = GetCursor(); if (!pcursor) { printf("Error getting wallet database cursor\n"); return DB_CORRUPT; } while (true) { // Read next record CDataStream ssKey(SER_DISK, CLIENT_VERSION); CDataStream ssValue(SER_DISK, CLIENT_VERSION); int ret = ReadAtCursor(pcursor, ssKey, ssValue); if (ret == DB_NOTFOUND) break; else if (ret != 0) { printf("Error reading next record from wallet database\n"); return DB_CORRUPT; } string strType; ssKey >> strType; if (strType == "tx") { uint256 hash; ssKey >> hash; vTxHash.push_back(hash); } } pcursor->close(); } catch (boost::thread_interrupted) { throw; } catch (...) { result = DB_CORRUPT; } if (fNoncriticalErrors && result == DB_LOAD_OK) result = DB_NONCRITICAL_ERROR; return result; } DBErrors CWalletDB::ZapWalletTx(CWallet* pwallet) { // build list of wallet TXs vector<uint256> vTxHash; DBErrors err = FindWalletTx(pwallet, vTxHash); if (err != DB_LOAD_OK) return err; // erase each wallet TX BOOST_FOREACH (uint256& hash, vTxHash) { if (!EraseTx(hash)) return DB_CORRUPT; } return DB_LOAD_OK; } void ThreadFlushWalletDB(void* parg) { // Make this thread recognisable as the wallet flushing thread RenameThread("AppleCoin-wallet"); const string& strFile = ((const string*)parg)[0]; static bool fOneThread; if (fOneThread) return; fOneThread = true; if (!GetBoolArg("-flushwallet", true)) return; unsigned int nLastSeen = nWalletDBUpdated; unsigned int nLastFlushed = nWalletDBUpdated; int64_t nLastWalletUpdate = GetTime(); while (!fShutdown) { Sleep(500); if (nLastSeen != nWalletDBUpdated) { nLastSeen = nWalletDBUpdated; nLastWalletUpdate = GetTime(); } if (nLastFlushed != nWalletDBUpdated && GetTime() - nLastWalletUpdate >= 2) { TRY_LOCK(bitdb.cs_db,lockDb); if (lockDb) { // Don't do this if any databases are in use int nRefCount = 0; map<string, int>::iterator mi = bitdb.mapFileUseCount.begin(); while (mi != bitdb.mapFileUseCount.end()) { nRefCount += (*mi).second; mi++; } if (nRefCount == 0 && !fShutdown) { map<string, int>::iterator mi = bitdb.mapFileUseCount.find(strFile); if (mi != bitdb.mapFileUseCount.end()) { printf("Flushing wallet.dat\n"); nLastFlushed = nWalletDBUpdated; int64_t nStart = GetTimeMillis(); // Flush wallet.dat so it's self contained bitdb.CloseDb(strFile); bitdb.CheckpointLSN(strFile); bitdb.mapFileUseCount.erase(mi++); printf("Flushed wallet.dat %" PRId64 "ms\n", GetTimeMillis() - nStart); } } } } } } bool BackupWallet(const CWallet& wallet, const string& strDest) { if (!wallet.fFileBacked) return false; while (!fShutdown) { { LOCK(bitdb.cs_db); if (!bitdb.mapFileUseCount.count(wallet.strWalletFile) || bitdb.mapFileUseCount[wallet.strWalletFile] == 0) { // Flush log data to the dat file bitdb.CloseDb(wallet.strWalletFile); bitdb.CheckpointLSN(wallet.strWalletFile); bitdb.mapFileUseCount.erase(wallet.strWalletFile); // Copy wallet.dat filesystem::path pathSrc = GetDataDir() / wallet.strWalletFile; filesystem::path pathDest(strDest); if (filesystem::is_directory(pathDest)) pathDest /= wallet.strWalletFile; try { #if BOOST_VERSION >= 104000 filesystem::copy_file(pathSrc, pathDest, filesystem::copy_option::overwrite_if_exists); #else filesystem::copy_file(pathSrc, pathDest); #endif printf("copied wallet.dat to %s\n", pathDest.string().c_str()); return true; } catch(const filesystem::filesystem_error &e) { printf("error copying wallet.dat to %s - %s\n", pathDest.string().c_str(), e.what()); return false; } } } Sleep(100); } return false; } bool DumpWallet(CWallet* pwallet, const string& strDest) { if (!pwallet->fFileBacked) return false; while (!fShutdown) { // Populate maps std::map<CKeyID, int64_t> mapKeyBirth; std::set<CKeyID> setKeyPool; pwallet->GetKeyBirthTimes(mapKeyBirth); pwallet->GetAllReserveKeys(setKeyPool); // sort time/key pairs std::vector<std::pair<int64_t, CKeyID> > vKeyBirth; for (std::map<CKeyID, int64_t>::const_iterator it = mapKeyBirth.begin(); it != mapKeyBirth.end(); it++) { vKeyBirth.push_back(std::make_pair(it->second, it->first)); } mapKeyBirth.clear(); std::sort(vKeyBirth.begin(), vKeyBirth.end()); // open outputfile as a stream ofstream file; file.open(strDest.c_str()); if (!file.is_open()) return false; // produce output file << strprintf("# Wallet dump created by AppleCoin %s (%s)\n", CLIENT_BUILD.c_str(), CLIENT_DATE.c_str()); file << strprintf("# * Created on %s\n", EncodeDumpTime(GetTime()).c_str()); file << strprintf("# * Best block at time of backup was %i (%s),\n", nBestHeight, hashBestChain.ToString().c_str()); file << strprintf("# mined on %s\n", EncodeDumpTime(pindexBest->nTime).c_str()); file << "\n"; for (std::vector<std::pair<int64_t, CKeyID> >::const_iterator it = vKeyBirth.begin(); it != vKeyBirth.end(); it++) { const CKeyID &keyid = it->second; std::string strTime = EncodeDumpTime(it->first); std::string strAddr = CBitcoinAddress(keyid).ToString(); bool IsCompressed; CKey key; if (pwallet->GetKey(keyid, key)) { if (pwallet->mapAddressBook.count(keyid)) { CSecret secret = key.GetSecret(IsCompressed); file << strprintf("%s %s label=%s # addr=%s\n", CBitcoinSecret(secret, IsCompressed).ToString().c_str(), strTime.c_str(), EncodeDumpString(pwallet->mapAddressBook[keyid]).c_str(), strAddr.c_str()); } else if (setKeyPool.count(keyid)) { CSecret secret = key.GetSecret(IsCompressed); file << strprintf("%s %s reserve=1 # addr=%s\n", CBitcoinSecret(secret, IsCompressed).ToString().c_str(), strTime.c_str(), strAddr.c_str()); } else { CSecret secret = key.GetSecret(IsCompressed); file << strprintf("%s %s change=1 # addr=%s\n", CBitcoinSecret(secret, IsCompressed).ToString().c_str(), strTime.c_str(), strAddr.c_str()); } } } file << "\n"; file << "# End of dump\n"; file.close(); return true; } return false; } bool ImportWallet(CWallet *pwallet, const string& strLocation) { if (!pwallet->fFileBacked) return false; while (!fShutdown) { // open inputfile as stream ifstream file; file.open(strLocation.c_str()); if (!file.is_open()) return false; int64_t nTimeBegin = pindexBest->nTime; bool fGood = true; // read through input file checking and importing keys into wallet. while (file.good()) { std::string line; std::getline(file, line); if (line.empty() || line[0] == '#') continue; std::vector<std::string> vstr; boost::split(vstr, line, boost::is_any_of(" ")); if (vstr.size() < 2) continue; CBitcoinSecret vchSecret; if (!vchSecret.SetString(vstr[0])) continue; bool fCompressed; CKey key; CSecret secret = vchSecret.GetSecret(fCompressed); key.SetSecret(secret, fCompressed); CKeyID keyid = key.GetPubKey().GetID(); if (pwallet->HaveKey(keyid)) { printf("Skipping import of %s (key already present)\n", CBitcoinAddress(keyid).ToString().c_str()); continue; } int64_t nTime = DecodeDumpTime(vstr[1]); std::string strLabel; bool fLabel = true; for (unsigned int nStr = 2; nStr < vstr.size(); nStr++) { if (boost::algorithm::starts_with(vstr[nStr], "#")) break; if (vstr[nStr] == "change=1") fLabel = false; if (vstr[nStr] == "reserve=1") fLabel = false; if (boost::algorithm::starts_with(vstr[nStr], "label=")) { strLabel = DecodeDumpString(vstr[nStr].substr(6)); fLabel = true; } } printf("Importing %s...\n", CBitcoinAddress(keyid).ToString().c_str()); if (!pwallet->AddKey(key)) { fGood = false; continue; } pwallet->mapKeyMetadata[keyid].nCreateTime = nTime; if (fLabel) pwallet->SetAddressBookName(keyid, strLabel); nTimeBegin = std::min(nTimeBegin, nTime); } file.close(); // rescan block chain looking for coins from new keys CBlockIndex *pindex = pindexBest; while (pindex && pindex->pprev && pindex->nTime > nTimeBegin - 7200) pindex = pindex->pprev; printf("Rescanning last %i blocks\n", pindexBest->nHeight - pindex->nHeight + 1); pwallet->ScanForWalletTransactions(pindex); pwallet->ReacceptWalletTransactions(); pwallet->MarkDirty(); return fGood; } return false; } // // Try to (very carefully!) recover wallet.dat if there is a problem. // bool CWalletDB::Recover(CDBEnv& dbenv, std::string filename, bool fOnlyKeys) { // Recovery procedure: // move wallet.dat to wallet.timestamp.bak // Call Salvage with fAggressive=true to // get as much data as possible. // Rewrite salvaged data to wallet.dat // Set -rescan so any missing transactions will be // found. int64_t now = GetTime(); std::string newFilename = strprintf("wallet.%" PRId64 ".bak", now); int result = dbenv.dbenv.dbrename(NULL, filename.c_str(), NULL, newFilename.c_str(), DB_AUTO_COMMIT); if (result == 0) printf("Renamed %s to %s\n", filename.c_str(), newFilename.c_str()); else { printf("Failed to rename %s to %s\n", filename.c_str(), newFilename.c_str()); return false; } std::vector<CDBEnv::KeyValPair> salvagedData; bool allOK = dbenv.Salvage(newFilename, true, salvagedData); if (salvagedData.empty()) { printf("Salvage(aggressive) found no records in %s.\n", newFilename.c_str()); return false; } printf("Salvage(aggressive) found %" PRIszu " records\n", salvagedData.size()); bool fSuccess = allOK; Db* pdbCopy = new Db(&dbenv.dbenv, 0); int ret = pdbCopy->open(NULL, // Txn pointer filename.c_str(), // Filename "main", // Logical db name DB_BTREE, // Database type DB_CREATE, // Flags 0); if (ret > 0) { printf("Cannot create database file %s\n", filename.c_str()); return false; } CWallet dummyWallet; CWalletScanState wss; DbTxn* ptxn = dbenv.TxnBegin(); BOOST_FOREACH(CDBEnv::KeyValPair& row, salvagedData) { if (fOnlyKeys) { CDataStream ssKey(row.first, SER_DISK, CLIENT_VERSION); CDataStream ssValue(row.second, SER_DISK, CLIENT_VERSION); string strType, strErr; bool fReadOK = ReadKeyValue(&dummyWallet, ssKey, ssValue, wss, strType, strErr); if (!IsKeyType(strType)) continue; if (!fReadOK) { printf("WARNING: CWalletDB::Recover skipping %s: %s\n", strType.c_str(), strErr.c_str()); continue; } } Dbt datKey(&row.first[0], row.first.size()); Dbt datValue(&row.second[0], row.second.size()); int ret2 = pdbCopy->put(ptxn, &datKey, &datValue, DB_NOOVERWRITE); if (ret2 > 0) fSuccess = false; } ptxn->commit(0); pdbCopy->close(0); delete pdbCopy; return fSuccess; } bool CWalletDB::Recover(CDBEnv& dbenv, std::string filename) { return CWalletDB::Recover(dbenv, filename, false); }