llvm-project
215 строк · 7.3 Кб
1//===- ComparisonCategories.cpp - Three Way Comparison Data -----*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the Comparison Category enum and data types, which
10// store the types and expressions needed to support operator<=>
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ComparisonCategories.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/Decl.h"
17#include "clang/AST/DeclCXX.h"
18#include "clang/AST/Type.h"
19#include "llvm/ADT/SmallVector.h"
20#include <optional>
21
22using namespace clang;
23
24std::optional<ComparisonCategoryType>
25clang::getComparisonCategoryForBuiltinCmp(QualType T) {
26using CCT = ComparisonCategoryType;
27
28if (T->isIntegralOrEnumerationType())
29return CCT::StrongOrdering;
30
31if (T->isRealFloatingType())
32return CCT::PartialOrdering;
33
34// C++2a [expr.spaceship]p8: If the composite pointer type is an object
35// pointer type, p <=> q is of type std::strong_ordering.
36// Note: this assumes neither operand is a null pointer constant.
37if (T->isObjectPointerType())
38return CCT::StrongOrdering;
39
40// TODO: Extend support for operator<=> to ObjC types.
41return std::nullopt;
42}
43
44bool ComparisonCategoryInfo::ValueInfo::hasValidIntValue() const {
45assert(VD && "must have var decl");
46if (!VD->isUsableInConstantExpressions(VD->getASTContext()))
47return false;
48
49// Before we attempt to get the value of the first field, ensure that we
50// actually have one (and only one) field.
51const auto *Record = VD->getType()->getAsCXXRecordDecl();
52if (std::distance(Record->field_begin(), Record->field_end()) != 1 ||
53!Record->field_begin()->getType()->isIntegralOrEnumerationType())
54return false;
55
56return true;
57}
58
59/// Attempt to determine the integer value used to represent the comparison
60/// category result by evaluating the initializer for the specified VarDecl as
61/// a constant expression and retrieving the value of the class's first
62/// (and only) field.
63///
64/// Note: The STL types are expected to have the form:
65/// struct X { T value; };
66/// where T is an integral or enumeration type.
67llvm::APSInt ComparisonCategoryInfo::ValueInfo::getIntValue() const {
68assert(hasValidIntValue() && "must have a valid value");
69return VD->evaluateValue()->getStructField(0).getInt();
70}
71
72ComparisonCategoryInfo::ValueInfo *ComparisonCategoryInfo::lookupValueInfo(
73ComparisonCategoryResult ValueKind) const {
74// Check if we already have a cache entry for this value.
75auto It = llvm::find_if(
76Objects, [&](ValueInfo const &Info) { return Info.Kind == ValueKind; });
77if (It != Objects.end())
78return &(*It);
79
80// We don't have a cached result. Lookup the variable declaration and create
81// a new entry representing it.
82DeclContextLookupResult Lookup = Record->getCanonicalDecl()->lookup(
83&Ctx.Idents.get(ComparisonCategories::getResultString(ValueKind)));
84if (Lookup.empty() || !isa<VarDecl>(Lookup.front()))
85return nullptr;
86Objects.emplace_back(ValueKind, cast<VarDecl>(Lookup.front()));
87return &Objects.back();
88}
89
90static const NamespaceDecl *lookupStdNamespace(const ASTContext &Ctx,
91NamespaceDecl *&StdNS) {
92if (!StdNS) {
93DeclContextLookupResult Lookup =
94Ctx.getTranslationUnitDecl()->lookup(&Ctx.Idents.get("std"));
95if (!Lookup.empty())
96StdNS = dyn_cast<NamespaceDecl>(Lookup.front());
97}
98return StdNS;
99}
100
101static const CXXRecordDecl *lookupCXXRecordDecl(const ASTContext &Ctx,
102const NamespaceDecl *StdNS,
103ComparisonCategoryType Kind) {
104StringRef Name = ComparisonCategories::getCategoryString(Kind);
105DeclContextLookupResult Lookup = StdNS->lookup(&Ctx.Idents.get(Name));
106if (!Lookup.empty())
107if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Lookup.front()))
108return RD;
109return nullptr;
110}
111
112const ComparisonCategoryInfo *
113ComparisonCategories::lookupInfo(ComparisonCategoryType Kind) const {
114auto It = Data.find(static_cast<char>(Kind));
115if (It != Data.end())
116return &It->second;
117
118if (const NamespaceDecl *NS = lookupStdNamespace(Ctx, StdNS))
119if (const CXXRecordDecl *RD = lookupCXXRecordDecl(Ctx, NS, Kind))
120return &Data.try_emplace((char)Kind, Ctx, RD, Kind).first->second;
121
122return nullptr;
123}
124
125const ComparisonCategoryInfo *
126ComparisonCategories::lookupInfoForType(QualType Ty) const {
127assert(!Ty.isNull() && "type must be non-null");
128using CCT = ComparisonCategoryType;
129const auto *RD = Ty->getAsCXXRecordDecl();
130if (!RD)
131return nullptr;
132
133// Check to see if we have information for the specified type cached.
134const auto *CanonRD = RD->getCanonicalDecl();
135for (const auto &KV : Data) {
136const ComparisonCategoryInfo &Info = KV.second;
137if (CanonRD == Info.Record->getCanonicalDecl())
138return &Info;
139}
140
141if (!RD->getEnclosingNamespaceContext()->isStdNamespace())
142return nullptr;
143
144// If not, check to see if the decl names a type in namespace std with a name
145// matching one of the comparison category types.
146for (unsigned I = static_cast<unsigned>(CCT::First),
147End = static_cast<unsigned>(CCT::Last);
148I <= End; ++I) {
149CCT Kind = static_cast<CCT>(I);
150
151// We've found the comparison category type. Build a new cache entry for
152// it.
153if (getCategoryString(Kind) == RD->getName())
154return &Data.try_emplace((char)Kind, Ctx, RD, Kind).first->second;
155}
156
157// We've found nothing. This isn't a comparison category type.
158return nullptr;
159}
160
161const ComparisonCategoryInfo &ComparisonCategories::getInfoForType(QualType Ty) const {
162const ComparisonCategoryInfo *Info = lookupInfoForType(Ty);
163assert(Info && "info for comparison category not found");
164return *Info;
165}
166
167QualType ComparisonCategoryInfo::getType() const {
168assert(Record);
169return QualType(Record->getTypeForDecl(), 0);
170}
171
172StringRef ComparisonCategories::getCategoryString(ComparisonCategoryType Kind) {
173using CCKT = ComparisonCategoryType;
174switch (Kind) {
175case CCKT::PartialOrdering:
176return "partial_ordering";
177case CCKT::WeakOrdering:
178return "weak_ordering";
179case CCKT::StrongOrdering:
180return "strong_ordering";
181}
182llvm_unreachable("unhandled cases in switch");
183}
184
185StringRef ComparisonCategories::getResultString(ComparisonCategoryResult Kind) {
186using CCVT = ComparisonCategoryResult;
187switch (Kind) {
188case CCVT::Equal:
189return "equal";
190case CCVT::Equivalent:
191return "equivalent";
192case CCVT::Less:
193return "less";
194case CCVT::Greater:
195return "greater";
196case CCVT::Unordered:
197return "unordered";
198}
199llvm_unreachable("unhandled case in switch");
200}
201
202std::vector<ComparisonCategoryResult>
203ComparisonCategories::getPossibleResultsForType(ComparisonCategoryType Type) {
204using CCT = ComparisonCategoryType;
205using CCR = ComparisonCategoryResult;
206std::vector<CCR> Values;
207Values.reserve(4);
208bool IsStrong = Type == CCT::StrongOrdering;
209Values.push_back(IsStrong ? CCR::Equal : CCR::Equivalent);
210Values.push_back(CCR::Less);
211Values.push_back(CCR::Greater);
212if (Type == CCT::PartialOrdering)
213Values.push_back(CCR::Unordered);
214return Values;
215}
216