1 //===--- Expr.cpp - Expression AST Node Implementation --------------------===//
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 implements the Expr class and subclasses.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "clang/AST/Expr.h"
14 #include "clang/AST/APValue.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/ComputeDependence.h"
19 #include "clang/AST/DeclCXX.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/DependenceFlags.h"
23 #include "clang/AST/EvaluatedExprVisitor.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/IgnoreExpr.h"
26 #include "clang/AST/Mangle.h"
27 #include "clang/AST/RecordLayout.h"
28 #include "clang/Basic/Builtins.h"
29 #include "clang/Basic/CharInfo.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/Lexer.h"
33 #include "clang/Lex/LiteralSupport.h"
34 #include "clang/Lex/Preprocessor.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/Format.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include <algorithm>
39 #include <cstring>
40 #include <optional>
41 using namespace clang;
42
getBestDynamicClassTypeExpr() const43 const Expr *Expr::getBestDynamicClassTypeExpr() const {
44 const Expr *E = this;
45 while (true) {
46 E = E->IgnoreParenBaseCasts();
47
48 // Follow the RHS of a comma operator.
49 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
50 if (BO->getOpcode() == BO_Comma) {
51 E = BO->getRHS();
52 continue;
53 }
54 }
55
56 // Step into initializer for materialized temporaries.
57 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
58 E = MTE->getSubExpr();
59 continue;
60 }
61
62 break;
63 }
64
65 return E;
66 }
67
getBestDynamicClassType() const68 const CXXRecordDecl *Expr::getBestDynamicClassType() const {
69 const Expr *E = getBestDynamicClassTypeExpr();
70 QualType DerivedType = E->getType();
71 if (const PointerType *PTy = DerivedType->getAs<PointerType>())
72 DerivedType = PTy->getPointeeType();
73
74 if (DerivedType->isDependentType())
75 return nullptr;
76
77 const RecordType *Ty = DerivedType->castAs<RecordType>();
78 Decl *D = Ty->getDecl();
79 return cast<CXXRecordDecl>(D);
80 }
81
skipRValueSubobjectAdjustments(SmallVectorImpl<const Expr * > & CommaLHSs,SmallVectorImpl<SubobjectAdjustment> & Adjustments) const82 const Expr *Expr::skipRValueSubobjectAdjustments(
83 SmallVectorImpl<const Expr *> &CommaLHSs,
84 SmallVectorImpl<SubobjectAdjustment> &Adjustments) const {
85 const Expr *E = this;
86 while (true) {
87 E = E->IgnoreParens();
88
89 if (const auto *CE = dyn_cast<CastExpr>(E)) {
90 if ((CE->getCastKind() == CK_DerivedToBase ||
91 CE->getCastKind() == CK_UncheckedDerivedToBase) &&
92 E->getType()->isRecordType()) {
93 E = CE->getSubExpr();
94 const auto *Derived =
95 cast<CXXRecordDecl>(E->getType()->castAs<RecordType>()->getDecl());
96 Adjustments.push_back(SubobjectAdjustment(CE, Derived));
97 continue;
98 }
99
100 if (CE->getCastKind() == CK_NoOp) {
101 E = CE->getSubExpr();
102 continue;
103 }
104 } else if (const auto *ME = dyn_cast<MemberExpr>(E)) {
105 if (!ME->isArrow()) {
106 assert(ME->getBase()->getType()->getAsRecordDecl());
107 if (const auto *Field = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
108 if (!Field->isBitField() && !Field->getType()->isReferenceType()) {
109 E = ME->getBase();
110 Adjustments.push_back(SubobjectAdjustment(Field));
111 continue;
112 }
113 }
114 }
115 } else if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
116 if (BO->getOpcode() == BO_PtrMemD) {
117 assert(BO->getRHS()->isPRValue());
118 E = BO->getLHS();
119 const auto *MPT = BO->getRHS()->getType()->getAs<MemberPointerType>();
120 Adjustments.push_back(SubobjectAdjustment(MPT, BO->getRHS()));
121 continue;
122 }
123 if (BO->getOpcode() == BO_Comma) {
124 CommaLHSs.push_back(BO->getLHS());
125 E = BO->getRHS();
126 continue;
127 }
128 }
129
130 // Nothing changed.
131 break;
132 }
133 return E;
134 }
135
isKnownToHaveBooleanValue(bool Semantic) const136 bool Expr::isKnownToHaveBooleanValue(bool Semantic) const {
137 const Expr *E = IgnoreParens();
138
139 // If this value has _Bool type, it is obvious 0/1.
140 if (E->getType()->isBooleanType()) return true;
141 // If this is a non-scalar-integer type, we don't care enough to try.
142 if (!E->getType()->isIntegralOrEnumerationType()) return false;
143
144 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
145 switch (UO->getOpcode()) {
146 case UO_Plus:
147 return UO->getSubExpr()->isKnownToHaveBooleanValue(Semantic);
148 case UO_LNot:
149 return true;
150 default:
151 return false;
152 }
153 }
154
155 // Only look through implicit casts. If the user writes
156 // '(int) (a && b)' treat it as an arbitrary int.
157 // FIXME: Should we look through any cast expression in !Semantic mode?
158 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
159 return CE->getSubExpr()->isKnownToHaveBooleanValue(Semantic);
160
161 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
162 switch (BO->getOpcode()) {
163 default: return false;
164 case BO_LT: // Relational operators.
165 case BO_GT:
166 case BO_LE:
167 case BO_GE:
168 case BO_EQ: // Equality operators.
169 case BO_NE:
170 case BO_LAnd: // AND operator.
171 case BO_LOr: // Logical OR operator.
172 return true;
173
174 case BO_And: // Bitwise AND operator.
175 case BO_Xor: // Bitwise XOR operator.
176 case BO_Or: // Bitwise OR operator.
177 // Handle things like (x==2)|(y==12).
178 return BO->getLHS()->isKnownToHaveBooleanValue(Semantic) &&
179 BO->getRHS()->isKnownToHaveBooleanValue(Semantic);
180
181 case BO_Comma:
182 case BO_Assign:
183 return BO->getRHS()->isKnownToHaveBooleanValue(Semantic);
184 }
185 }
186
187 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
188 return CO->getTrueExpr()->isKnownToHaveBooleanValue(Semantic) &&
189 CO->getFalseExpr()->isKnownToHaveBooleanValue(Semantic);
190
191 if (isa<ObjCBoolLiteralExpr>(E))
192 return true;
193
194 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
195 return OVE->getSourceExpr()->isKnownToHaveBooleanValue(Semantic);
196
197 if (const FieldDecl *FD = E->getSourceBitField())
198 if (!Semantic && FD->getType()->isUnsignedIntegerType() &&
199 !FD->getBitWidth()->isValueDependent() && FD->getBitWidthValue() == 1)
200 return true;
201
202 return false;
203 }
204
isFlexibleArrayMemberLike(const ASTContext & Ctx,LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel,bool IgnoreTemplateOrMacroSubstitution) const205 bool Expr::isFlexibleArrayMemberLike(
206 const ASTContext &Ctx,
207 LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel,
208 bool IgnoreTemplateOrMacroSubstitution) const {
209 const Expr *E = IgnoreParens();
210 const Decl *D = nullptr;
211
212 if (const auto *ME = dyn_cast<MemberExpr>(E))
213 D = ME->getMemberDecl();
214 else if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
215 D = DRE->getDecl();
216 else if (const auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
217 D = IRE->getDecl();
218
219 return Decl::isFlexibleArrayMemberLike(Ctx, D, E->getType(),
220 StrictFlexArraysLevel,
221 IgnoreTemplateOrMacroSubstitution);
222 }
223
224 const ValueDecl *
getAsBuiltinConstantDeclRef(const ASTContext & Context) const225 Expr::getAsBuiltinConstantDeclRef(const ASTContext &Context) const {
226 Expr::EvalResult Eval;
227
228 if (EvaluateAsConstantExpr(Eval, Context)) {
229 APValue &Value = Eval.Val;
230
231 if (Value.isMemberPointer())
232 return Value.getMemberPointerDecl();
233
234 if (Value.isLValue() && Value.getLValueOffset().isZero())
235 return Value.getLValueBase().dyn_cast<const ValueDecl *>();
236 }
237
238 return nullptr;
239 }
240
241 // Amusing macro metaprogramming hack: check whether a class provides
242 // a more specific implementation of getExprLoc().
243 //
244 // See also Stmt.cpp:{getBeginLoc(),getEndLoc()}.
245 namespace {
246 /// This implementation is used when a class provides a custom
247 /// implementation of getExprLoc.
248 template <class E, class T>
getExprLocImpl(const Expr * expr,SourceLocation (T::* v)()const)249 SourceLocation getExprLocImpl(const Expr *expr,
250 SourceLocation (T::*v)() const) {
251 return static_cast<const E*>(expr)->getExprLoc();
252 }
253
254 /// This implementation is used when a class doesn't provide
255 /// a custom implementation of getExprLoc. Overload resolution
256 /// should pick it over the implementation above because it's
257 /// more specialized according to function template partial ordering.
258 template <class E>
getExprLocImpl(const Expr * expr,SourceLocation (Expr::* v)()const)259 SourceLocation getExprLocImpl(const Expr *expr,
260 SourceLocation (Expr::*v)() const) {
261 return static_cast<const E *>(expr)->getBeginLoc();
262 }
263 }
264
getEnumCoercedType(const ASTContext & Ctx) const265 QualType Expr::getEnumCoercedType(const ASTContext &Ctx) const {
266 if (isa<EnumType>(getType()))
267 return getType();
268 if (const auto *ECD = getEnumConstantDecl()) {
269 const auto *ED = cast<EnumDecl>(ECD->getDeclContext());
270 if (ED->isCompleteDefinition())
271 return Ctx.getTypeDeclType(ED);
272 }
273 return getType();
274 }
275
getExprLoc() const276 SourceLocation Expr::getExprLoc() const {
277 switch (getStmtClass()) {
278 case Stmt::NoStmtClass: llvm_unreachable("statement without class");
279 #define ABSTRACT_STMT(type)
280 #define STMT(type, base) \
281 case Stmt::type##Class: break;
282 #define EXPR(type, base) \
283 case Stmt::type##Class: return getExprLocImpl<type>(this, &type::getExprLoc);
284 #include "clang/AST/StmtNodes.inc"
285 }
286 llvm_unreachable("unknown expression kind");
287 }
288
289 //===----------------------------------------------------------------------===//
290 // Primary Expressions.
291 //===----------------------------------------------------------------------===//
292
AssertResultStorageKind(ConstantResultStorageKind Kind)293 static void AssertResultStorageKind(ConstantResultStorageKind Kind) {
294 assert((Kind == ConstantResultStorageKind::APValue ||
295 Kind == ConstantResultStorageKind::Int64 ||
296 Kind == ConstantResultStorageKind::None) &&
297 "Invalid StorageKind Value");
298 (void)Kind;
299 }
300
getStorageKind(const APValue & Value)301 ConstantResultStorageKind ConstantExpr::getStorageKind(const APValue &Value) {
302 switch (Value.getKind()) {
303 case APValue::None:
304 case APValue::Indeterminate:
305 return ConstantResultStorageKind::None;
306 case APValue::Int:
307 if (!Value.getInt().needsCleanup())
308 return ConstantResultStorageKind::Int64;
309 [[fallthrough]];
310 default:
311 return ConstantResultStorageKind::APValue;
312 }
313 }
314
315 ConstantResultStorageKind
getStorageKind(const Type * T,const ASTContext & Context)316 ConstantExpr::getStorageKind(const Type *T, const ASTContext &Context) {
317 if (T->isIntegralOrEnumerationType() && Context.getTypeInfo(T).Width <= 64)
318 return ConstantResultStorageKind::Int64;
319 return ConstantResultStorageKind::APValue;
320 }
321
ConstantExpr(Expr * SubExpr,ConstantResultStorageKind StorageKind,bool IsImmediateInvocation)322 ConstantExpr::ConstantExpr(Expr *SubExpr, ConstantResultStorageKind StorageKind,
323 bool IsImmediateInvocation)
324 : FullExpr(ConstantExprClass, SubExpr) {
325 ConstantExprBits.ResultKind = llvm::to_underlying(StorageKind);
326 ConstantExprBits.APValueKind = APValue::None;
327 ConstantExprBits.IsUnsigned = false;
328 ConstantExprBits.BitWidth = 0;
329 ConstantExprBits.HasCleanup = false;
330 ConstantExprBits.IsImmediateInvocation = IsImmediateInvocation;
331
332 if (StorageKind == ConstantResultStorageKind::APValue)
333 ::new (getTrailingObjects<APValue>()) APValue();
334 }
335
Create(const ASTContext & Context,Expr * E,ConstantResultStorageKind StorageKind,bool IsImmediateInvocation)336 ConstantExpr *ConstantExpr::Create(const ASTContext &Context, Expr *E,
337 ConstantResultStorageKind StorageKind,
338 bool IsImmediateInvocation) {
339 assert(!isa<ConstantExpr>(E));
340 AssertResultStorageKind(StorageKind);
341
342 unsigned Size = totalSizeToAlloc<APValue, uint64_t>(
343 StorageKind == ConstantResultStorageKind::APValue,
344 StorageKind == ConstantResultStorageKind::Int64);
345 void *Mem = Context.Allocate(Size, alignof(ConstantExpr));
346 return new (Mem) ConstantExpr(E, StorageKind, IsImmediateInvocation);
347 }
348
Create(const ASTContext & Context,Expr * E,const APValue & Result)349 ConstantExpr *ConstantExpr::Create(const ASTContext &Context, Expr *E,
350 const APValue &Result) {
351 ConstantResultStorageKind StorageKind = getStorageKind(Result);
352 ConstantExpr *Self = Create(Context, E, StorageKind);
353 Self->SetResult(Result, Context);
354 return Self;
355 }
356
ConstantExpr(EmptyShell Empty,ConstantResultStorageKind StorageKind)357 ConstantExpr::ConstantExpr(EmptyShell Empty,
358 ConstantResultStorageKind StorageKind)
359 : FullExpr(ConstantExprClass, Empty) {
360 ConstantExprBits.ResultKind = llvm::to_underlying(StorageKind);
361
362 if (StorageKind == ConstantResultStorageKind::APValue)
363 ::new (getTrailingObjects<APValue>()) APValue();
364 }
365
CreateEmpty(const ASTContext & Context,ConstantResultStorageKind StorageKind)366 ConstantExpr *ConstantExpr::CreateEmpty(const ASTContext &Context,
367 ConstantResultStorageKind StorageKind) {
368 AssertResultStorageKind(StorageKind);
369
370 unsigned Size = totalSizeToAlloc<APValue, uint64_t>(
371 StorageKind == ConstantResultStorageKind::APValue,
372 StorageKind == ConstantResultStorageKind::Int64);
373 void *Mem = Context.Allocate(Size, alignof(ConstantExpr));
374 return new (Mem) ConstantExpr(EmptyShell(), StorageKind);
375 }
376
MoveIntoResult(APValue & Value,const ASTContext & Context)377 void ConstantExpr::MoveIntoResult(APValue &Value, const ASTContext &Context) {
378 assert((unsigned)getStorageKind(Value) <= ConstantExprBits.ResultKind &&
379 "Invalid storage for this value kind");
380 ConstantExprBits.APValueKind = Value.getKind();
381 switch (getResultStorageKind()) {
382 case ConstantResultStorageKind::None:
383 return;
384 case ConstantResultStorageKind::Int64:
385 Int64Result() = *Value.getInt().getRawData();
386 ConstantExprBits.BitWidth = Value.getInt().getBitWidth();
387 ConstantExprBits.IsUnsigned = Value.getInt().isUnsigned();
388 return;
389 case ConstantResultStorageKind::APValue:
390 if (!ConstantExprBits.HasCleanup && Value.needsCleanup()) {
391 ConstantExprBits.HasCleanup = true;
392 Context.addDestruction(&APValueResult());
393 }
394 APValueResult() = std::move(Value);
395 return;
396 }
397 llvm_unreachable("Invalid ResultKind Bits");
398 }
399
getResultAsAPSInt() const400 llvm::APSInt ConstantExpr::getResultAsAPSInt() const {
401 switch (getResultStorageKind()) {
402 case ConstantResultStorageKind::APValue:
403 return APValueResult().getInt();
404 case ConstantResultStorageKind::Int64:
405 return llvm::APSInt(llvm::APInt(ConstantExprBits.BitWidth, Int64Result()),
406 ConstantExprBits.IsUnsigned);
407 default:
408 llvm_unreachable("invalid Accessor");
409 }
410 }
411
getAPValueResult() const412 APValue ConstantExpr::getAPValueResult() const {
413
414 switch (getResultStorageKind()) {
415 case ConstantResultStorageKind::APValue:
416 return APValueResult();
417 case ConstantResultStorageKind::Int64:
418 return APValue(
419 llvm::APSInt(llvm::APInt(ConstantExprBits.BitWidth, Int64Result()),
420 ConstantExprBits.IsUnsigned));
421 case ConstantResultStorageKind::None:
422 if (ConstantExprBits.APValueKind == APValue::Indeterminate)
423 return APValue::IndeterminateValue();
424 return APValue();
425 }
426 llvm_unreachable("invalid ResultKind");
427 }
428
DeclRefExpr(const ASTContext & Ctx,ValueDecl * D,bool RefersToEnclosingVariableOrCapture,QualType T,ExprValueKind VK,SourceLocation L,const DeclarationNameLoc & LocInfo,NonOdrUseReason NOUR)429 DeclRefExpr::DeclRefExpr(const ASTContext &Ctx, ValueDecl *D,
430 bool RefersToEnclosingVariableOrCapture, QualType T,
431 ExprValueKind VK, SourceLocation L,
432 const DeclarationNameLoc &LocInfo,
433 NonOdrUseReason NOUR)
434 : Expr(DeclRefExprClass, T, VK, OK_Ordinary), D(D), DNLoc(LocInfo) {
435 DeclRefExprBits.HasQualifier = false;
436 DeclRefExprBits.HasTemplateKWAndArgsInfo = false;
437 DeclRefExprBits.HasFoundDecl = false;
438 DeclRefExprBits.HadMultipleCandidates = false;
439 DeclRefExprBits.RefersToEnclosingVariableOrCapture =
440 RefersToEnclosingVariableOrCapture;
441 DeclRefExprBits.CapturedByCopyInLambdaWithExplicitObjectParameter = false;
442 DeclRefExprBits.NonOdrUseReason = NOUR;
443 DeclRefExprBits.IsImmediateEscalating = false;
444 DeclRefExprBits.Loc = L;
445 setDependence(computeDependence(this, Ctx));
446 }
447
DeclRefExpr(const ASTContext & Ctx,NestedNameSpecifierLoc QualifierLoc,SourceLocation TemplateKWLoc,ValueDecl * D,bool RefersToEnclosingVariableOrCapture,const DeclarationNameInfo & NameInfo,NamedDecl * FoundD,const TemplateArgumentListInfo * TemplateArgs,QualType T,ExprValueKind VK,NonOdrUseReason NOUR)448 DeclRefExpr::DeclRefExpr(const ASTContext &Ctx,
449 NestedNameSpecifierLoc QualifierLoc,
450 SourceLocation TemplateKWLoc, ValueDecl *D,
451 bool RefersToEnclosingVariableOrCapture,
452 const DeclarationNameInfo &NameInfo, NamedDecl *FoundD,
453 const TemplateArgumentListInfo *TemplateArgs,
454 QualType T, ExprValueKind VK, NonOdrUseReason NOUR)
455 : Expr(DeclRefExprClass, T, VK, OK_Ordinary), D(D),
456 DNLoc(NameInfo.getInfo()) {
457 DeclRefExprBits.Loc = NameInfo.getLoc();
458 DeclRefExprBits.HasQualifier = QualifierLoc ? 1 : 0;
459 if (QualifierLoc)
460 new (getTrailingObjects<NestedNameSpecifierLoc>())
461 NestedNameSpecifierLoc(QualifierLoc);
462 DeclRefExprBits.HasFoundDecl = FoundD ? 1 : 0;
463 if (FoundD)
464 *getTrailingObjects<NamedDecl *>() = FoundD;
465 DeclRefExprBits.HasTemplateKWAndArgsInfo
466 = (TemplateArgs || TemplateKWLoc.isValid()) ? 1 : 0;
467 DeclRefExprBits.RefersToEnclosingVariableOrCapture =
468 RefersToEnclosingVariableOrCapture;
469 DeclRefExprBits.CapturedByCopyInLambdaWithExplicitObjectParameter = false;
470 DeclRefExprBits.NonOdrUseReason = NOUR;
471 if (TemplateArgs) {
472 auto Deps = TemplateArgumentDependence::None;
473 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
474 TemplateKWLoc, *TemplateArgs, getTrailingObjects<TemplateArgumentLoc>(),
475 Deps);
476 assert(!(Deps & TemplateArgumentDependence::Dependent) &&
477 "built a DeclRefExpr with dependent template args");
478 } else if (TemplateKWLoc.isValid()) {
479 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
480 TemplateKWLoc);
481 }
482 DeclRefExprBits.IsImmediateEscalating = false;
483 DeclRefExprBits.HadMultipleCandidates = 0;
484 setDependence(computeDependence(this, Ctx));
485 }
486
Create(const ASTContext & Context,NestedNameSpecifierLoc QualifierLoc,SourceLocation TemplateKWLoc,ValueDecl * D,bool RefersToEnclosingVariableOrCapture,SourceLocation NameLoc,QualType T,ExprValueKind VK,NamedDecl * FoundD,const TemplateArgumentListInfo * TemplateArgs,NonOdrUseReason NOUR)487 DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,
488 NestedNameSpecifierLoc QualifierLoc,
489 SourceLocation TemplateKWLoc, ValueDecl *D,
490 bool RefersToEnclosingVariableOrCapture,
491 SourceLocation NameLoc, QualType T,
492 ExprValueKind VK, NamedDecl *FoundD,
493 const TemplateArgumentListInfo *TemplateArgs,
494 NonOdrUseReason NOUR) {
495 return Create(Context, QualifierLoc, TemplateKWLoc, D,
496 RefersToEnclosingVariableOrCapture,
497 DeclarationNameInfo(D->getDeclName(), NameLoc),
498 T, VK, FoundD, TemplateArgs, NOUR);
499 }
500
Create(const ASTContext & Context,NestedNameSpecifierLoc QualifierLoc,SourceLocation TemplateKWLoc,ValueDecl * D,bool RefersToEnclosingVariableOrCapture,const DeclarationNameInfo & NameInfo,QualType T,ExprValueKind VK,NamedDecl * FoundD,const TemplateArgumentListInfo * TemplateArgs,NonOdrUseReason NOUR)501 DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,
502 NestedNameSpecifierLoc QualifierLoc,
503 SourceLocation TemplateKWLoc, ValueDecl *D,
504 bool RefersToEnclosingVariableOrCapture,
505 const DeclarationNameInfo &NameInfo,
506 QualType T, ExprValueKind VK,
507 NamedDecl *FoundD,
508 const TemplateArgumentListInfo *TemplateArgs,
509 NonOdrUseReason NOUR) {
510 // Filter out cases where the found Decl is the same as the value refenenced.
511 if (D == FoundD)
512 FoundD = nullptr;
513
514 bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
515 std::size_t Size =
516 totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
517 ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
518 QualifierLoc ? 1 : 0, FoundD ? 1 : 0,
519 HasTemplateKWAndArgsInfo ? 1 : 0,
520 TemplateArgs ? TemplateArgs->size() : 0);
521
522 void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));
523 return new (Mem) DeclRefExpr(Context, QualifierLoc, TemplateKWLoc, D,
524 RefersToEnclosingVariableOrCapture, NameInfo,
525 FoundD, TemplateArgs, T, VK, NOUR);
526 }
527
CreateEmpty(const ASTContext & Context,bool HasQualifier,bool HasFoundDecl,bool HasTemplateKWAndArgsInfo,unsigned NumTemplateArgs)528 DeclRefExpr *DeclRefExpr::CreateEmpty(const ASTContext &Context,
529 bool HasQualifier,
530 bool HasFoundDecl,
531 bool HasTemplateKWAndArgsInfo,
532 unsigned NumTemplateArgs) {
533 assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo);
534 std::size_t Size =
535 totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
536 ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
537 HasQualifier ? 1 : 0, HasFoundDecl ? 1 : 0, HasTemplateKWAndArgsInfo,
538 NumTemplateArgs);
539 void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));
540 return new (Mem) DeclRefExpr(EmptyShell());
541 }
542
setDecl(ValueDecl * NewD)543 void DeclRefExpr::setDecl(ValueDecl *NewD) {
544 D = NewD;
545 if (getType()->isUndeducedType())
546 setType(NewD->getType());
547 setDependence(computeDependence(this, NewD->getASTContext()));
548 }
549
getEndLoc() const550 SourceLocation DeclRefExpr::getEndLoc() const {
551 if (hasExplicitTemplateArgs())
552 return getRAngleLoc();
553 return getNameInfo().getEndLoc();
554 }
555
SYCLUniqueStableNameExpr(SourceLocation OpLoc,SourceLocation LParen,SourceLocation RParen,QualType ResultTy,TypeSourceInfo * TSI)556 SYCLUniqueStableNameExpr::SYCLUniqueStableNameExpr(SourceLocation OpLoc,
557 SourceLocation LParen,
558 SourceLocation RParen,
559 QualType ResultTy,
560 TypeSourceInfo *TSI)
561 : Expr(SYCLUniqueStableNameExprClass, ResultTy, VK_PRValue, OK_Ordinary),
562 OpLoc(OpLoc), LParen(LParen), RParen(RParen) {
563 setTypeSourceInfo(TSI);
564 setDependence(computeDependence(this));
565 }
566
SYCLUniqueStableNameExpr(EmptyShell Empty,QualType ResultTy)567 SYCLUniqueStableNameExpr::SYCLUniqueStableNameExpr(EmptyShell Empty,
568 QualType ResultTy)
569 : Expr(SYCLUniqueStableNameExprClass, ResultTy, VK_PRValue, OK_Ordinary) {}
570
571 SYCLUniqueStableNameExpr *
Create(const ASTContext & Ctx,SourceLocation OpLoc,SourceLocation LParen,SourceLocation RParen,TypeSourceInfo * TSI)572 SYCLUniqueStableNameExpr::Create(const ASTContext &Ctx, SourceLocation OpLoc,
573 SourceLocation LParen, SourceLocation RParen,
574 TypeSourceInfo *TSI) {
575 QualType ResultTy = Ctx.getPointerType(Ctx.CharTy.withConst());
576 return new (Ctx)
577 SYCLUniqueStableNameExpr(OpLoc, LParen, RParen, ResultTy, TSI);
578 }
579
580 SYCLUniqueStableNameExpr *
CreateEmpty(const ASTContext & Ctx)581 SYCLUniqueStableNameExpr::CreateEmpty(const ASTContext &Ctx) {
582 QualType ResultTy = Ctx.getPointerType(Ctx.CharTy.withConst());
583 return new (Ctx) SYCLUniqueStableNameExpr(EmptyShell(), ResultTy);
584 }
585
ComputeName(ASTContext & Context) const586 std::string SYCLUniqueStableNameExpr::ComputeName(ASTContext &Context) const {
587 return SYCLUniqueStableNameExpr::ComputeName(Context,
588 getTypeSourceInfo()->getType());
589 }
590
ComputeName(ASTContext & Context,QualType Ty)591 std::string SYCLUniqueStableNameExpr::ComputeName(ASTContext &Context,
592 QualType Ty) {
593 auto MangleCallback = [](ASTContext &Ctx,
594 const NamedDecl *ND) -> UnsignedOrNone {
595 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
596 return RD->getDeviceLambdaManglingNumber();
597 return std::nullopt;
598 };
599
600 std::unique_ptr<MangleContext> Ctx{ItaniumMangleContext::create(
601 Context, Context.getDiagnostics(), MangleCallback)};
602
603 std::string Buffer;
604 Buffer.reserve(128);
605 llvm::raw_string_ostream Out(Buffer);
606 Ctx->mangleCanonicalTypeName(Ty, Out);
607
608 return Buffer;
609 }
610
PredefinedExpr(SourceLocation L,QualType FNTy,PredefinedIdentKind IK,bool IsTransparent,StringLiteral * SL)611 PredefinedExpr::PredefinedExpr(SourceLocation L, QualType FNTy,
612 PredefinedIdentKind IK, bool IsTransparent,
613 StringLiteral *SL)
614 : Expr(PredefinedExprClass, FNTy, VK_LValue, OK_Ordinary) {
615 PredefinedExprBits.Kind = llvm::to_underlying(IK);
616 assert((getIdentKind() == IK) &&
617 "IdentKind do not fit in PredefinedExprBitfields!");
618 bool HasFunctionName = SL != nullptr;
619 PredefinedExprBits.HasFunctionName = HasFunctionName;
620 PredefinedExprBits.IsTransparent = IsTransparent;
621 PredefinedExprBits.Loc = L;
622 if (HasFunctionName)
623 setFunctionName(SL);
624 setDependence(computeDependence(this));
625 }
626
PredefinedExpr(EmptyShell Empty,bool HasFunctionName)627 PredefinedExpr::PredefinedExpr(EmptyShell Empty, bool HasFunctionName)
628 : Expr(PredefinedExprClass, Empty) {
629 PredefinedExprBits.HasFunctionName = HasFunctionName;
630 }
631
Create(const ASTContext & Ctx,SourceLocation L,QualType FNTy,PredefinedIdentKind IK,bool IsTransparent,StringLiteral * SL)632 PredefinedExpr *PredefinedExpr::Create(const ASTContext &Ctx, SourceLocation L,
633 QualType FNTy, PredefinedIdentKind IK,
634 bool IsTransparent, StringLiteral *SL) {
635 bool HasFunctionName = SL != nullptr;
636 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(HasFunctionName),
637 alignof(PredefinedExpr));
638 return new (Mem) PredefinedExpr(L, FNTy, IK, IsTransparent, SL);
639 }
640
CreateEmpty(const ASTContext & Ctx,bool HasFunctionName)641 PredefinedExpr *PredefinedExpr::CreateEmpty(const ASTContext &Ctx,
642 bool HasFunctionName) {
643 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(HasFunctionName),
644 alignof(PredefinedExpr));
645 return new (Mem) PredefinedExpr(EmptyShell(), HasFunctionName);
646 }
647
getIdentKindName(PredefinedIdentKind IK)648 StringRef PredefinedExpr::getIdentKindName(PredefinedIdentKind IK) {
649 switch (IK) {
650 case PredefinedIdentKind::Func:
651 return "__func__";
652 case PredefinedIdentKind::Function:
653 return "__FUNCTION__";
654 case PredefinedIdentKind::FuncDName:
655 return "__FUNCDNAME__";
656 case PredefinedIdentKind::LFunction:
657 return "L__FUNCTION__";
658 case PredefinedIdentKind::PrettyFunction:
659 return "__PRETTY_FUNCTION__";
660 case PredefinedIdentKind::FuncSig:
661 return "__FUNCSIG__";
662 case PredefinedIdentKind::LFuncSig:
663 return "L__FUNCSIG__";
664 case PredefinedIdentKind::PrettyFunctionNoVirtual:
665 break;
666 }
667 llvm_unreachable("Unknown ident kind for PredefinedExpr");
668 }
669
670 // FIXME: Maybe this should use DeclPrinter with a special "print predefined
671 // expr" policy instead.
ComputeName(PredefinedIdentKind IK,const Decl * CurrentDecl,bool ForceElaboratedPrinting)672 std::string PredefinedExpr::ComputeName(PredefinedIdentKind IK,
673 const Decl *CurrentDecl,
674 bool ForceElaboratedPrinting) {
675 ASTContext &Context = CurrentDecl->getASTContext();
676
677 if (IK == PredefinedIdentKind::FuncDName) {
678 if (const NamedDecl *ND = dyn_cast<NamedDecl>(CurrentDecl)) {
679 std::unique_ptr<MangleContext> MC;
680 MC.reset(Context.createMangleContext());
681
682 if (MC->shouldMangleDeclName(ND)) {
683 SmallString<256> Buffer;
684 llvm::raw_svector_ostream Out(Buffer);
685 GlobalDecl GD;
686 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(ND))
687 GD = GlobalDecl(CD, Ctor_Base);
688 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(ND))
689 GD = GlobalDecl(DD, Dtor_Base);
690 else if (auto FD = dyn_cast<FunctionDecl>(ND)) {
691 GD = FD->isReferenceableKernel() ? GlobalDecl(FD) : GlobalDecl(ND);
692 } else
693 GD = GlobalDecl(ND);
694 MC->mangleName(GD, Out);
695
696 if (!Buffer.empty() && Buffer.front() == '\01')
697 return std::string(Buffer.substr(1));
698 return std::string(Buffer);
699 }
700 return std::string(ND->getIdentifier()->getName());
701 }
702 return "";
703 }
704 if (isa<BlockDecl>(CurrentDecl)) {
705 // For blocks we only emit something if it is enclosed in a function
706 // For top-level block we'd like to include the name of variable, but we
707 // don't have it at this point.
708 auto DC = CurrentDecl->getDeclContext();
709 if (DC->isFileContext())
710 return "";
711
712 SmallString<256> Buffer;
713 llvm::raw_svector_ostream Out(Buffer);
714 if (auto *DCBlock = dyn_cast<BlockDecl>(DC))
715 // For nested blocks, propagate up to the parent.
716 Out << ComputeName(IK, DCBlock);
717 else if (auto *DCDecl = dyn_cast<Decl>(DC))
718 Out << ComputeName(IK, DCDecl) << "_block_invoke";
719 return std::string(Out.str());
720 }
721 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurrentDecl)) {
722 const auto &LO = Context.getLangOpts();
723 bool IsFuncOrFunctionInNonMSVCCompatEnv =
724 ((IK == PredefinedIdentKind::Func ||
725 IK == PredefinedIdentKind ::Function) &&
726 !LO.MSVCCompat);
727 bool IsLFunctionInMSVCCommpatEnv =
728 IK == PredefinedIdentKind::LFunction && LO.MSVCCompat;
729 bool IsFuncOrFunctionOrLFunctionOrFuncDName =
730 IK != PredefinedIdentKind::PrettyFunction &&
731 IK != PredefinedIdentKind::PrettyFunctionNoVirtual &&
732 IK != PredefinedIdentKind::FuncSig &&
733 IK != PredefinedIdentKind::LFuncSig;
734 if ((ForceElaboratedPrinting &&
735 (IsFuncOrFunctionInNonMSVCCompatEnv || IsLFunctionInMSVCCommpatEnv)) ||
736 (!ForceElaboratedPrinting && IsFuncOrFunctionOrLFunctionOrFuncDName))
737 return FD->getNameAsString();
738
739 SmallString<256> Name;
740 llvm::raw_svector_ostream Out(Name);
741
742 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
743 if (MD->isVirtual() && IK != PredefinedIdentKind::PrettyFunctionNoVirtual)
744 Out << "virtual ";
745 if (MD->isStatic() && !ForceElaboratedPrinting)
746 Out << "static ";
747 }
748
749 class PrettyCallbacks final : public PrintingCallbacks {
750 public:
751 PrettyCallbacks(const LangOptions &LO) : LO(LO) {}
752 std::string remapPath(StringRef Path) const override {
753 SmallString<128> p(Path);
754 LO.remapPathPrefix(p);
755 return std::string(p);
756 }
757
758 private:
759 const LangOptions &LO;
760 };
761 PrintingPolicy Policy(Context.getLangOpts());
762 PrettyCallbacks PrettyCB(Context.getLangOpts());
763 Policy.Callbacks = &PrettyCB;
764 if (IK == PredefinedIdentKind::Function && ForceElaboratedPrinting)
765 Policy.SuppressTagKeyword = !LO.MSVCCompat;
766 std::string Proto;
767 llvm::raw_string_ostream POut(Proto);
768
769 const FunctionDecl *Decl = FD;
770 if (const FunctionDecl* Pattern = FD->getTemplateInstantiationPattern())
771 Decl = Pattern;
772
773 // Bail out if the type of the function has not been set yet.
774 // This can notably happen in the trailing return type of a lambda
775 // expression.
776 const Type *Ty = Decl->getType().getTypePtrOrNull();
777 if (!Ty)
778 return "";
779
780 const FunctionType *AFT = Ty->getAs<FunctionType>();
781 const FunctionProtoType *FT = nullptr;
782 if (FD->hasWrittenPrototype())
783 FT = dyn_cast<FunctionProtoType>(AFT);
784
785 if (IK == PredefinedIdentKind::FuncSig ||
786 IK == PredefinedIdentKind::LFuncSig) {
787 switch (AFT->getCallConv()) {
788 case CC_C: POut << "__cdecl "; break;
789 case CC_X86StdCall: POut << "__stdcall "; break;
790 case CC_X86FastCall: POut << "__fastcall "; break;
791 case CC_X86ThisCall: POut << "__thiscall "; break;
792 case CC_X86VectorCall: POut << "__vectorcall "; break;
793 case CC_X86RegCall: POut << "__regcall "; break;
794 // Only bother printing the conventions that MSVC knows about.
795 default: break;
796 }
797 }
798
799 FD->printQualifiedName(POut, Policy);
800
801 if (IK == PredefinedIdentKind::Function) {
802 Out << Proto;
803 return std::string(Name);
804 }
805
806 POut << "(";
807 if (FT) {
808 for (unsigned i = 0, e = Decl->getNumParams(); i != e; ++i) {
809 if (i) POut << ", ";
810 POut << Decl->getParamDecl(i)->getType().stream(Policy);
811 }
812
813 if (FT->isVariadic()) {
814 if (FD->getNumParams()) POut << ", ";
815 POut << "...";
816 } else if ((IK == PredefinedIdentKind::FuncSig ||
817 IK == PredefinedIdentKind::LFuncSig ||
818 !Context.getLangOpts().CPlusPlus) &&
819 !Decl->getNumParams()) {
820 POut << "void";
821 }
822 }
823 POut << ")";
824
825 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
826 assert(FT && "We must have a written prototype in this case.");
827 if (FT->isConst())
828 POut << " const";
829 if (FT->isVolatile())
830 POut << " volatile";
831 RefQualifierKind Ref = MD->getRefQualifier();
832 if (Ref == RQ_LValue)
833 POut << " &";
834 else if (Ref == RQ_RValue)
835 POut << " &&";
836 }
837
838 typedef SmallVector<const ClassTemplateSpecializationDecl *, 8> SpecsTy;
839 SpecsTy Specs;
840 const DeclContext *Ctx = FD->getDeclContext();
841 while (isa_and_nonnull<NamedDecl>(Ctx)) {
842 const ClassTemplateSpecializationDecl *Spec
843 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx);
844 if (Spec && !Spec->isExplicitSpecialization())
845 Specs.push_back(Spec);
846 Ctx = Ctx->getParent();
847 }
848
849 std::string TemplateParams;
850 llvm::raw_string_ostream TOut(TemplateParams);
851 for (const ClassTemplateSpecializationDecl *D : llvm::reverse(Specs)) {
852 const TemplateParameterList *Params =
853 D->getSpecializedTemplate()->getTemplateParameters();
854 const TemplateArgumentList &Args = D->getTemplateArgs();
855 assert(Params->size() == Args.size());
856 for (unsigned i = 0, numParams = Params->size(); i != numParams; ++i) {
857 StringRef Param = Params->getParam(i)->getName();
858 if (Param.empty()) continue;
859 TOut << Param << " = ";
860 Args.get(i).print(Policy, TOut,
861 TemplateParameterList::shouldIncludeTypeForArgument(
862 Policy, Params, i));
863 TOut << ", ";
864 }
865 }
866
867 FunctionTemplateSpecializationInfo *FSI
868 = FD->getTemplateSpecializationInfo();
869 if (FSI && !FSI->isExplicitSpecialization()) {
870 const TemplateParameterList* Params
871 = FSI->getTemplate()->getTemplateParameters();
872 const TemplateArgumentList* Args = FSI->TemplateArguments;
873 assert(Params->size() == Args->size());
874 for (unsigned i = 0, e = Params->size(); i != e; ++i) {
875 StringRef Param = Params->getParam(i)->getName();
876 if (Param.empty()) continue;
877 TOut << Param << " = ";
878 Args->get(i).print(Policy, TOut, /*IncludeType*/ true);
879 TOut << ", ";
880 }
881 }
882
883 if (!TemplateParams.empty()) {
884 // remove the trailing comma and space
885 TemplateParams.resize(TemplateParams.size() - 2);
886 POut << " [" << TemplateParams << "]";
887 }
888
889 // Print "auto" for all deduced return types. This includes C++1y return
890 // type deduction and lambdas. For trailing return types resolve the
891 // decltype expression. Otherwise print the real type when this is
892 // not a constructor or destructor.
893 if (isLambdaMethod(FD))
894 Proto = "auto " + Proto;
895 else if (FT && FT->getReturnType()->getAs<DecltypeType>())
896 FT->getReturnType()
897 ->getAs<DecltypeType>()
898 ->getUnderlyingType()
899 .getAsStringInternal(Proto, Policy);
900 else if (!isa<CXXConstructorDecl>(FD) && !isa<CXXDestructorDecl>(FD))
901 AFT->getReturnType().getAsStringInternal(Proto, Policy);
902
903 Out << Proto;
904
905 return std::string(Name);
906 }
907 if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(CurrentDecl)) {
908 for (const DeclContext *DC = CD->getParent(); DC; DC = DC->getParent())
909 // Skip to its enclosing function or method, but not its enclosing
910 // CapturedDecl.
911 if (DC->isFunctionOrMethod() && (DC->getDeclKind() != Decl::Captured)) {
912 const Decl *D = Decl::castFromDeclContext(DC);
913 return ComputeName(IK, D);
914 }
915 llvm_unreachable("CapturedDecl not inside a function or method");
916 }
917 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurrentDecl)) {
918 SmallString<256> Name;
919 llvm::raw_svector_ostream Out(Name);
920 Out << (MD->isInstanceMethod() ? '-' : '+');
921 Out << '[';
922
923 // For incorrect code, there might not be an ObjCInterfaceDecl. Do
924 // a null check to avoid a crash.
925 if (const ObjCInterfaceDecl *ID = MD->getClassInterface())
926 Out << *ID;
927
928 if (const ObjCCategoryImplDecl *CID =
929 dyn_cast<ObjCCategoryImplDecl>(MD->getDeclContext()))
930 Out << '(' << *CID << ')';
931
932 Out << ' ';
933 MD->getSelector().print(Out);
934 Out << ']';
935
936 return std::string(Name);
937 }
938 if (isa<TranslationUnitDecl>(CurrentDecl) &&
939 IK == PredefinedIdentKind::PrettyFunction) {
940 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
941 return "top level";
942 }
943 return "";
944 }
945
setIntValue(const ASTContext & C,const llvm::APInt & Val)946 void APNumericStorage::setIntValue(const ASTContext &C,
947 const llvm::APInt &Val) {
948 if (hasAllocation())
949 C.Deallocate(pVal);
950
951 BitWidth = Val.getBitWidth();
952 unsigned NumWords = Val.getNumWords();
953 const uint64_t* Words = Val.getRawData();
954 if (NumWords > 1) {
955 pVal = new (C) uint64_t[NumWords];
956 std::copy(Words, Words + NumWords, pVal);
957 } else if (NumWords == 1)
958 VAL = Words[0];
959 else
960 VAL = 0;
961 }
962
IntegerLiteral(const ASTContext & C,const llvm::APInt & V,QualType type,SourceLocation l)963 IntegerLiteral::IntegerLiteral(const ASTContext &C, const llvm::APInt &V,
964 QualType type, SourceLocation l)
965 : Expr(IntegerLiteralClass, type, VK_PRValue, OK_Ordinary), Loc(l) {
966 assert(type->isIntegerType() && "Illegal type in IntegerLiteral");
967 assert(V.getBitWidth() == C.getIntWidth(type) &&
968 "Integer type is not the correct size for constant.");
969 setValue(C, V);
970 setDependence(ExprDependence::None);
971 }
972
973 IntegerLiteral *
Create(const ASTContext & C,const llvm::APInt & V,QualType type,SourceLocation l)974 IntegerLiteral::Create(const ASTContext &C, const llvm::APInt &V,
975 QualType type, SourceLocation l) {
976 return new (C) IntegerLiteral(C, V, type, l);
977 }
978
979 IntegerLiteral *
Create(const ASTContext & C,EmptyShell Empty)980 IntegerLiteral::Create(const ASTContext &C, EmptyShell Empty) {
981 return new (C) IntegerLiteral(Empty);
982 }
983
FixedPointLiteral(const ASTContext & C,const llvm::APInt & V,QualType type,SourceLocation l,unsigned Scale)984 FixedPointLiteral::FixedPointLiteral(const ASTContext &C, const llvm::APInt &V,
985 QualType type, SourceLocation l,
986 unsigned Scale)
987 : Expr(FixedPointLiteralClass, type, VK_PRValue, OK_Ordinary), Loc(l),
988 Scale(Scale) {
989 assert(type->isFixedPointType() && "Illegal type in FixedPointLiteral");
990 assert(V.getBitWidth() == C.getTypeInfo(type).Width &&
991 "Fixed point type is not the correct size for constant.");
992 setValue(C, V);
993 setDependence(ExprDependence::None);
994 }
995
CreateFromRawInt(const ASTContext & C,const llvm::APInt & V,QualType type,SourceLocation l,unsigned Scale)996 FixedPointLiteral *FixedPointLiteral::CreateFromRawInt(const ASTContext &C,
997 const llvm::APInt &V,
998 QualType type,
999 SourceLocation l,
1000 unsigned Scale) {
1001 return new (C) FixedPointLiteral(C, V, type, l, Scale);
1002 }
1003
Create(const ASTContext & C,EmptyShell Empty)1004 FixedPointLiteral *FixedPointLiteral::Create(const ASTContext &C,
1005 EmptyShell Empty) {
1006 return new (C) FixedPointLiteral(Empty);
1007 }
1008
getValueAsString(unsigned Radix) const1009 std::string FixedPointLiteral::getValueAsString(unsigned Radix) const {
1010 // Currently the longest decimal number that can be printed is the max for an
1011 // unsigned long _Accum: 4294967295.99999999976716935634613037109375
1012 // which is 43 characters.
1013 SmallString<64> S;
1014 FixedPointValueToString(
1015 S, llvm::APSInt::getUnsigned(getValue().getZExtValue()), Scale);
1016 return std::string(S);
1017 }
1018
print(unsigned Val,CharacterLiteralKind Kind,raw_ostream & OS)1019 void CharacterLiteral::print(unsigned Val, CharacterLiteralKind Kind,
1020 raw_ostream &OS) {
1021 switch (Kind) {
1022 case CharacterLiteralKind::Ascii:
1023 break; // no prefix.
1024 case CharacterLiteralKind::Wide:
1025 OS << 'L';
1026 break;
1027 case CharacterLiteralKind::UTF8:
1028 OS << "u8";
1029 break;
1030 case CharacterLiteralKind::UTF16:
1031 OS << 'u';
1032 break;
1033 case CharacterLiteralKind::UTF32:
1034 OS << 'U';
1035 break;
1036 }
1037
1038 StringRef Escaped = escapeCStyle<EscapeChar::Single>(Val);
1039 if (!Escaped.empty()) {
1040 OS << "'" << Escaped << "'";
1041 } else {
1042 // A character literal might be sign-extended, which
1043 // would result in an invalid \U escape sequence.
1044 // FIXME: multicharacter literals such as '\xFF\xFF\xFF\xFF'
1045 // are not correctly handled.
1046 if ((Val & ~0xFFu) == ~0xFFu && Kind == CharacterLiteralKind::Ascii)
1047 Val &= 0xFFu;
1048 if (Val < 256 && isPrintable((unsigned char)Val))
1049 OS << "'" << (char)Val << "'";
1050 else if (Val < 256)
1051 OS << "'\\x" << llvm::format("%02x", Val) << "'";
1052 else if (Val <= 0xFFFF)
1053 OS << "'\\u" << llvm::format("%04x", Val) << "'";
1054 else
1055 OS << "'\\U" << llvm::format("%08x", Val) << "'";
1056 }
1057 }
1058
FloatingLiteral(const ASTContext & C,const llvm::APFloat & V,bool isexact,QualType Type,SourceLocation L)1059 FloatingLiteral::FloatingLiteral(const ASTContext &C, const llvm::APFloat &V,
1060 bool isexact, QualType Type, SourceLocation L)
1061 : Expr(FloatingLiteralClass, Type, VK_PRValue, OK_Ordinary), Loc(L) {
1062 setSemantics(V.getSemantics());
1063 FloatingLiteralBits.IsExact = isexact;
1064 setValue(C, V);
1065 setDependence(ExprDependence::None);
1066 }
1067
FloatingLiteral(const ASTContext & C,EmptyShell Empty)1068 FloatingLiteral::FloatingLiteral(const ASTContext &C, EmptyShell Empty)
1069 : Expr(FloatingLiteralClass, Empty) {
1070 setRawSemantics(llvm::APFloatBase::S_IEEEhalf);
1071 FloatingLiteralBits.IsExact = false;
1072 }
1073
1074 FloatingLiteral *
Create(const ASTContext & C,const llvm::APFloat & V,bool isexact,QualType Type,SourceLocation L)1075 FloatingLiteral::Create(const ASTContext &C, const llvm::APFloat &V,
1076 bool isexact, QualType Type, SourceLocation L) {
1077 return new (C) FloatingLiteral(C, V, isexact, Type, L);
1078 }
1079
1080 FloatingLiteral *
Create(const ASTContext & C,EmptyShell Empty)1081 FloatingLiteral::Create(const ASTContext &C, EmptyShell Empty) {
1082 return new (C) FloatingLiteral(C, Empty);
1083 }
1084
1085 /// getValueAsApproximateDouble - This returns the value as an inaccurate
1086 /// double. Note that this may cause loss of precision, but is useful for
1087 /// debugging dumps, etc.
getValueAsApproximateDouble() const1088 double FloatingLiteral::getValueAsApproximateDouble() const {
1089 llvm::APFloat V = getValue();
1090 bool ignored;
1091 V.convert(llvm::APFloat::IEEEdouble(), llvm::APFloat::rmNearestTiesToEven,
1092 &ignored);
1093 return V.convertToDouble();
1094 }
1095
mapCharByteWidth(TargetInfo const & Target,StringLiteralKind SK)1096 unsigned StringLiteral::mapCharByteWidth(TargetInfo const &Target,
1097 StringLiteralKind SK) {
1098 unsigned CharByteWidth = 0;
1099 switch (SK) {
1100 case StringLiteralKind::Ordinary:
1101 case StringLiteralKind::UTF8:
1102 case StringLiteralKind::Binary:
1103 CharByteWidth = Target.getCharWidth();
1104 break;
1105 case StringLiteralKind::Wide:
1106 CharByteWidth = Target.getWCharWidth();
1107 break;
1108 case StringLiteralKind::UTF16:
1109 CharByteWidth = Target.getChar16Width();
1110 break;
1111 case StringLiteralKind::UTF32:
1112 CharByteWidth = Target.getChar32Width();
1113 break;
1114 case StringLiteralKind::Unevaluated:
1115 return sizeof(char); // Host;
1116 }
1117 assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
1118 CharByteWidth /= 8;
1119 assert((CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth == 4) &&
1120 "The only supported character byte widths are 1,2 and 4!");
1121 return CharByteWidth;
1122 }
1123
StringLiteral(const ASTContext & Ctx,StringRef Str,StringLiteralKind Kind,bool Pascal,QualType Ty,ArrayRef<SourceLocation> Locs)1124 StringLiteral::StringLiteral(const ASTContext &Ctx, StringRef Str,
1125 StringLiteralKind Kind, bool Pascal, QualType Ty,
1126 ArrayRef<SourceLocation> Locs)
1127 : Expr(StringLiteralClass, Ty, VK_LValue, OK_Ordinary) {
1128
1129 unsigned Length = Str.size();
1130
1131 StringLiteralBits.Kind = llvm::to_underlying(Kind);
1132 StringLiteralBits.NumConcatenated = Locs.size();
1133
1134 if (Kind != StringLiteralKind::Unevaluated) {
1135 assert(Ctx.getAsConstantArrayType(Ty) &&
1136 "StringLiteral must be of constant array type!");
1137 unsigned CharByteWidth = mapCharByteWidth(Ctx.getTargetInfo(), Kind);
1138 unsigned ByteLength = Str.size();
1139 assert((ByteLength % CharByteWidth == 0) &&
1140 "The size of the data must be a multiple of CharByteWidth!");
1141
1142 // Avoid the expensive division. The compiler should be able to figure it
1143 // out by itself. However as of clang 7, even with the appropriate
1144 // llvm_unreachable added just here, it is not able to do so.
1145 switch (CharByteWidth) {
1146 case 1:
1147 Length = ByteLength;
1148 break;
1149 case 2:
1150 Length = ByteLength / 2;
1151 break;
1152 case 4:
1153 Length = ByteLength / 4;
1154 break;
1155 default:
1156 llvm_unreachable("Unsupported character width!");
1157 }
1158
1159 StringLiteralBits.CharByteWidth = CharByteWidth;
1160 StringLiteralBits.IsPascal = Pascal;
1161 } else {
1162 assert(!Pascal && "Can't make an unevaluated Pascal string");
1163 StringLiteralBits.CharByteWidth = 1;
1164 StringLiteralBits.IsPascal = false;
1165 }
1166
1167 *getTrailingObjects<unsigned>() = Length;
1168
1169 // Initialize the trailing array of SourceLocation.
1170 // This is safe since SourceLocation is POD-like.
1171 llvm::copy(Locs, getTrailingObjects<SourceLocation>());
1172
1173 // Initialize the trailing array of char holding the string data.
1174 llvm::copy(Str, getTrailingObjects<char>());
1175
1176 setDependence(ExprDependence::None);
1177 }
1178
StringLiteral(EmptyShell Empty,unsigned NumConcatenated,unsigned Length,unsigned CharByteWidth)1179 StringLiteral::StringLiteral(EmptyShell Empty, unsigned NumConcatenated,
1180 unsigned Length, unsigned CharByteWidth)
1181 : Expr(StringLiteralClass, Empty) {
1182 StringLiteralBits.CharByteWidth = CharByteWidth;
1183 StringLiteralBits.NumConcatenated = NumConcatenated;
1184 *getTrailingObjects<unsigned>() = Length;
1185 }
1186
Create(const ASTContext & Ctx,StringRef Str,StringLiteralKind Kind,bool Pascal,QualType Ty,ArrayRef<SourceLocation> Locs)1187 StringLiteral *StringLiteral::Create(const ASTContext &Ctx, StringRef Str,
1188 StringLiteralKind Kind, bool Pascal,
1189 QualType Ty,
1190 ArrayRef<SourceLocation> Locs) {
1191 void *Mem = Ctx.Allocate(totalSizeToAlloc<unsigned, SourceLocation, char>(
1192 1, Locs.size(), Str.size()),
1193 alignof(StringLiteral));
1194 return new (Mem) StringLiteral(Ctx, Str, Kind, Pascal, Ty, Locs);
1195 }
1196
CreateEmpty(const ASTContext & Ctx,unsigned NumConcatenated,unsigned Length,unsigned CharByteWidth)1197 StringLiteral *StringLiteral::CreateEmpty(const ASTContext &Ctx,
1198 unsigned NumConcatenated,
1199 unsigned Length,
1200 unsigned CharByteWidth) {
1201 void *Mem = Ctx.Allocate(totalSizeToAlloc<unsigned, SourceLocation, char>(
1202 1, NumConcatenated, Length * CharByteWidth),
1203 alignof(StringLiteral));
1204 return new (Mem)
1205 StringLiteral(EmptyShell(), NumConcatenated, Length, CharByteWidth);
1206 }
1207
outputString(raw_ostream & OS) const1208 void StringLiteral::outputString(raw_ostream &OS) const {
1209 switch (getKind()) {
1210 case StringLiteralKind::Unevaluated:
1211 case StringLiteralKind::Ordinary:
1212 case StringLiteralKind::Binary:
1213 break; // no prefix.
1214 case StringLiteralKind::Wide:
1215 OS << 'L';
1216 break;
1217 case StringLiteralKind::UTF8:
1218 OS << "u8";
1219 break;
1220 case StringLiteralKind::UTF16:
1221 OS << 'u';
1222 break;
1223 case StringLiteralKind::UTF32:
1224 OS << 'U';
1225 break;
1226 }
1227 OS << '"';
1228 static const char Hex[] = "0123456789ABCDEF";
1229
1230 unsigned LastSlashX = getLength();
1231 for (unsigned I = 0, N = getLength(); I != N; ++I) {
1232 uint32_t Char = getCodeUnit(I);
1233 StringRef Escaped = escapeCStyle<EscapeChar::Double>(Char);
1234 if (Escaped.empty()) {
1235 // FIXME: Convert UTF-8 back to codepoints before rendering.
1236
1237 // Convert UTF-16 surrogate pairs back to codepoints before rendering.
1238 // Leave invalid surrogates alone; we'll use \x for those.
1239 if (getKind() == StringLiteralKind::UTF16 && I != N - 1 &&
1240 Char >= 0xd800 && Char <= 0xdbff) {
1241 uint32_t Trail = getCodeUnit(I + 1);
1242 if (Trail >= 0xdc00 && Trail <= 0xdfff) {
1243 Char = 0x10000 + ((Char - 0xd800) << 10) + (Trail - 0xdc00);
1244 ++I;
1245 }
1246 }
1247
1248 if (Char > 0xff) {
1249 // If this is a wide string, output characters over 0xff using \x
1250 // escapes. Otherwise, this is a UTF-16 or UTF-32 string, and Char is a
1251 // codepoint: use \x escapes for invalid codepoints.
1252 if (getKind() == StringLiteralKind::Wide ||
1253 (Char >= 0xd800 && Char <= 0xdfff) || Char >= 0x110000) {
1254 // FIXME: Is this the best way to print wchar_t?
1255 OS << "\\x";
1256 int Shift = 28;
1257 while ((Char >> Shift) == 0)
1258 Shift -= 4;
1259 for (/**/; Shift >= 0; Shift -= 4)
1260 OS << Hex[(Char >> Shift) & 15];
1261 LastSlashX = I;
1262 continue;
1263 }
1264
1265 if (Char > 0xffff)
1266 OS << "\\U00"
1267 << Hex[(Char >> 20) & 15]
1268 << Hex[(Char >> 16) & 15];
1269 else
1270 OS << "\\u";
1271 OS << Hex[(Char >> 12) & 15]
1272 << Hex[(Char >> 8) & 15]
1273 << Hex[(Char >> 4) & 15]
1274 << Hex[(Char >> 0) & 15];
1275 continue;
1276 }
1277
1278 // If we used \x... for the previous character, and this character is a
1279 // hexadecimal digit, prevent it being slurped as part of the \x.
1280 if (LastSlashX + 1 == I) {
1281 switch (Char) {
1282 case '0': case '1': case '2': case '3': case '4':
1283 case '5': case '6': case '7': case '8': case '9':
1284 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
1285 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
1286 OS << "\"\"";
1287 }
1288 }
1289
1290 assert(Char <= 0xff &&
1291 "Characters above 0xff should already have been handled.");
1292
1293 if (isPrintable(Char))
1294 OS << (char)Char;
1295 else // Output anything hard as an octal escape.
1296 OS << '\\'
1297 << (char)('0' + ((Char >> 6) & 7))
1298 << (char)('0' + ((Char >> 3) & 7))
1299 << (char)('0' + ((Char >> 0) & 7));
1300 } else {
1301 // Handle some common non-printable cases to make dumps prettier.
1302 OS << Escaped;
1303 }
1304 }
1305 OS << '"';
1306 }
1307
1308 /// getLocationOfByte - Return a source location that points to the specified
1309 /// byte of this string literal.
1310 ///
1311 /// Strings are amazingly complex. They can be formed from multiple tokens and
1312 /// can have escape sequences in them in addition to the usual trigraph and
1313 /// escaped newline business. This routine handles this complexity.
1314 ///
1315 /// The *StartToken sets the first token to be searched in this function and
1316 /// the *StartTokenByteOffset is the byte offset of the first token. Before
1317 /// returning, it updates the *StartToken to the TokNo of the token being found
1318 /// and sets *StartTokenByteOffset to the byte offset of the token in the
1319 /// string.
1320 /// Using these two parameters can reduce the time complexity from O(n^2) to
1321 /// O(n) if one wants to get the location of byte for all the tokens in a
1322 /// string.
1323 ///
1324 SourceLocation
getLocationOfByte(unsigned ByteNo,const SourceManager & SM,const LangOptions & Features,const TargetInfo & Target,unsigned * StartToken,unsigned * StartTokenByteOffset) const1325 StringLiteral::getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1326 const LangOptions &Features,
1327 const TargetInfo &Target, unsigned *StartToken,
1328 unsigned *StartTokenByteOffset) const {
1329 // No source location of bytes for binary literals since they don't come from
1330 // source.
1331 if (getKind() == StringLiteralKind::Binary)
1332 return getStrTokenLoc(0);
1333
1334 assert((getKind() == StringLiteralKind::Ordinary ||
1335 getKind() == StringLiteralKind::UTF8 ||
1336 getKind() == StringLiteralKind::Unevaluated) &&
1337 "Only narrow string literals are currently supported");
1338
1339 // Loop over all of the tokens in this string until we find the one that
1340 // contains the byte we're looking for.
1341 unsigned TokNo = 0;
1342 unsigned StringOffset = 0;
1343 if (StartToken)
1344 TokNo = *StartToken;
1345 if (StartTokenByteOffset) {
1346 StringOffset = *StartTokenByteOffset;
1347 ByteNo -= StringOffset;
1348 }
1349 while (true) {
1350 assert(TokNo < getNumConcatenated() && "Invalid byte number!");
1351 SourceLocation StrTokLoc = getStrTokenLoc(TokNo);
1352
1353 // Get the spelling of the string so that we can get the data that makes up
1354 // the string literal, not the identifier for the macro it is potentially
1355 // expanded through.
1356 SourceLocation StrTokSpellingLoc = SM.getSpellingLoc(StrTokLoc);
1357
1358 // Re-lex the token to get its length and original spelling.
1359 FileIDAndOffset LocInfo = SM.getDecomposedLoc(StrTokSpellingLoc);
1360 bool Invalid = false;
1361 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
1362 if (Invalid) {
1363 if (StartTokenByteOffset != nullptr)
1364 *StartTokenByteOffset = StringOffset;
1365 if (StartToken != nullptr)
1366 *StartToken = TokNo;
1367 return StrTokSpellingLoc;
1368 }
1369
1370 const char *StrData = Buffer.data()+LocInfo.second;
1371
1372 // Create a lexer starting at the beginning of this token.
1373 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), Features,
1374 Buffer.begin(), StrData, Buffer.end());
1375 Token TheTok;
1376 TheLexer.LexFromRawLexer(TheTok);
1377
1378 // Use the StringLiteralParser to compute the length of the string in bytes.
1379 StringLiteralParser SLP(TheTok, SM, Features, Target);
1380 unsigned TokNumBytes = SLP.GetStringLength();
1381
1382 // If the byte is in this token, return the location of the byte.
1383 if (ByteNo < TokNumBytes ||
1384 (ByteNo == TokNumBytes && TokNo == getNumConcatenated() - 1)) {
1385 unsigned Offset = SLP.getOffsetOfStringByte(TheTok, ByteNo);
1386
1387 // Now that we know the offset of the token in the spelling, use the
1388 // preprocessor to get the offset in the original source.
1389 if (StartTokenByteOffset != nullptr)
1390 *StartTokenByteOffset = StringOffset;
1391 if (StartToken != nullptr)
1392 *StartToken = TokNo;
1393 return Lexer::AdvanceToTokenCharacter(StrTokLoc, Offset, SM, Features);
1394 }
1395
1396 // Move to the next string token.
1397 StringOffset += TokNumBytes;
1398 ++TokNo;
1399 ByteNo -= TokNumBytes;
1400 }
1401 }
1402
1403 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1404 /// corresponds to, e.g. "sizeof" or "[pre]++".
getOpcodeStr(Opcode Op)1405 StringRef UnaryOperator::getOpcodeStr(Opcode Op) {
1406 switch (Op) {
1407 #define UNARY_OPERATION(Name, Spelling) case UO_##Name: return Spelling;
1408 #include "clang/AST/OperationKinds.def"
1409 }
1410 llvm_unreachable("Unknown unary operator");
1411 }
1412
1413 UnaryOperatorKind
getOverloadedOpcode(OverloadedOperatorKind OO,bool Postfix)1414 UnaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix) {
1415 switch (OO) {
1416 default: llvm_unreachable("No unary operator for overloaded function");
1417 case OO_PlusPlus: return Postfix ? UO_PostInc : UO_PreInc;
1418 case OO_MinusMinus: return Postfix ? UO_PostDec : UO_PreDec;
1419 case OO_Amp: return UO_AddrOf;
1420 case OO_Star: return UO_Deref;
1421 case OO_Plus: return UO_Plus;
1422 case OO_Minus: return UO_Minus;
1423 case OO_Tilde: return UO_Not;
1424 case OO_Exclaim: return UO_LNot;
1425 case OO_Coawait: return UO_Coawait;
1426 }
1427 }
1428
getOverloadedOperator(Opcode Opc)1429 OverloadedOperatorKind UnaryOperator::getOverloadedOperator(Opcode Opc) {
1430 switch (Opc) {
1431 case UO_PostInc: case UO_PreInc: return OO_PlusPlus;
1432 case UO_PostDec: case UO_PreDec: return OO_MinusMinus;
1433 case UO_AddrOf: return OO_Amp;
1434 case UO_Deref: return OO_Star;
1435 case UO_Plus: return OO_Plus;
1436 case UO_Minus: return OO_Minus;
1437 case UO_Not: return OO_Tilde;
1438 case UO_LNot: return OO_Exclaim;
1439 case UO_Coawait: return OO_Coawait;
1440 default: return OO_None;
1441 }
1442 }
1443
1444
1445 //===----------------------------------------------------------------------===//
1446 // Postfix Operators.
1447 //===----------------------------------------------------------------------===//
1448 #ifndef NDEBUG
SizeOfCallExprInstance(Expr::StmtClass SC)1449 static unsigned SizeOfCallExprInstance(Expr::StmtClass SC) {
1450 switch (SC) {
1451 case Expr::CallExprClass:
1452 return sizeof(CallExpr);
1453 case Expr::CXXOperatorCallExprClass:
1454 return sizeof(CXXOperatorCallExpr);
1455 case Expr::CXXMemberCallExprClass:
1456 return sizeof(CXXMemberCallExpr);
1457 case Expr::UserDefinedLiteralClass:
1458 return sizeof(UserDefinedLiteral);
1459 case Expr::CUDAKernelCallExprClass:
1460 return sizeof(CUDAKernelCallExpr);
1461 default:
1462 llvm_unreachable("unexpected class deriving from CallExpr!");
1463 }
1464 }
1465 #endif
1466
1467 // changing the size of SourceLocation, CallExpr, and
1468 // subclasses requires careful considerations
1469 static_assert(sizeof(SourceLocation) == 4 && sizeof(CXXOperatorCallExpr) <= 32,
1470 "we assume CXXOperatorCallExpr is at most 32 bytes");
1471
CallExpr(StmtClass SC,Expr * Fn,ArrayRef<Expr * > PreArgs,ArrayRef<Expr * > Args,QualType Ty,ExprValueKind VK,SourceLocation RParenLoc,FPOptionsOverride FPFeatures,unsigned MinNumArgs,ADLCallKind UsesADL)1472 CallExpr::CallExpr(StmtClass SC, Expr *Fn, ArrayRef<Expr *> PreArgs,
1473 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
1474 SourceLocation RParenLoc, FPOptionsOverride FPFeatures,
1475 unsigned MinNumArgs, ADLCallKind UsesADL)
1476 : Expr(SC, Ty, VK, OK_Ordinary), RParenLoc(RParenLoc) {
1477 NumArgs = std::max<unsigned>(Args.size(), MinNumArgs);
1478 unsigned NumPreArgs = PreArgs.size();
1479 CallExprBits.NumPreArgs = NumPreArgs;
1480 assert((NumPreArgs == getNumPreArgs()) && "NumPreArgs overflow!");
1481 assert(SizeOfCallExprInstance(SC) <= OffsetToTrailingObjects &&
1482 "This CallExpr subclass is too big or unsupported");
1483
1484 CallExprBits.UsesADL = static_cast<bool>(UsesADL);
1485
1486 setCallee(Fn);
1487 for (unsigned I = 0; I != NumPreArgs; ++I)
1488 setPreArg(I, PreArgs[I]);
1489 for (unsigned I = 0; I != Args.size(); ++I)
1490 setArg(I, Args[I]);
1491 for (unsigned I = Args.size(); I != NumArgs; ++I)
1492 setArg(I, nullptr);
1493
1494 this->computeDependence();
1495
1496 CallExprBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();
1497 CallExprBits.IsCoroElideSafe = false;
1498 CallExprBits.ExplicitObjectMemFunUsingMemberSyntax = false;
1499 CallExprBits.HasTrailingSourceLoc = false;
1500
1501 if (hasStoredFPFeatures())
1502 setStoredFPFeatures(FPFeatures);
1503 }
1504
CallExpr(StmtClass SC,unsigned NumPreArgs,unsigned NumArgs,bool HasFPFeatures,EmptyShell Empty)1505 CallExpr::CallExpr(StmtClass SC, unsigned NumPreArgs, unsigned NumArgs,
1506 bool HasFPFeatures, EmptyShell Empty)
1507 : Expr(SC, Empty), NumArgs(NumArgs) {
1508 CallExprBits.NumPreArgs = NumPreArgs;
1509 assert((NumPreArgs == getNumPreArgs()) && "NumPreArgs overflow!");
1510 CallExprBits.HasFPFeatures = HasFPFeatures;
1511 CallExprBits.IsCoroElideSafe = false;
1512 CallExprBits.ExplicitObjectMemFunUsingMemberSyntax = false;
1513 CallExprBits.HasTrailingSourceLoc = false;
1514 }
1515
Create(const ASTContext & Ctx,Expr * Fn,ArrayRef<Expr * > Args,QualType Ty,ExprValueKind VK,SourceLocation RParenLoc,FPOptionsOverride FPFeatures,unsigned MinNumArgs,ADLCallKind UsesADL)1516 CallExpr *CallExpr::Create(const ASTContext &Ctx, Expr *Fn,
1517 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
1518 SourceLocation RParenLoc,
1519 FPOptionsOverride FPFeatures, unsigned MinNumArgs,
1520 ADLCallKind UsesADL) {
1521 unsigned NumArgs = std::max<unsigned>(Args.size(), MinNumArgs);
1522 unsigned SizeOfTrailingObjects = CallExpr::sizeOfTrailingObjects(
1523 /*NumPreArgs=*/0, NumArgs, FPFeatures.requiresTrailingStorage());
1524 void *Mem = Ctx.Allocate(
1525 sizeToAllocateForCallExprSubclass<CallExpr>(SizeOfTrailingObjects),
1526 alignof(CallExpr));
1527 CallExpr *E =
1528 new (Mem) CallExpr(CallExprClass, Fn, /*PreArgs=*/{}, Args, Ty, VK,
1529 RParenLoc, FPFeatures, MinNumArgs, UsesADL);
1530 E->updateTrailingSourceLoc();
1531 return E;
1532 }
1533
CreateEmpty(const ASTContext & Ctx,unsigned NumArgs,bool HasFPFeatures,EmptyShell Empty)1534 CallExpr *CallExpr::CreateEmpty(const ASTContext &Ctx, unsigned NumArgs,
1535 bool HasFPFeatures, EmptyShell Empty) {
1536 unsigned SizeOfTrailingObjects =
1537 CallExpr::sizeOfTrailingObjects(/*NumPreArgs=*/0, NumArgs, HasFPFeatures);
1538 void *Mem = Ctx.Allocate(
1539 sizeToAllocateForCallExprSubclass<CallExpr>(SizeOfTrailingObjects),
1540 alignof(CallExpr));
1541 return new (Mem)
1542 CallExpr(CallExprClass, /*NumPreArgs=*/0, NumArgs, HasFPFeatures, Empty);
1543 }
1544
getReferencedDeclOfCallee()1545 Decl *Expr::getReferencedDeclOfCallee() {
1546
1547 // Optimize for the common case first
1548 // (simple function or member function call)
1549 // then try more exotic possibilities.
1550 Expr *CEE = IgnoreImpCasts();
1551
1552 if (auto *DRE = dyn_cast<DeclRefExpr>(CEE))
1553 return DRE->getDecl();
1554
1555 if (auto *ME = dyn_cast<MemberExpr>(CEE))
1556 return ME->getMemberDecl();
1557
1558 CEE = CEE->IgnoreParens();
1559
1560 while (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(CEE))
1561 CEE = NTTP->getReplacement()->IgnoreParenImpCasts();
1562
1563 // If we're calling a dereference, look at the pointer instead.
1564 while (true) {
1565 if (auto *BO = dyn_cast<BinaryOperator>(CEE)) {
1566 if (BO->isPtrMemOp()) {
1567 CEE = BO->getRHS()->IgnoreParenImpCasts();
1568 continue;
1569 }
1570 } else if (auto *UO = dyn_cast<UnaryOperator>(CEE)) {
1571 if (UO->getOpcode() == UO_Deref || UO->getOpcode() == UO_AddrOf ||
1572 UO->getOpcode() == UO_Plus) {
1573 CEE = UO->getSubExpr()->IgnoreParenImpCasts();
1574 continue;
1575 }
1576 }
1577 break;
1578 }
1579
1580 if (auto *DRE = dyn_cast<DeclRefExpr>(CEE))
1581 return DRE->getDecl();
1582 if (auto *ME = dyn_cast<MemberExpr>(CEE))
1583 return ME->getMemberDecl();
1584 if (auto *BE = dyn_cast<BlockExpr>(CEE))
1585 return BE->getBlockDecl();
1586
1587 return nullptr;
1588 }
1589
1590 /// If this is a call to a builtin, return the builtin ID. If not, return 0.
getBuiltinCallee() const1591 unsigned CallExpr::getBuiltinCallee() const {
1592 const auto *FDecl = getDirectCallee();
1593 return FDecl ? FDecl->getBuiltinID() : 0;
1594 }
1595
isUnevaluatedBuiltinCall(const ASTContext & Ctx) const1596 bool CallExpr::isUnevaluatedBuiltinCall(const ASTContext &Ctx) const {
1597 if (unsigned BI = getBuiltinCallee())
1598 return Ctx.BuiltinInfo.isUnevaluated(BI);
1599 return false;
1600 }
1601
getCallReturnType(const ASTContext & Ctx) const1602 QualType CallExpr::getCallReturnType(const ASTContext &Ctx) const {
1603 const Expr *Callee = getCallee();
1604 QualType CalleeType = Callee->getType();
1605 if (const auto *FnTypePtr = CalleeType->getAs<PointerType>()) {
1606 CalleeType = FnTypePtr->getPointeeType();
1607 } else if (const auto *BPT = CalleeType->getAs<BlockPointerType>()) {
1608 CalleeType = BPT->getPointeeType();
1609 } else if (CalleeType->isSpecificPlaceholderType(BuiltinType::BoundMember)) {
1610 if (isa<CXXPseudoDestructorExpr>(Callee->IgnoreParens()))
1611 return Ctx.VoidTy;
1612
1613 if (isa<UnresolvedMemberExpr>(Callee->IgnoreParens()))
1614 return Ctx.DependentTy;
1615
1616 // This should never be overloaded and so should never return null.
1617 CalleeType = Expr::findBoundMemberType(Callee);
1618 assert(!CalleeType.isNull());
1619 } else if (CalleeType->isRecordType()) {
1620 // If the Callee is a record type, then it is a not-yet-resolved
1621 // dependent call to the call operator of that type.
1622 return Ctx.DependentTy;
1623 } else if (CalleeType->isDependentType() ||
1624 CalleeType->isSpecificPlaceholderType(BuiltinType::Overload)) {
1625 return Ctx.DependentTy;
1626 }
1627
1628 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
1629 return FnType->getReturnType();
1630 }
1631
1632 std::pair<const NamedDecl *, const Attr *>
getUnusedResultAttr(const ASTContext & Ctx) const1633 CallExpr::getUnusedResultAttr(const ASTContext &Ctx) const {
1634 // If the callee is marked nodiscard, return that attribute
1635 if (const Decl *D = getCalleeDecl())
1636 if (const auto *A = D->getAttr<WarnUnusedResultAttr>())
1637 return {nullptr, A};
1638
1639 // If the return type is a struct, union, or enum that is marked nodiscard,
1640 // then return the return type attribute.
1641 if (const TagDecl *TD = getCallReturnType(Ctx)->getAsTagDecl())
1642 if (const auto *A = TD->getAttr<WarnUnusedResultAttr>())
1643 return {TD, A};
1644
1645 for (const auto *TD = getCallReturnType(Ctx)->getAs<TypedefType>(); TD;
1646 TD = TD->desugar()->getAs<TypedefType>())
1647 if (const auto *A = TD->getDecl()->getAttr<WarnUnusedResultAttr>())
1648 return {TD->getDecl(), A};
1649 return {nullptr, nullptr};
1650 }
1651
Create(const ASTContext & C,QualType type,SourceLocation OperatorLoc,TypeSourceInfo * tsi,ArrayRef<OffsetOfNode> comps,ArrayRef<Expr * > exprs,SourceLocation RParenLoc)1652 OffsetOfExpr *OffsetOfExpr::Create(const ASTContext &C, QualType type,
1653 SourceLocation OperatorLoc,
1654 TypeSourceInfo *tsi,
1655 ArrayRef<OffsetOfNode> comps,
1656 ArrayRef<Expr*> exprs,
1657 SourceLocation RParenLoc) {
1658 void *Mem = C.Allocate(
1659 totalSizeToAlloc<OffsetOfNode, Expr *>(comps.size(), exprs.size()));
1660
1661 return new (Mem) OffsetOfExpr(C, type, OperatorLoc, tsi, comps, exprs,
1662 RParenLoc);
1663 }
1664
CreateEmpty(const ASTContext & C,unsigned numComps,unsigned numExprs)1665 OffsetOfExpr *OffsetOfExpr::CreateEmpty(const ASTContext &C,
1666 unsigned numComps, unsigned numExprs) {
1667 void *Mem =
1668 C.Allocate(totalSizeToAlloc<OffsetOfNode, Expr *>(numComps, numExprs));
1669 return new (Mem) OffsetOfExpr(numComps, numExprs);
1670 }
1671
OffsetOfExpr(const ASTContext & C,QualType type,SourceLocation OperatorLoc,TypeSourceInfo * tsi,ArrayRef<OffsetOfNode> comps,ArrayRef<Expr * > exprs,SourceLocation RParenLoc)1672 OffsetOfExpr::OffsetOfExpr(const ASTContext &C, QualType type,
1673 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1674 ArrayRef<OffsetOfNode> comps, ArrayRef<Expr *> exprs,
1675 SourceLocation RParenLoc)
1676 : Expr(OffsetOfExprClass, type, VK_PRValue, OK_Ordinary),
1677 OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi),
1678 NumComps(comps.size()), NumExprs(exprs.size()) {
1679 for (unsigned i = 0; i != comps.size(); ++i)
1680 setComponent(i, comps[i]);
1681 for (unsigned i = 0; i != exprs.size(); ++i)
1682 setIndexExpr(i, exprs[i]);
1683
1684 setDependence(computeDependence(this));
1685 }
1686
getFieldName() const1687 IdentifierInfo *OffsetOfNode::getFieldName() const {
1688 assert(getKind() == Field || getKind() == Identifier);
1689 if (getKind() == Field)
1690 return getField()->getIdentifier();
1691
1692 return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask);
1693 }
1694
UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind,Expr * E,QualType resultType,SourceLocation op,SourceLocation rp)1695 UnaryExprOrTypeTraitExpr::UnaryExprOrTypeTraitExpr(
1696 UnaryExprOrTypeTrait ExprKind, Expr *E, QualType resultType,
1697 SourceLocation op, SourceLocation rp)
1698 : Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_PRValue, OK_Ordinary),
1699 OpLoc(op), RParenLoc(rp) {
1700 assert(ExprKind <= UETT_Last && "invalid enum value!");
1701 UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
1702 assert(static_cast<unsigned>(ExprKind) == UnaryExprOrTypeTraitExprBits.Kind &&
1703 "UnaryExprOrTypeTraitExprBits.Kind overflow!");
1704 UnaryExprOrTypeTraitExprBits.IsType = false;
1705 Argument.Ex = E;
1706 setDependence(computeDependence(this));
1707 }
1708
MemberExpr(Expr * Base,bool IsArrow,SourceLocation OperatorLoc,NestedNameSpecifierLoc QualifierLoc,SourceLocation TemplateKWLoc,ValueDecl * MemberDecl,DeclAccessPair FoundDecl,const DeclarationNameInfo & NameInfo,const TemplateArgumentListInfo * TemplateArgs,QualType T,ExprValueKind VK,ExprObjectKind OK,NonOdrUseReason NOUR)1709 MemberExpr::MemberExpr(Expr *Base, bool IsArrow, SourceLocation OperatorLoc,
1710 NestedNameSpecifierLoc QualifierLoc,
1711 SourceLocation TemplateKWLoc, ValueDecl *MemberDecl,
1712 DeclAccessPair FoundDecl,
1713 const DeclarationNameInfo &NameInfo,
1714 const TemplateArgumentListInfo *TemplateArgs, QualType T,
1715 ExprValueKind VK, ExprObjectKind OK,
1716 NonOdrUseReason NOUR)
1717 : Expr(MemberExprClass, T, VK, OK), Base(Base), MemberDecl(MemberDecl),
1718 MemberDNLoc(NameInfo.getInfo()), MemberLoc(NameInfo.getLoc()) {
1719 assert(!NameInfo.getName() ||
1720 MemberDecl->getDeclName() == NameInfo.getName());
1721 MemberExprBits.IsArrow = IsArrow;
1722 MemberExprBits.HasQualifier = QualifierLoc.hasQualifier();
1723 MemberExprBits.HasFoundDecl =
1724 FoundDecl.getDecl() != MemberDecl ||
1725 FoundDecl.getAccess() != MemberDecl->getAccess();
1726 MemberExprBits.HasTemplateKWAndArgsInfo =
1727 TemplateArgs || TemplateKWLoc.isValid();
1728 MemberExprBits.HadMultipleCandidates = false;
1729 MemberExprBits.NonOdrUseReason = NOUR;
1730 MemberExprBits.OperatorLoc = OperatorLoc;
1731
1732 if (hasQualifier())
1733 new (getTrailingObjects<NestedNameSpecifierLoc>())
1734 NestedNameSpecifierLoc(QualifierLoc);
1735 if (hasFoundDecl())
1736 *getTrailingObjects<DeclAccessPair>() = FoundDecl;
1737 if (TemplateArgs) {
1738 auto Deps = TemplateArgumentDependence::None;
1739 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1740 TemplateKWLoc, *TemplateArgs, getTrailingObjects<TemplateArgumentLoc>(),
1741 Deps);
1742 } else if (TemplateKWLoc.isValid()) {
1743 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1744 TemplateKWLoc);
1745 }
1746 setDependence(computeDependence(this));
1747 }
1748
Create(const ASTContext & C,Expr * Base,bool IsArrow,SourceLocation OperatorLoc,NestedNameSpecifierLoc QualifierLoc,SourceLocation TemplateKWLoc,ValueDecl * MemberDecl,DeclAccessPair FoundDecl,DeclarationNameInfo NameInfo,const TemplateArgumentListInfo * TemplateArgs,QualType T,ExprValueKind VK,ExprObjectKind OK,NonOdrUseReason NOUR)1749 MemberExpr *MemberExpr::Create(
1750 const ASTContext &C, Expr *Base, bool IsArrow, SourceLocation OperatorLoc,
1751 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
1752 ValueDecl *MemberDecl, DeclAccessPair FoundDecl,
1753 DeclarationNameInfo NameInfo, const TemplateArgumentListInfo *TemplateArgs,
1754 QualType T, ExprValueKind VK, ExprObjectKind OK, NonOdrUseReason NOUR) {
1755 bool HasQualifier = QualifierLoc.hasQualifier();
1756 bool HasFoundDecl = FoundDecl.getDecl() != MemberDecl ||
1757 FoundDecl.getAccess() != MemberDecl->getAccess();
1758 bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
1759 std::size_t Size =
1760 totalSizeToAlloc<NestedNameSpecifierLoc, DeclAccessPair,
1761 ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
1762 HasQualifier, HasFoundDecl, HasTemplateKWAndArgsInfo,
1763 TemplateArgs ? TemplateArgs->size() : 0);
1764
1765 void *Mem = C.Allocate(Size, alignof(MemberExpr));
1766 return new (Mem) MemberExpr(Base, IsArrow, OperatorLoc, QualifierLoc,
1767 TemplateKWLoc, MemberDecl, FoundDecl, NameInfo,
1768 TemplateArgs, T, VK, OK, NOUR);
1769 }
1770
CreateEmpty(const ASTContext & Context,bool HasQualifier,bool HasFoundDecl,bool HasTemplateKWAndArgsInfo,unsigned NumTemplateArgs)1771 MemberExpr *MemberExpr::CreateEmpty(const ASTContext &Context,
1772 bool HasQualifier, bool HasFoundDecl,
1773 bool HasTemplateKWAndArgsInfo,
1774 unsigned NumTemplateArgs) {
1775 assert((!NumTemplateArgs || HasTemplateKWAndArgsInfo) &&
1776 "template args but no template arg info?");
1777 std::size_t Size =
1778 totalSizeToAlloc<NestedNameSpecifierLoc, DeclAccessPair,
1779 ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
1780 HasQualifier, HasFoundDecl, HasTemplateKWAndArgsInfo,
1781 NumTemplateArgs);
1782 void *Mem = Context.Allocate(Size, alignof(MemberExpr));
1783 return new (Mem) MemberExpr(EmptyShell());
1784 }
1785
setMemberDecl(ValueDecl * NewD)1786 void MemberExpr::setMemberDecl(ValueDecl *NewD) {
1787 MemberDecl = NewD;
1788 if (getType()->isUndeducedType())
1789 setType(NewD->getType());
1790 setDependence(computeDependence(this));
1791 }
1792
getBeginLoc() const1793 SourceLocation MemberExpr::getBeginLoc() const {
1794 if (isImplicitAccess()) {
1795 if (hasQualifier())
1796 return getQualifierLoc().getBeginLoc();
1797 return MemberLoc;
1798 }
1799
1800 // FIXME: We don't want this to happen. Rather, we should be able to
1801 // detect all kinds of implicit accesses more cleanly.
1802 SourceLocation BaseStartLoc = getBase()->getBeginLoc();
1803 if (BaseStartLoc.isValid())
1804 return BaseStartLoc;
1805 return MemberLoc;
1806 }
getEndLoc() const1807 SourceLocation MemberExpr::getEndLoc() const {
1808 SourceLocation EndLoc = getMemberNameInfo().getEndLoc();
1809 if (hasExplicitTemplateArgs())
1810 EndLoc = getRAngleLoc();
1811 else if (EndLoc.isInvalid())
1812 EndLoc = getBase()->getEndLoc();
1813 return EndLoc;
1814 }
1815
CastConsistency() const1816 bool CastExpr::CastConsistency() const {
1817 switch (getCastKind()) {
1818 case CK_DerivedToBase:
1819 case CK_UncheckedDerivedToBase:
1820 case CK_DerivedToBaseMemberPointer:
1821 case CK_BaseToDerived:
1822 case CK_BaseToDerivedMemberPointer:
1823 assert(!path_empty() && "Cast kind should have a base path!");
1824 break;
1825
1826 case CK_CPointerToObjCPointerCast:
1827 assert(getType()->isObjCObjectPointerType());
1828 assert(getSubExpr()->getType()->isPointerType());
1829 goto CheckNoBasePath;
1830
1831 case CK_BlockPointerToObjCPointerCast:
1832 assert(getType()->isObjCObjectPointerType());
1833 assert(getSubExpr()->getType()->isBlockPointerType());
1834 goto CheckNoBasePath;
1835
1836 case CK_ReinterpretMemberPointer:
1837 assert(getType()->isMemberPointerType());
1838 assert(getSubExpr()->getType()->isMemberPointerType());
1839 goto CheckNoBasePath;
1840
1841 case CK_BitCast:
1842 // Arbitrary casts to C pointer types count as bitcasts.
1843 // Otherwise, we should only have block and ObjC pointer casts
1844 // here if they stay within the type kind.
1845 if (!getType()->isPointerType()) {
1846 assert(getType()->isObjCObjectPointerType() ==
1847 getSubExpr()->getType()->isObjCObjectPointerType());
1848 assert(getType()->isBlockPointerType() ==
1849 getSubExpr()->getType()->isBlockPointerType());
1850 }
1851 goto CheckNoBasePath;
1852
1853 case CK_AnyPointerToBlockPointerCast:
1854 assert(getType()->isBlockPointerType());
1855 assert(getSubExpr()->getType()->isAnyPointerType() &&
1856 !getSubExpr()->getType()->isBlockPointerType());
1857 goto CheckNoBasePath;
1858
1859 case CK_CopyAndAutoreleaseBlockObject:
1860 assert(getType()->isBlockPointerType());
1861 assert(getSubExpr()->getType()->isBlockPointerType());
1862 goto CheckNoBasePath;
1863
1864 case CK_FunctionToPointerDecay:
1865 assert(getType()->isPointerType());
1866 assert(getSubExpr()->getType()->isFunctionType());
1867 goto CheckNoBasePath;
1868
1869 case CK_AddressSpaceConversion: {
1870 auto Ty = getType();
1871 auto SETy = getSubExpr()->getType();
1872 assert(getValueKindForType(Ty) == Expr::getValueKindForType(SETy));
1873 if (isPRValue() && !Ty->isDependentType() && !SETy->isDependentType()) {
1874 Ty = Ty->getPointeeType();
1875 SETy = SETy->getPointeeType();
1876 }
1877 assert((Ty->isDependentType() || SETy->isDependentType()) ||
1878 (!Ty.isNull() && !SETy.isNull() &&
1879 Ty.getAddressSpace() != SETy.getAddressSpace()));
1880 goto CheckNoBasePath;
1881 }
1882 // These should not have an inheritance path.
1883 case CK_Dynamic:
1884 case CK_ToUnion:
1885 case CK_ArrayToPointerDecay:
1886 case CK_NullToMemberPointer:
1887 case CK_NullToPointer:
1888 case CK_ConstructorConversion:
1889 case CK_IntegralToPointer:
1890 case CK_PointerToIntegral:
1891 case CK_ToVoid:
1892 case CK_VectorSplat:
1893 case CK_IntegralCast:
1894 case CK_BooleanToSignedIntegral:
1895 case CK_IntegralToFloating:
1896 case CK_FloatingToIntegral:
1897 case CK_FloatingCast:
1898 case CK_ObjCObjectLValueCast:
1899 case CK_FloatingRealToComplex:
1900 case CK_FloatingComplexToReal:
1901 case CK_FloatingComplexCast:
1902 case CK_FloatingComplexToIntegralComplex:
1903 case CK_IntegralRealToComplex:
1904 case CK_IntegralComplexToReal:
1905 case CK_IntegralComplexCast:
1906 case CK_IntegralComplexToFloatingComplex:
1907 case CK_ARCProduceObject:
1908 case CK_ARCConsumeObject:
1909 case CK_ARCReclaimReturnedObject:
1910 case CK_ARCExtendBlockObject:
1911 case CK_ZeroToOCLOpaqueType:
1912 case CK_IntToOCLSampler:
1913 case CK_FloatingToFixedPoint:
1914 case CK_FixedPointToFloating:
1915 case CK_FixedPointCast:
1916 case CK_FixedPointToIntegral:
1917 case CK_IntegralToFixedPoint:
1918 case CK_MatrixCast:
1919 assert(!getType()->isBooleanType() && "unheralded conversion to bool");
1920 goto CheckNoBasePath;
1921
1922 case CK_Dependent:
1923 case CK_LValueToRValue:
1924 case CK_NoOp:
1925 case CK_AtomicToNonAtomic:
1926 case CK_NonAtomicToAtomic:
1927 case CK_PointerToBoolean:
1928 case CK_IntegralToBoolean:
1929 case CK_FloatingToBoolean:
1930 case CK_MemberPointerToBoolean:
1931 case CK_FloatingComplexToBoolean:
1932 case CK_IntegralComplexToBoolean:
1933 case CK_LValueBitCast: // -> bool&
1934 case CK_LValueToRValueBitCast:
1935 case CK_UserDefinedConversion: // operator bool()
1936 case CK_BuiltinFnToFnPtr:
1937 case CK_FixedPointToBoolean:
1938 case CK_HLSLArrayRValue:
1939 case CK_HLSLVectorTruncation:
1940 case CK_HLSLElementwiseCast:
1941 case CK_HLSLAggregateSplatCast:
1942 CheckNoBasePath:
1943 assert(path_empty() && "Cast kind should not have a base path!");
1944 break;
1945 }
1946 return true;
1947 }
1948
getCastKindName(CastKind CK)1949 const char *CastExpr::getCastKindName(CastKind CK) {
1950 switch (CK) {
1951 #define CAST_OPERATION(Name) case CK_##Name: return #Name;
1952 #include "clang/AST/OperationKinds.def"
1953 }
1954 llvm_unreachable("Unhandled cast kind!");
1955 }
1956
1957 namespace {
1958 // Skip over implicit nodes produced as part of semantic analysis.
1959 // Designed for use with IgnoreExprNodes.
ignoreImplicitSemaNodes(Expr * E)1960 static Expr *ignoreImplicitSemaNodes(Expr *E) {
1961 if (auto *Materialize = dyn_cast<MaterializeTemporaryExpr>(E))
1962 return Materialize->getSubExpr();
1963
1964 if (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
1965 return Binder->getSubExpr();
1966
1967 if (auto *Full = dyn_cast<FullExpr>(E))
1968 return Full->getSubExpr();
1969
1970 if (auto *CPLIE = dyn_cast<CXXParenListInitExpr>(E);
1971 CPLIE && CPLIE->getInitExprs().size() == 1)
1972 return CPLIE->getInitExprs()[0];
1973
1974 return E;
1975 }
1976 } // namespace
1977
getSubExprAsWritten()1978 Expr *CastExpr::getSubExprAsWritten() {
1979 const Expr *SubExpr = nullptr;
1980
1981 for (const CastExpr *E = this; E; E = dyn_cast<ImplicitCastExpr>(SubExpr)) {
1982 SubExpr = IgnoreExprNodes(E->getSubExpr(), ignoreImplicitSemaNodes);
1983
1984 // Conversions by constructor and conversion functions have a
1985 // subexpression describing the call; strip it off.
1986 if (E->getCastKind() == CK_ConstructorConversion) {
1987 SubExpr = IgnoreExprNodes(cast<CXXConstructExpr>(SubExpr)->getArg(0),
1988 ignoreImplicitSemaNodes);
1989 } else if (E->getCastKind() == CK_UserDefinedConversion) {
1990 assert((isa<CallExpr, BlockExpr>(SubExpr)) &&
1991 "Unexpected SubExpr for CK_UserDefinedConversion.");
1992 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))
1993 SubExpr = MCE->getImplicitObjectArgument();
1994 }
1995 }
1996
1997 return const_cast<Expr *>(SubExpr);
1998 }
1999
getConversionFunction() const2000 NamedDecl *CastExpr::getConversionFunction() const {
2001 const Expr *SubExpr = nullptr;
2002
2003 for (const CastExpr *E = this; E; E = dyn_cast<ImplicitCastExpr>(SubExpr)) {
2004 SubExpr = IgnoreExprNodes(E->getSubExpr(), ignoreImplicitSemaNodes);
2005
2006 if (E->getCastKind() == CK_ConstructorConversion)
2007 return cast<CXXConstructExpr>(SubExpr)->getConstructor();
2008
2009 if (E->getCastKind() == CK_UserDefinedConversion) {
2010 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))
2011 return MCE->getMethodDecl();
2012 }
2013 }
2014
2015 return nullptr;
2016 }
2017
path_buffer()2018 CXXBaseSpecifier **CastExpr::path_buffer() {
2019 switch (getStmtClass()) {
2020 #define ABSTRACT_STMT(x)
2021 #define CASTEXPR(Type, Base) \
2022 case Stmt::Type##Class: \
2023 return static_cast<Type *>(this) \
2024 ->getTrailingObjectsNonStrict<CXXBaseSpecifier *>();
2025 #define STMT(Type, Base)
2026 #include "clang/AST/StmtNodes.inc"
2027 default:
2028 llvm_unreachable("non-cast expressions not possible here");
2029 }
2030 }
2031
getTargetFieldForToUnionCast(QualType unionType,QualType opType)2032 const FieldDecl *CastExpr::getTargetFieldForToUnionCast(QualType unionType,
2033 QualType opType) {
2034 auto RD = unionType->castAs<RecordType>()->getDecl();
2035 return getTargetFieldForToUnionCast(RD, opType);
2036 }
2037
getTargetFieldForToUnionCast(const RecordDecl * RD,QualType OpType)2038 const FieldDecl *CastExpr::getTargetFieldForToUnionCast(const RecordDecl *RD,
2039 QualType OpType) {
2040 auto &Ctx = RD->getASTContext();
2041 RecordDecl::field_iterator Field, FieldEnd;
2042 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2043 Field != FieldEnd; ++Field) {
2044 if (Ctx.hasSameUnqualifiedType(Field->getType(), OpType) &&
2045 !Field->isUnnamedBitField()) {
2046 return *Field;
2047 }
2048 }
2049 return nullptr;
2050 }
2051
getTrailingFPFeatures()2052 FPOptionsOverride *CastExpr::getTrailingFPFeatures() {
2053 assert(hasStoredFPFeatures());
2054 switch (getStmtClass()) {
2055 case ImplicitCastExprClass:
2056 return static_cast<ImplicitCastExpr *>(this)
2057 ->getTrailingObjects<FPOptionsOverride>();
2058 case CStyleCastExprClass:
2059 return static_cast<CStyleCastExpr *>(this)
2060 ->getTrailingObjects<FPOptionsOverride>();
2061 case CXXFunctionalCastExprClass:
2062 return static_cast<CXXFunctionalCastExpr *>(this)
2063 ->getTrailingObjects<FPOptionsOverride>();
2064 case CXXStaticCastExprClass:
2065 return static_cast<CXXStaticCastExpr *>(this)
2066 ->getTrailingObjects<FPOptionsOverride>();
2067 default:
2068 llvm_unreachable("Cast does not have FPFeatures");
2069 }
2070 }
2071
Create(const ASTContext & C,QualType T,CastKind Kind,Expr * Operand,const CXXCastPath * BasePath,ExprValueKind VK,FPOptionsOverride FPO)2072 ImplicitCastExpr *ImplicitCastExpr::Create(const ASTContext &C, QualType T,
2073 CastKind Kind, Expr *Operand,
2074 const CXXCastPath *BasePath,
2075 ExprValueKind VK,
2076 FPOptionsOverride FPO) {
2077 unsigned PathSize = (BasePath ? BasePath->size() : 0);
2078 void *Buffer =
2079 C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(
2080 PathSize, FPO.requiresTrailingStorage()));
2081 // Per C++ [conv.lval]p3, lvalue-to-rvalue conversions on class and
2082 // std::nullptr_t have special semantics not captured by CK_LValueToRValue.
2083 assert((Kind != CK_LValueToRValue ||
2084 !(T->isNullPtrType() || T->getAsCXXRecordDecl())) &&
2085 "invalid type for lvalue-to-rvalue conversion");
2086 ImplicitCastExpr *E =
2087 new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, FPO, VK);
2088 if (PathSize)
2089 llvm::uninitialized_copy(*BasePath,
2090 E->getTrailingObjects<CXXBaseSpecifier *>());
2091 return E;
2092 }
2093
CreateEmpty(const ASTContext & C,unsigned PathSize,bool HasFPFeatures)2094 ImplicitCastExpr *ImplicitCastExpr::CreateEmpty(const ASTContext &C,
2095 unsigned PathSize,
2096 bool HasFPFeatures) {
2097 void *Buffer =
2098 C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(
2099 PathSize, HasFPFeatures));
2100 return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize, HasFPFeatures);
2101 }
2102
Create(const ASTContext & C,QualType T,ExprValueKind VK,CastKind K,Expr * Op,const CXXCastPath * BasePath,FPOptionsOverride FPO,TypeSourceInfo * WrittenTy,SourceLocation L,SourceLocation R)2103 CStyleCastExpr *CStyleCastExpr::Create(const ASTContext &C, QualType T,
2104 ExprValueKind VK, CastKind K, Expr *Op,
2105 const CXXCastPath *BasePath,
2106 FPOptionsOverride FPO,
2107 TypeSourceInfo *WrittenTy,
2108 SourceLocation L, SourceLocation R) {
2109 unsigned PathSize = (BasePath ? BasePath->size() : 0);
2110 void *Buffer =
2111 C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(
2112 PathSize, FPO.requiresTrailingStorage()));
2113 CStyleCastExpr *E =
2114 new (Buffer) CStyleCastExpr(T, VK, K, Op, PathSize, FPO, WrittenTy, L, R);
2115 if (PathSize)
2116 llvm::uninitialized_copy(*BasePath,
2117 E->getTrailingObjects<CXXBaseSpecifier *>());
2118 return E;
2119 }
2120
CreateEmpty(const ASTContext & C,unsigned PathSize,bool HasFPFeatures)2121 CStyleCastExpr *CStyleCastExpr::CreateEmpty(const ASTContext &C,
2122 unsigned PathSize,
2123 bool HasFPFeatures) {
2124 void *Buffer =
2125 C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(
2126 PathSize, HasFPFeatures));
2127 return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize, HasFPFeatures);
2128 }
2129
2130 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
2131 /// corresponds to, e.g. "<<=".
getOpcodeStr(Opcode Op)2132 StringRef BinaryOperator::getOpcodeStr(Opcode Op) {
2133 switch (Op) {
2134 #define BINARY_OPERATION(Name, Spelling) case BO_##Name: return Spelling;
2135 #include "clang/AST/OperationKinds.def"
2136 }
2137 llvm_unreachable("Invalid OpCode!");
2138 }
2139
2140 BinaryOperatorKind
getOverloadedOpcode(OverloadedOperatorKind OO)2141 BinaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO) {
2142 switch (OO) {
2143 default: llvm_unreachable("Not an overloadable binary operator");
2144 case OO_Plus: return BO_Add;
2145 case OO_Minus: return BO_Sub;
2146 case OO_Star: return BO_Mul;
2147 case OO_Slash: return BO_Div;
2148 case OO_Percent: return BO_Rem;
2149 case OO_Caret: return BO_Xor;
2150 case OO_Amp: return BO_And;
2151 case OO_Pipe: return BO_Or;
2152 case OO_Equal: return BO_Assign;
2153 case OO_Spaceship: return BO_Cmp;
2154 case OO_Less: return BO_LT;
2155 case OO_Greater: return BO_GT;
2156 case OO_PlusEqual: return BO_AddAssign;
2157 case OO_MinusEqual: return BO_SubAssign;
2158 case OO_StarEqual: return BO_MulAssign;
2159 case OO_SlashEqual: return BO_DivAssign;
2160 case OO_PercentEqual: return BO_RemAssign;
2161 case OO_CaretEqual: return BO_XorAssign;
2162 case OO_AmpEqual: return BO_AndAssign;
2163 case OO_PipeEqual: return BO_OrAssign;
2164 case OO_LessLess: return BO_Shl;
2165 case OO_GreaterGreater: return BO_Shr;
2166 case OO_LessLessEqual: return BO_ShlAssign;
2167 case OO_GreaterGreaterEqual: return BO_ShrAssign;
2168 case OO_EqualEqual: return BO_EQ;
2169 case OO_ExclaimEqual: return BO_NE;
2170 case OO_LessEqual: return BO_LE;
2171 case OO_GreaterEqual: return BO_GE;
2172 case OO_AmpAmp: return BO_LAnd;
2173 case OO_PipePipe: return BO_LOr;
2174 case OO_Comma: return BO_Comma;
2175 case OO_ArrowStar: return BO_PtrMemI;
2176 }
2177 }
2178
getOverloadedOperator(Opcode Opc)2179 OverloadedOperatorKind BinaryOperator::getOverloadedOperator(Opcode Opc) {
2180 static const OverloadedOperatorKind OverOps[] = {
2181 /* .* Cannot be overloaded */OO_None, OO_ArrowStar,
2182 OO_Star, OO_Slash, OO_Percent,
2183 OO_Plus, OO_Minus,
2184 OO_LessLess, OO_GreaterGreater,
2185 OO_Spaceship,
2186 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
2187 OO_EqualEqual, OO_ExclaimEqual,
2188 OO_Amp,
2189 OO_Caret,
2190 OO_Pipe,
2191 OO_AmpAmp,
2192 OO_PipePipe,
2193 OO_Equal, OO_StarEqual,
2194 OO_SlashEqual, OO_PercentEqual,
2195 OO_PlusEqual, OO_MinusEqual,
2196 OO_LessLessEqual, OO_GreaterGreaterEqual,
2197 OO_AmpEqual, OO_CaretEqual,
2198 OO_PipeEqual,
2199 OO_Comma
2200 };
2201 return OverOps[Opc];
2202 }
2203
isNullPointerArithmeticExtension(ASTContext & Ctx,Opcode Opc,const Expr * LHS,const Expr * RHS)2204 bool BinaryOperator::isNullPointerArithmeticExtension(ASTContext &Ctx,
2205 Opcode Opc,
2206 const Expr *LHS,
2207 const Expr *RHS) {
2208 if (Opc != BO_Add)
2209 return false;
2210
2211 // Check that we have one pointer and one integer operand.
2212 const Expr *PExp;
2213 if (LHS->getType()->isPointerType()) {
2214 if (!RHS->getType()->isIntegerType())
2215 return false;
2216 PExp = LHS;
2217 } else if (RHS->getType()->isPointerType()) {
2218 if (!LHS->getType()->isIntegerType())
2219 return false;
2220 PExp = RHS;
2221 } else {
2222 return false;
2223 }
2224
2225 // Workaround for old glibc's __PTR_ALIGN macro
2226 if (auto *Select =
2227 dyn_cast<ConditionalOperator>(PExp->IgnoreParenNoopCasts(Ctx))) {
2228 // If the condition can be constant evaluated, we check the selected arm.
2229 bool EvalResult;
2230 if (!Select->getCond()->EvaluateAsBooleanCondition(EvalResult, Ctx))
2231 return false;
2232 PExp = EvalResult ? Select->getTrueExpr() : Select->getFalseExpr();
2233 }
2234
2235 // Check that the pointer is a nullptr.
2236 if (!PExp->IgnoreParenCasts()
2237 ->isNullPointerConstant(Ctx, Expr::NPC_ValueDependentIsNotNull))
2238 return false;
2239
2240 // Check that the pointee type is char-sized.
2241 const PointerType *PTy = PExp->getType()->getAs<PointerType>();
2242 if (!PTy || !PTy->getPointeeType()->isCharType())
2243 return false;
2244
2245 return true;
2246 }
2247
SourceLocExpr(const ASTContext & Ctx,SourceLocIdentKind Kind,QualType ResultTy,SourceLocation BLoc,SourceLocation RParenLoc,DeclContext * ParentContext)2248 SourceLocExpr::SourceLocExpr(const ASTContext &Ctx, SourceLocIdentKind Kind,
2249 QualType ResultTy, SourceLocation BLoc,
2250 SourceLocation RParenLoc,
2251 DeclContext *ParentContext)
2252 : Expr(SourceLocExprClass, ResultTy, VK_PRValue, OK_Ordinary),
2253 BuiltinLoc(BLoc), RParenLoc(RParenLoc), ParentContext(ParentContext) {
2254 SourceLocExprBits.Kind = llvm::to_underlying(Kind);
2255 // In dependent contexts, function names may change.
2256 setDependence(MayBeDependent(Kind) && ParentContext->isDependentContext()
2257 ? ExprDependence::Value
2258 : ExprDependence::None);
2259 }
2260
getBuiltinStr() const2261 StringRef SourceLocExpr::getBuiltinStr() const {
2262 switch (getIdentKind()) {
2263 case SourceLocIdentKind::File:
2264 return "__builtin_FILE";
2265 case SourceLocIdentKind::FileName:
2266 return "__builtin_FILE_NAME";
2267 case SourceLocIdentKind::Function:
2268 return "__builtin_FUNCTION";
2269 case SourceLocIdentKind::FuncSig:
2270 return "__builtin_FUNCSIG";
2271 case SourceLocIdentKind::Line:
2272 return "__builtin_LINE";
2273 case SourceLocIdentKind::Column:
2274 return "__builtin_COLUMN";
2275 case SourceLocIdentKind::SourceLocStruct:
2276 return "__builtin_source_location";
2277 }
2278 llvm_unreachable("unexpected IdentKind!");
2279 }
2280
EvaluateInContext(const ASTContext & Ctx,const Expr * DefaultExpr) const2281 APValue SourceLocExpr::EvaluateInContext(const ASTContext &Ctx,
2282 const Expr *DefaultExpr) const {
2283 SourceLocation Loc;
2284 const DeclContext *Context;
2285
2286 if (const auto *DIE = dyn_cast_if_present<CXXDefaultInitExpr>(DefaultExpr)) {
2287 Loc = DIE->getUsedLocation();
2288 Context = DIE->getUsedContext();
2289 } else if (const auto *DAE =
2290 dyn_cast_if_present<CXXDefaultArgExpr>(DefaultExpr)) {
2291 Loc = DAE->getUsedLocation();
2292 Context = DAE->getUsedContext();
2293 } else {
2294 Loc = getLocation();
2295 Context = getParentContext();
2296 }
2297
2298 // If we are currently parsing a lambda declarator, we might not have a fully
2299 // formed call operator declaration yet, and we could not form a function name
2300 // for it. Because we do not have access to Sema/function scopes here, we
2301 // detect this case by relying on the fact such method doesn't yet have a
2302 // type.
2303 if (const auto *D = dyn_cast<CXXMethodDecl>(Context);
2304 D && D->getFunctionTypeLoc().isNull() && isLambdaCallOperator(D))
2305 Context = D->getParent()->getParent();
2306
2307 PresumedLoc PLoc = Ctx.getSourceManager().getPresumedLoc(
2308 Ctx.getSourceManager().getExpansionRange(Loc).getEnd());
2309
2310 auto MakeStringLiteral = [&](StringRef Tmp) {
2311 using LValuePathEntry = APValue::LValuePathEntry;
2312 StringLiteral *Res = Ctx.getPredefinedStringLiteralFromCache(Tmp);
2313 // Decay the string to a pointer to the first character.
2314 LValuePathEntry Path[1] = {LValuePathEntry::ArrayIndex(0)};
2315 return APValue(Res, CharUnits::Zero(), Path, /*OnePastTheEnd=*/false);
2316 };
2317
2318 switch (getIdentKind()) {
2319 case SourceLocIdentKind::FileName: {
2320 // __builtin_FILE_NAME() is a Clang-specific extension that expands to the
2321 // the last part of __builtin_FILE().
2322 SmallString<256> FileName;
2323 clang::Preprocessor::processPathToFileName(
2324 FileName, PLoc, Ctx.getLangOpts(), Ctx.getTargetInfo());
2325 return MakeStringLiteral(FileName);
2326 }
2327 case SourceLocIdentKind::File: {
2328 SmallString<256> Path(PLoc.getFilename());
2329 clang::Preprocessor::processPathForFileMacro(Path, Ctx.getLangOpts(),
2330 Ctx.getTargetInfo());
2331 return MakeStringLiteral(Path);
2332 }
2333 case SourceLocIdentKind::Function:
2334 case SourceLocIdentKind::FuncSig: {
2335 const auto *CurDecl = dyn_cast<Decl>(Context);
2336 const auto Kind = getIdentKind() == SourceLocIdentKind::Function
2337 ? PredefinedIdentKind::Function
2338 : PredefinedIdentKind::FuncSig;
2339 return MakeStringLiteral(
2340 CurDecl ? PredefinedExpr::ComputeName(Kind, CurDecl) : std::string(""));
2341 }
2342 case SourceLocIdentKind::Line:
2343 return APValue(Ctx.MakeIntValue(PLoc.getLine(), Ctx.UnsignedIntTy));
2344 case SourceLocIdentKind::Column:
2345 return APValue(Ctx.MakeIntValue(PLoc.getColumn(), Ctx.UnsignedIntTy));
2346 case SourceLocIdentKind::SourceLocStruct: {
2347 // Fill in a std::source_location::__impl structure, by creating an
2348 // artificial file-scoped CompoundLiteralExpr, and returning a pointer to
2349 // that.
2350 const CXXRecordDecl *ImplDecl = getType()->getPointeeCXXRecordDecl();
2351 assert(ImplDecl);
2352
2353 // Construct an APValue for the __impl struct, and get or create a Decl
2354 // corresponding to that. Note that we've already verified that the shape of
2355 // the ImplDecl type is as expected.
2356
2357 APValue Value(APValue::UninitStruct(), 0, 4);
2358 for (const FieldDecl *F : ImplDecl->fields()) {
2359 StringRef Name = F->getName();
2360 if (Name == "_M_file_name") {
2361 SmallString<256> Path(PLoc.getFilename());
2362 clang::Preprocessor::processPathForFileMacro(Path, Ctx.getLangOpts(),
2363 Ctx.getTargetInfo());
2364 Value.getStructField(F->getFieldIndex()) = MakeStringLiteral(Path);
2365 } else if (Name == "_M_function_name") {
2366 // Note: this emits the PrettyFunction name -- different than what
2367 // __builtin_FUNCTION() above returns!
2368 const auto *CurDecl = dyn_cast<Decl>(Context);
2369 Value.getStructField(F->getFieldIndex()) = MakeStringLiteral(
2370 CurDecl && !isa<TranslationUnitDecl>(CurDecl)
2371 ? StringRef(PredefinedExpr::ComputeName(
2372 PredefinedIdentKind::PrettyFunction, CurDecl))
2373 : "");
2374 } else if (Name == "_M_line") {
2375 llvm::APSInt IntVal = Ctx.MakeIntValue(PLoc.getLine(), F->getType());
2376 Value.getStructField(F->getFieldIndex()) = APValue(IntVal);
2377 } else if (Name == "_M_column") {
2378 llvm::APSInt IntVal = Ctx.MakeIntValue(PLoc.getColumn(), F->getType());
2379 Value.getStructField(F->getFieldIndex()) = APValue(IntVal);
2380 }
2381 }
2382
2383 UnnamedGlobalConstantDecl *GV =
2384 Ctx.getUnnamedGlobalConstantDecl(getType()->getPointeeType(), Value);
2385
2386 return APValue(GV, CharUnits::Zero(), ArrayRef<APValue::LValuePathEntry>{},
2387 false);
2388 }
2389 }
2390 llvm_unreachable("unhandled case");
2391 }
2392
EmbedExpr(const ASTContext & Ctx,SourceLocation Loc,EmbedDataStorage * Data,unsigned Begin,unsigned NumOfElements)2393 EmbedExpr::EmbedExpr(const ASTContext &Ctx, SourceLocation Loc,
2394 EmbedDataStorage *Data, unsigned Begin,
2395 unsigned NumOfElements)
2396 : Expr(EmbedExprClass, Ctx.IntTy, VK_PRValue, OK_Ordinary),
2397 EmbedKeywordLoc(Loc), Ctx(&Ctx), Data(Data), Begin(Begin),
2398 NumOfElements(NumOfElements) {
2399 setDependence(ExprDependence::None);
2400 FakeChildNode = IntegerLiteral::Create(
2401 Ctx, llvm::APInt::getZero(Ctx.getTypeSize(getType())), getType(), Loc);
2402 }
2403
InitListExpr(const ASTContext & C,SourceLocation lbraceloc,ArrayRef<Expr * > initExprs,SourceLocation rbraceloc)2404 InitListExpr::InitListExpr(const ASTContext &C, SourceLocation lbraceloc,
2405 ArrayRef<Expr *> initExprs, SourceLocation rbraceloc)
2406 : Expr(InitListExprClass, QualType(), VK_PRValue, OK_Ordinary),
2407 InitExprs(C, initExprs.size()), LBraceLoc(lbraceloc),
2408 RBraceLoc(rbraceloc), AltForm(nullptr, true) {
2409 sawArrayRangeDesignator(false);
2410 InitExprs.insert(C, InitExprs.end(), initExprs.begin(), initExprs.end());
2411
2412 setDependence(computeDependence(this));
2413 }
2414
reserveInits(const ASTContext & C,unsigned NumInits)2415 void InitListExpr::reserveInits(const ASTContext &C, unsigned NumInits) {
2416 if (NumInits > InitExprs.size())
2417 InitExprs.reserve(C, NumInits);
2418 }
2419
resizeInits(const ASTContext & C,unsigned NumInits)2420 void InitListExpr::resizeInits(const ASTContext &C, unsigned NumInits) {
2421 InitExprs.resize(C, NumInits, nullptr);
2422 }
2423
updateInit(const ASTContext & C,unsigned Init,Expr * expr)2424 Expr *InitListExpr::updateInit(const ASTContext &C, unsigned Init, Expr *expr) {
2425 if (Init >= InitExprs.size()) {
2426 InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, nullptr);
2427 setInit(Init, expr);
2428 return nullptr;
2429 }
2430
2431 Expr *Result = cast_or_null<Expr>(InitExprs[Init]);
2432 setInit(Init, expr);
2433 return Result;
2434 }
2435
setArrayFiller(Expr * filler)2436 void InitListExpr::setArrayFiller(Expr *filler) {
2437 assert(!hasArrayFiller() && "Filler already set!");
2438 ArrayFillerOrUnionFieldInit = filler;
2439 // Fill out any "holes" in the array due to designated initializers.
2440 Expr **inits = getInits();
2441 for (unsigned i = 0, e = getNumInits(); i != e; ++i)
2442 if (inits[i] == nullptr)
2443 inits[i] = filler;
2444 }
2445
isStringLiteralInit() const2446 bool InitListExpr::isStringLiteralInit() const {
2447 if (getNumInits() != 1)
2448 return false;
2449 const ArrayType *AT = getType()->getAsArrayTypeUnsafe();
2450 if (!AT || !AT->getElementType()->isIntegerType())
2451 return false;
2452 // It is possible for getInit() to return null.
2453 const Expr *Init = getInit(0);
2454 if (!Init)
2455 return false;
2456 Init = Init->IgnoreParenImpCasts();
2457 return isa<StringLiteral>(Init) || isa<ObjCEncodeExpr>(Init);
2458 }
2459
isTransparent() const2460 bool InitListExpr::isTransparent() const {
2461 assert(isSemanticForm() && "syntactic form never semantically transparent");
2462
2463 // A glvalue InitListExpr is always just sugar.
2464 if (isGLValue()) {
2465 assert(getNumInits() == 1 && "multiple inits in glvalue init list");
2466 return true;
2467 }
2468
2469 // Otherwise, we're sugar if and only if we have exactly one initializer that
2470 // is of the same type.
2471 if (getNumInits() != 1 || !getInit(0))
2472 return false;
2473
2474 // Don't confuse aggregate initialization of a struct X { X &x; }; with a
2475 // transparent struct copy.
2476 if (!getInit(0)->isPRValue() && getType()->isRecordType())
2477 return false;
2478
2479 return getType().getCanonicalType() ==
2480 getInit(0)->getType().getCanonicalType();
2481 }
2482
isIdiomaticZeroInitializer(const LangOptions & LangOpts) const2483 bool InitListExpr::isIdiomaticZeroInitializer(const LangOptions &LangOpts) const {
2484 assert(isSyntacticForm() && "only test syntactic form as zero initializer");
2485
2486 if (LangOpts.CPlusPlus || getNumInits() != 1 || !getInit(0)) {
2487 return false;
2488 }
2489
2490 const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(getInit(0)->IgnoreImplicit());
2491 return Lit && Lit->getValue() == 0;
2492 }
2493
getBeginLoc() const2494 SourceLocation InitListExpr::getBeginLoc() const {
2495 if (InitListExpr *SyntacticForm = getSyntacticForm())
2496 return SyntacticForm->getBeginLoc();
2497 SourceLocation Beg = LBraceLoc;
2498 if (Beg.isInvalid()) {
2499 // Find the first non-null initializer.
2500 for (InitExprsTy::const_iterator I = InitExprs.begin(),
2501 E = InitExprs.end();
2502 I != E; ++I) {
2503 if (Stmt *S = *I) {
2504 Beg = S->getBeginLoc();
2505 break;
2506 }
2507 }
2508 }
2509 return Beg;
2510 }
2511
getEndLoc() const2512 SourceLocation InitListExpr::getEndLoc() const {
2513 if (InitListExpr *SyntacticForm = getSyntacticForm())
2514 return SyntacticForm->getEndLoc();
2515 SourceLocation End = RBraceLoc;
2516 if (End.isInvalid()) {
2517 // Find the first non-null initializer from the end.
2518 for (Stmt *S : llvm::reverse(InitExprs)) {
2519 if (S) {
2520 End = S->getEndLoc();
2521 break;
2522 }
2523 }
2524 }
2525 return End;
2526 }
2527
2528 /// getFunctionType - Return the underlying function type for this block.
2529 ///
getFunctionType() const2530 const FunctionProtoType *BlockExpr::getFunctionType() const {
2531 // The block pointer is never sugared, but the function type might be.
2532 return cast<BlockPointerType>(getType())
2533 ->getPointeeType()->castAs<FunctionProtoType>();
2534 }
2535
getCaretLocation() const2536 SourceLocation BlockExpr::getCaretLocation() const {
2537 return TheBlock->getCaretLocation();
2538 }
getBody() const2539 const Stmt *BlockExpr::getBody() const {
2540 return TheBlock->getBody();
2541 }
getBody()2542 Stmt *BlockExpr::getBody() {
2543 return TheBlock->getBody();
2544 }
2545
2546
2547 //===----------------------------------------------------------------------===//
2548 // Generic Expression Routines
2549 //===----------------------------------------------------------------------===//
2550
isReadIfDiscardedInCPlusPlus11() const2551 bool Expr::isReadIfDiscardedInCPlusPlus11() const {
2552 // In C++11, discarded-value expressions of a certain form are special,
2553 // according to [expr]p10:
2554 // The lvalue-to-rvalue conversion (4.1) is applied only if the
2555 // expression is a glvalue of volatile-qualified type and it has
2556 // one of the following forms:
2557 if (!isGLValue() || !getType().isVolatileQualified())
2558 return false;
2559
2560 const Expr *E = IgnoreParens();
2561
2562 // - id-expression (5.1.1),
2563 if (isa<DeclRefExpr>(E))
2564 return true;
2565
2566 // - subscripting (5.2.1),
2567 if (isa<ArraySubscriptExpr>(E))
2568 return true;
2569
2570 // - class member access (5.2.5),
2571 if (isa<MemberExpr>(E))
2572 return true;
2573
2574 // - indirection (5.3.1),
2575 if (auto *UO = dyn_cast<UnaryOperator>(E))
2576 if (UO->getOpcode() == UO_Deref)
2577 return true;
2578
2579 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
2580 // - pointer-to-member operation (5.5),
2581 if (BO->isPtrMemOp())
2582 return true;
2583
2584 // - comma expression (5.18) where the right operand is one of the above.
2585 if (BO->getOpcode() == BO_Comma)
2586 return BO->getRHS()->isReadIfDiscardedInCPlusPlus11();
2587 }
2588
2589 // - conditional expression (5.16) where both the second and the third
2590 // operands are one of the above, or
2591 if (auto *CO = dyn_cast<ConditionalOperator>(E))
2592 return CO->getTrueExpr()->isReadIfDiscardedInCPlusPlus11() &&
2593 CO->getFalseExpr()->isReadIfDiscardedInCPlusPlus11();
2594 // The related edge case of "*x ?: *x".
2595 if (auto *BCO =
2596 dyn_cast<BinaryConditionalOperator>(E)) {
2597 if (auto *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
2598 return OVE->getSourceExpr()->isReadIfDiscardedInCPlusPlus11() &&
2599 BCO->getFalseExpr()->isReadIfDiscardedInCPlusPlus11();
2600 }
2601
2602 // Objective-C++ extensions to the rule.
2603 if (isa<ObjCIvarRefExpr>(E))
2604 return true;
2605 if (const auto *POE = dyn_cast<PseudoObjectExpr>(E)) {
2606 if (isa<ObjCPropertyRefExpr, ObjCSubscriptRefExpr>(POE->getSyntacticForm()))
2607 return true;
2608 }
2609
2610 return false;
2611 }
2612
2613 /// isUnusedResultAWarning - Return true if this immediate expression should
2614 /// be warned about if the result is unused. If so, fill in Loc and Ranges
2615 /// with location to warn on and the source range[s] to report with the
2616 /// warning.
isUnusedResultAWarning(const Expr * & WarnE,SourceLocation & Loc,SourceRange & R1,SourceRange & R2,ASTContext & Ctx) const2617 bool Expr::isUnusedResultAWarning(const Expr *&WarnE, SourceLocation &Loc,
2618 SourceRange &R1, SourceRange &R2,
2619 ASTContext &Ctx) const {
2620 // Don't warn if the expr is type dependent. The type could end up
2621 // instantiating to void.
2622 if (isTypeDependent())
2623 return false;
2624
2625 switch (getStmtClass()) {
2626 default:
2627 if (getType()->isVoidType())
2628 return false;
2629 WarnE = this;
2630 Loc = getExprLoc();
2631 R1 = getSourceRange();
2632 return true;
2633 case ParenExprClass:
2634 return cast<ParenExpr>(this)->getSubExpr()->
2635 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2636 case GenericSelectionExprClass:
2637 return cast<GenericSelectionExpr>(this)->getResultExpr()->
2638 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2639 case CoawaitExprClass:
2640 case CoyieldExprClass:
2641 return cast<CoroutineSuspendExpr>(this)->getResumeExpr()->
2642 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2643 case ChooseExprClass:
2644 return cast<ChooseExpr>(this)->getChosenSubExpr()->
2645 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2646 case UnaryOperatorClass: {
2647 const UnaryOperator *UO = cast<UnaryOperator>(this);
2648
2649 switch (UO->getOpcode()) {
2650 case UO_Plus:
2651 case UO_Minus:
2652 case UO_AddrOf:
2653 case UO_Not:
2654 case UO_LNot:
2655 case UO_Deref:
2656 break;
2657 case UO_Coawait:
2658 // This is just the 'operator co_await' call inside the guts of a
2659 // dependent co_await call.
2660 case UO_PostInc:
2661 case UO_PostDec:
2662 case UO_PreInc:
2663 case UO_PreDec: // ++/--
2664 return false; // Not a warning.
2665 case UO_Real:
2666 case UO_Imag:
2667 // accessing a piece of a volatile complex is a side-effect.
2668 if (Ctx.getCanonicalType(UO->getSubExpr()->getType())
2669 .isVolatileQualified())
2670 return false;
2671 break;
2672 case UO_Extension:
2673 return UO->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2674 }
2675 WarnE = this;
2676 Loc = UO->getOperatorLoc();
2677 R1 = UO->getSubExpr()->getSourceRange();
2678 return true;
2679 }
2680 case BinaryOperatorClass: {
2681 const BinaryOperator *BO = cast<BinaryOperator>(this);
2682 switch (BO->getOpcode()) {
2683 default:
2684 break;
2685 // Consider the RHS of comma for side effects. LHS was checked by
2686 // Sema::CheckCommaOperands.
2687 case BO_Comma:
2688 // ((foo = <blah>), 0) is an idiom for hiding the result (and
2689 // lvalue-ness) of an assignment written in a macro.
2690 if (IntegerLiteral *IE =
2691 dyn_cast<IntegerLiteral>(BO->getRHS()->IgnoreParens()))
2692 if (IE->getValue() == 0)
2693 return false;
2694 return BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2695 // Consider '||', '&&' to have side effects if the LHS or RHS does.
2696 case BO_LAnd:
2697 case BO_LOr:
2698 if (!BO->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) ||
2699 !BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
2700 return false;
2701 break;
2702 }
2703 if (BO->isAssignmentOp())
2704 return false;
2705 WarnE = this;
2706 Loc = BO->getOperatorLoc();
2707 R1 = BO->getLHS()->getSourceRange();
2708 R2 = BO->getRHS()->getSourceRange();
2709 return true;
2710 }
2711 case CompoundAssignOperatorClass:
2712 case VAArgExprClass:
2713 case AtomicExprClass:
2714 return false;
2715
2716 case ConditionalOperatorClass: {
2717 // If only one of the LHS or RHS is a warning, the operator might
2718 // be being used for control flow. Only warn if both the LHS and
2719 // RHS are warnings.
2720 const auto *Exp = cast<ConditionalOperator>(this);
2721 return Exp->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) &&
2722 Exp->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2723 }
2724 case BinaryConditionalOperatorClass: {
2725 const auto *Exp = cast<BinaryConditionalOperator>(this);
2726 return Exp->getFalseExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2727 }
2728
2729 case MemberExprClass:
2730 WarnE = this;
2731 Loc = cast<MemberExpr>(this)->getMemberLoc();
2732 R1 = SourceRange(Loc, Loc);
2733 R2 = cast<MemberExpr>(this)->getBase()->getSourceRange();
2734 return true;
2735
2736 case ArraySubscriptExprClass:
2737 WarnE = this;
2738 Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc();
2739 R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange();
2740 R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange();
2741 return true;
2742
2743 case CXXOperatorCallExprClass: {
2744 // Warn about operator ==,!=,<,>,<=, and >= even when user-defined operator
2745 // overloads as there is no reasonable way to define these such that they
2746 // have non-trivial, desirable side-effects. See the -Wunused-comparison
2747 // warning: operators == and != are commonly typo'ed, and so warning on them
2748 // provides additional value as well. If this list is updated,
2749 // DiagnoseUnusedComparison should be as well.
2750 const CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(this);
2751 switch (Op->getOperator()) {
2752 default:
2753 break;
2754 case OO_EqualEqual:
2755 case OO_ExclaimEqual:
2756 case OO_Less:
2757 case OO_Greater:
2758 case OO_GreaterEqual:
2759 case OO_LessEqual:
2760 if (Op->getCallReturnType(Ctx)->isReferenceType() ||
2761 Op->getCallReturnType(Ctx)->isVoidType())
2762 break;
2763 WarnE = this;
2764 Loc = Op->getOperatorLoc();
2765 R1 = Op->getSourceRange();
2766 return true;
2767 }
2768
2769 // Fallthrough for generic call handling.
2770 [[fallthrough]];
2771 }
2772 case CallExprClass:
2773 case CXXMemberCallExprClass:
2774 case UserDefinedLiteralClass: {
2775 // If this is a direct call, get the callee.
2776 const CallExpr *CE = cast<CallExpr>(this);
2777 if (const Decl *FD = CE->getCalleeDecl()) {
2778 // If the callee has attribute pure, const, or warn_unused_result, warn
2779 // about it. void foo() { strlen("bar"); } should warn.
2780 //
2781 // Note: If new cases are added here, DiagnoseUnusedExprResult should be
2782 // updated to match for QoI.
2783 if (CE->hasUnusedResultAttr(Ctx) ||
2784 FD->hasAttr<PureAttr>() || FD->hasAttr<ConstAttr>()) {
2785 WarnE = this;
2786 Loc = CE->getCallee()->getBeginLoc();
2787 R1 = CE->getCallee()->getSourceRange();
2788
2789 if (unsigned NumArgs = CE->getNumArgs())
2790 R2 = SourceRange(CE->getArg(0)->getBeginLoc(),
2791 CE->getArg(NumArgs - 1)->getEndLoc());
2792 return true;
2793 }
2794 }
2795 return false;
2796 }
2797
2798 // If we don't know precisely what we're looking at, let's not warn.
2799 case UnresolvedLookupExprClass:
2800 case CXXUnresolvedConstructExprClass:
2801 case RecoveryExprClass:
2802 return false;
2803
2804 case CXXTemporaryObjectExprClass:
2805 case CXXConstructExprClass: {
2806 if (const CXXRecordDecl *Type = getType()->getAsCXXRecordDecl()) {
2807 const auto *WarnURAttr = Type->getAttr<WarnUnusedResultAttr>();
2808 if (Type->hasAttr<WarnUnusedAttr>() ||
2809 (WarnURAttr && WarnURAttr->IsCXX11NoDiscard())) {
2810 WarnE = this;
2811 Loc = getBeginLoc();
2812 R1 = getSourceRange();
2813 return true;
2814 }
2815 }
2816
2817 const auto *CE = cast<CXXConstructExpr>(this);
2818 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) {
2819 const auto *WarnURAttr = Ctor->getAttr<WarnUnusedResultAttr>();
2820 if (WarnURAttr && WarnURAttr->IsCXX11NoDiscard()) {
2821 WarnE = this;
2822 Loc = getBeginLoc();
2823 R1 = getSourceRange();
2824
2825 if (unsigned NumArgs = CE->getNumArgs())
2826 R2 = SourceRange(CE->getArg(0)->getBeginLoc(),
2827 CE->getArg(NumArgs - 1)->getEndLoc());
2828 return true;
2829 }
2830 }
2831
2832 return false;
2833 }
2834
2835 case ObjCMessageExprClass: {
2836 const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(this);
2837 if (Ctx.getLangOpts().ObjCAutoRefCount &&
2838 ME->isInstanceMessage() &&
2839 !ME->getType()->isVoidType() &&
2840 ME->getMethodFamily() == OMF_init) {
2841 WarnE = this;
2842 Loc = getExprLoc();
2843 R1 = ME->getSourceRange();
2844 return true;
2845 }
2846
2847 if (const ObjCMethodDecl *MD = ME->getMethodDecl())
2848 if (MD->hasAttr<WarnUnusedResultAttr>()) {
2849 WarnE = this;
2850 Loc = getExprLoc();
2851 return true;
2852 }
2853
2854 return false;
2855 }
2856
2857 case ObjCPropertyRefExprClass:
2858 case ObjCSubscriptRefExprClass:
2859 WarnE = this;
2860 Loc = getExprLoc();
2861 R1 = getSourceRange();
2862 return true;
2863
2864 case PseudoObjectExprClass: {
2865 const auto *POE = cast<PseudoObjectExpr>(this);
2866
2867 // For some syntactic forms, we should always warn.
2868 if (isa<ObjCPropertyRefExpr, ObjCSubscriptRefExpr>(
2869 POE->getSyntacticForm())) {
2870 WarnE = this;
2871 Loc = getExprLoc();
2872 R1 = getSourceRange();
2873 return true;
2874 }
2875
2876 // For others, we should never warn.
2877 if (auto *BO = dyn_cast<BinaryOperator>(POE->getSyntacticForm()))
2878 if (BO->isAssignmentOp())
2879 return false;
2880 if (auto *UO = dyn_cast<UnaryOperator>(POE->getSyntacticForm()))
2881 if (UO->isIncrementDecrementOp())
2882 return false;
2883
2884 // Otherwise, warn if the result expression would warn.
2885 const Expr *Result = POE->getResultExpr();
2886 return Result && Result->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2887 }
2888
2889 case StmtExprClass: {
2890 // Statement exprs don't logically have side effects themselves, but are
2891 // sometimes used in macros in ways that give them a type that is unused.
2892 // For example ({ blah; foo(); }) will end up with a type if foo has a type.
2893 // however, if the result of the stmt expr is dead, we don't want to emit a
2894 // warning.
2895 const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt();
2896 if (!CS->body_empty()) {
2897 if (const Expr *E = dyn_cast<Expr>(CS->body_back()))
2898 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2899 if (const LabelStmt *Label = dyn_cast<LabelStmt>(CS->body_back()))
2900 if (const Expr *E = dyn_cast<Expr>(Label->getSubStmt()))
2901 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2902 }
2903
2904 if (getType()->isVoidType())
2905 return false;
2906 WarnE = this;
2907 Loc = cast<StmtExpr>(this)->getLParenLoc();
2908 R1 = getSourceRange();
2909 return true;
2910 }
2911 case CXXFunctionalCastExprClass:
2912 case CStyleCastExprClass: {
2913 // Ignore an explicit cast to void, except in C++98 if the operand is a
2914 // volatile glvalue for which we would trigger an implicit read in any
2915 // other language mode. (Such an implicit read always happens as part of
2916 // the lvalue conversion in C, and happens in C++ for expressions of all
2917 // forms where it seems likely the user intended to trigger a volatile
2918 // load.)
2919 const CastExpr *CE = cast<CastExpr>(this);
2920 const Expr *SubE = CE->getSubExpr()->IgnoreParens();
2921 if (CE->getCastKind() == CK_ToVoid) {
2922 if (Ctx.getLangOpts().CPlusPlus && !Ctx.getLangOpts().CPlusPlus11 &&
2923 SubE->isReadIfDiscardedInCPlusPlus11()) {
2924 // Suppress the "unused value" warning for idiomatic usage of
2925 // '(void)var;' used to suppress "unused variable" warnings.
2926 if (auto *DRE = dyn_cast<DeclRefExpr>(SubE))
2927 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
2928 if (!VD->isExternallyVisible())
2929 return false;
2930
2931 // The lvalue-to-rvalue conversion would have no effect for an array.
2932 // It's implausible that the programmer expected this to result in a
2933 // volatile array load, so don't warn.
2934 if (SubE->getType()->isArrayType())
2935 return false;
2936
2937 return SubE->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2938 }
2939 return false;
2940 }
2941
2942 // If this is a cast to a constructor conversion, check the operand.
2943 // Otherwise, the result of the cast is unused.
2944 if (CE->getCastKind() == CK_ConstructorConversion)
2945 return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2946 if (CE->getCastKind() == CK_Dependent)
2947 return false;
2948
2949 WarnE = this;
2950 if (const CXXFunctionalCastExpr *CXXCE =
2951 dyn_cast<CXXFunctionalCastExpr>(this)) {
2952 Loc = CXXCE->getBeginLoc();
2953 R1 = CXXCE->getSubExpr()->getSourceRange();
2954 } else {
2955 const CStyleCastExpr *CStyleCE = cast<CStyleCastExpr>(this);
2956 Loc = CStyleCE->getLParenLoc();
2957 R1 = CStyleCE->getSubExpr()->getSourceRange();
2958 }
2959 return true;
2960 }
2961 case ImplicitCastExprClass: {
2962 const CastExpr *ICE = cast<ImplicitCastExpr>(this);
2963
2964 // lvalue-to-rvalue conversion on a volatile lvalue is a side-effect.
2965 if (ICE->getCastKind() == CK_LValueToRValue &&
2966 ICE->getSubExpr()->getType().isVolatileQualified())
2967 return false;
2968
2969 return ICE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2970 }
2971 case CXXDefaultArgExprClass:
2972 return (cast<CXXDefaultArgExpr>(this)
2973 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
2974 case CXXDefaultInitExprClass:
2975 return (cast<CXXDefaultInitExpr>(this)
2976 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
2977
2978 case CXXNewExprClass:
2979 // FIXME: In theory, there might be new expressions that don't have side
2980 // effects (e.g. a placement new with an uninitialized POD).
2981 case CXXDeleteExprClass:
2982 return false;
2983 case MaterializeTemporaryExprClass:
2984 return cast<MaterializeTemporaryExpr>(this)
2985 ->getSubExpr()
2986 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2987 case CXXBindTemporaryExprClass:
2988 return cast<CXXBindTemporaryExpr>(this)->getSubExpr()
2989 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2990 case ExprWithCleanupsClass:
2991 return cast<ExprWithCleanups>(this)->getSubExpr()
2992 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2993 case OpaqueValueExprClass:
2994 return cast<OpaqueValueExpr>(this)->getSourceExpr()->isUnusedResultAWarning(
2995 WarnE, Loc, R1, R2, Ctx);
2996 }
2997 }
2998
2999 /// isOBJCGCCandidate - Check if an expression is objc gc'able.
3000 /// returns true, if it is; false otherwise.
isOBJCGCCandidate(ASTContext & Ctx) const3001 bool Expr::isOBJCGCCandidate(ASTContext &Ctx) const {
3002 const Expr *E = IgnoreParens();
3003 switch (E->getStmtClass()) {
3004 default:
3005 return false;
3006 case ObjCIvarRefExprClass:
3007 return true;
3008 case Expr::UnaryOperatorClass:
3009 return cast<UnaryOperator>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
3010 case ImplicitCastExprClass:
3011 return cast<ImplicitCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
3012 case MaterializeTemporaryExprClass:
3013 return cast<MaterializeTemporaryExpr>(E)->getSubExpr()->isOBJCGCCandidate(
3014 Ctx);
3015 case CStyleCastExprClass:
3016 return cast<CStyleCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
3017 case DeclRefExprClass: {
3018 const Decl *D = cast<DeclRefExpr>(E)->getDecl();
3019
3020 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3021 if (VD->hasGlobalStorage())
3022 return true;
3023 QualType T = VD->getType();
3024 // dereferencing to a pointer is always a gc'able candidate,
3025 // unless it is __weak.
3026 return T->isPointerType() &&
3027 (Ctx.getObjCGCAttrKind(T) != Qualifiers::Weak);
3028 }
3029 return false;
3030 }
3031 case MemberExprClass: {
3032 const MemberExpr *M = cast<MemberExpr>(E);
3033 return M->getBase()->isOBJCGCCandidate(Ctx);
3034 }
3035 case ArraySubscriptExprClass:
3036 return cast<ArraySubscriptExpr>(E)->getBase()->isOBJCGCCandidate(Ctx);
3037 }
3038 }
3039
isBoundMemberFunction(ASTContext & Ctx) const3040 bool Expr::isBoundMemberFunction(ASTContext &Ctx) const {
3041 if (isTypeDependent())
3042 return false;
3043 return ClassifyLValue(Ctx) == Expr::LV_MemberFunction;
3044 }
3045
findBoundMemberType(const Expr * expr)3046 QualType Expr::findBoundMemberType(const Expr *expr) {
3047 assert(expr->hasPlaceholderType(BuiltinType::BoundMember));
3048
3049 // Bound member expressions are always one of these possibilities:
3050 // x->m x.m x->*y x.*y
3051 // (possibly parenthesized)
3052
3053 expr = expr->IgnoreParens();
3054 if (const MemberExpr *mem = dyn_cast<MemberExpr>(expr)) {
3055 assert(isa<CXXMethodDecl>(mem->getMemberDecl()));
3056 return mem->getMemberDecl()->getType();
3057 }
3058
3059 if (const BinaryOperator *op = dyn_cast<BinaryOperator>(expr)) {
3060 QualType type = op->getRHS()->getType()->castAs<MemberPointerType>()
3061 ->getPointeeType();
3062 assert(type->isFunctionType());
3063 return type;
3064 }
3065
3066 assert(isa<UnresolvedMemberExpr>(expr) || isa<CXXPseudoDestructorExpr>(expr));
3067 return QualType();
3068 }
3069
IgnoreImpCasts()3070 Expr *Expr::IgnoreImpCasts() {
3071 return IgnoreExprNodes(this, IgnoreImplicitCastsSingleStep);
3072 }
3073
IgnoreCasts()3074 Expr *Expr::IgnoreCasts() {
3075 return IgnoreExprNodes(this, IgnoreCastsSingleStep);
3076 }
3077
IgnoreImplicit()3078 Expr *Expr::IgnoreImplicit() {
3079 return IgnoreExprNodes(this, IgnoreImplicitSingleStep);
3080 }
3081
IgnoreImplicitAsWritten()3082 Expr *Expr::IgnoreImplicitAsWritten() {
3083 return IgnoreExprNodes(this, IgnoreImplicitAsWrittenSingleStep);
3084 }
3085
IgnoreParens()3086 Expr *Expr::IgnoreParens() {
3087 return IgnoreExprNodes(this, IgnoreParensSingleStep);
3088 }
3089
IgnoreParenImpCasts()3090 Expr *Expr::IgnoreParenImpCasts() {
3091 return IgnoreExprNodes(this, IgnoreParensSingleStep,
3092 IgnoreImplicitCastsExtraSingleStep);
3093 }
3094
IgnoreParenCasts()3095 Expr *Expr::IgnoreParenCasts() {
3096 return IgnoreExprNodes(this, IgnoreParensSingleStep, IgnoreCastsSingleStep);
3097 }
3098
IgnoreConversionOperatorSingleStep()3099 Expr *Expr::IgnoreConversionOperatorSingleStep() {
3100 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(this)) {
3101 if (isa_and_nonnull<CXXConversionDecl>(MCE->getMethodDecl()))
3102 return MCE->getImplicitObjectArgument();
3103 }
3104 return this;
3105 }
3106
IgnoreParenLValueCasts()3107 Expr *Expr::IgnoreParenLValueCasts() {
3108 return IgnoreExprNodes(this, IgnoreParensSingleStep,
3109 IgnoreLValueCastsSingleStep);
3110 }
3111
IgnoreParenBaseCasts()3112 Expr *Expr::IgnoreParenBaseCasts() {
3113 return IgnoreExprNodes(this, IgnoreParensSingleStep,
3114 IgnoreBaseCastsSingleStep);
3115 }
3116
IgnoreParenNoopCasts(const ASTContext & Ctx)3117 Expr *Expr::IgnoreParenNoopCasts(const ASTContext &Ctx) {
3118 auto IgnoreNoopCastsSingleStep = [&Ctx](Expr *E) {
3119 if (auto *CE = dyn_cast<CastExpr>(E)) {
3120 // We ignore integer <-> casts that are of the same width, ptr<->ptr and
3121 // ptr<->int casts of the same width. We also ignore all identity casts.
3122 Expr *SubExpr = CE->getSubExpr();
3123 bool IsIdentityCast =
3124 Ctx.hasSameUnqualifiedType(E->getType(), SubExpr->getType());
3125 bool IsSameWidthCast = (E->getType()->isPointerType() ||
3126 E->getType()->isIntegralType(Ctx)) &&
3127 (SubExpr->getType()->isPointerType() ||
3128 SubExpr->getType()->isIntegralType(Ctx)) &&
3129 (Ctx.getTypeSize(E->getType()) ==
3130 Ctx.getTypeSize(SubExpr->getType()));
3131
3132 if (IsIdentityCast || IsSameWidthCast)
3133 return SubExpr;
3134 } else if (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
3135 return NTTP->getReplacement();
3136
3137 return E;
3138 };
3139 return IgnoreExprNodes(this, IgnoreParensSingleStep,
3140 IgnoreNoopCastsSingleStep);
3141 }
3142
IgnoreUnlessSpelledInSource()3143 Expr *Expr::IgnoreUnlessSpelledInSource() {
3144 auto IgnoreImplicitConstructorSingleStep = [](Expr *E) {
3145 if (auto *Cast = dyn_cast<CXXFunctionalCastExpr>(E)) {
3146 auto *SE = Cast->getSubExpr();
3147 if (SE->getSourceRange() == E->getSourceRange())
3148 return SE;
3149 }
3150
3151 if (auto *C = dyn_cast<CXXConstructExpr>(E)) {
3152 auto NumArgs = C->getNumArgs();
3153 if (NumArgs == 1 ||
3154 (NumArgs > 1 && isa<CXXDefaultArgExpr>(C->getArg(1)))) {
3155 Expr *A = C->getArg(0);
3156 if (A->getSourceRange() == E->getSourceRange() || C->isElidable())
3157 return A;
3158 }
3159 }
3160 return E;
3161 };
3162 auto IgnoreImplicitMemberCallSingleStep = [](Expr *E) {
3163 if (auto *C = dyn_cast<CXXMemberCallExpr>(E)) {
3164 Expr *ExprNode = C->getImplicitObjectArgument();
3165 if (ExprNode->getSourceRange() == E->getSourceRange()) {
3166 return ExprNode;
3167 }
3168 if (auto *PE = dyn_cast<ParenExpr>(ExprNode)) {
3169 if (PE->getSourceRange() == C->getSourceRange()) {
3170 return cast<Expr>(PE);
3171 }
3172 }
3173 ExprNode = ExprNode->IgnoreParenImpCasts();
3174 if (ExprNode->getSourceRange() == E->getSourceRange())
3175 return ExprNode;
3176 }
3177 return E;
3178 };
3179 return IgnoreExprNodes(
3180 this, IgnoreImplicitSingleStep, IgnoreImplicitCastsExtraSingleStep,
3181 IgnoreParensOnlySingleStep, IgnoreImplicitConstructorSingleStep,
3182 IgnoreImplicitMemberCallSingleStep);
3183 }
3184
isDefaultArgument() const3185 bool Expr::isDefaultArgument() const {
3186 const Expr *E = this;
3187 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
3188 E = M->getSubExpr();
3189
3190 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3191 E = ICE->getSubExprAsWritten();
3192
3193 return isa<CXXDefaultArgExpr>(E);
3194 }
3195
3196 /// Skip over any no-op casts and any temporary-binding
3197 /// expressions.
skipTemporaryBindingsNoOpCastsAndParens(const Expr * E)3198 static const Expr *skipTemporaryBindingsNoOpCastsAndParens(const Expr *E) {
3199 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
3200 E = M->getSubExpr();
3201
3202 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3203 if (ICE->getCastKind() == CK_NoOp)
3204 E = ICE->getSubExpr();
3205 else
3206 break;
3207 }
3208
3209 while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
3210 E = BE->getSubExpr();
3211
3212 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3213 if (ICE->getCastKind() == CK_NoOp)
3214 E = ICE->getSubExpr();
3215 else
3216 break;
3217 }
3218
3219 return E->IgnoreParens();
3220 }
3221
3222 /// isTemporaryObject - Determines if this expression produces a
3223 /// temporary of the given class type.
isTemporaryObject(ASTContext & C,const CXXRecordDecl * TempTy) const3224 bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const {
3225 if (!C.hasSameUnqualifiedType(getType(), C.getTypeDeclType(TempTy)))
3226 return false;
3227
3228 const Expr *E = skipTemporaryBindingsNoOpCastsAndParens(this);
3229
3230 // Temporaries are by definition pr-values of class type.
3231 if (!E->Classify(C).isPRValue()) {
3232 // In this context, property reference is a message call and is pr-value.
3233 if (!isa<ObjCPropertyRefExpr>(E))
3234 return false;
3235 }
3236
3237 // Black-list a few cases which yield pr-values of class type that don't
3238 // refer to temporaries of that type:
3239
3240 // - implicit derived-to-base conversions
3241 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3242 switch (ICE->getCastKind()) {
3243 case CK_DerivedToBase:
3244 case CK_UncheckedDerivedToBase:
3245 return false;
3246 default:
3247 break;
3248 }
3249 }
3250
3251 // - member expressions (all)
3252 if (isa<MemberExpr>(E))
3253 return false;
3254
3255 if (const auto *BO = dyn_cast<BinaryOperator>(E))
3256 if (BO->isPtrMemOp())
3257 return false;
3258
3259 // - opaque values (all)
3260 if (isa<OpaqueValueExpr>(E))
3261 return false;
3262
3263 return true;
3264 }
3265
isImplicitCXXThis() const3266 bool Expr::isImplicitCXXThis() const {
3267 const Expr *E = this;
3268
3269 // Strip away parentheses and casts we don't care about.
3270 while (true) {
3271 if (const ParenExpr *Paren = dyn_cast<ParenExpr>(E)) {
3272 E = Paren->getSubExpr();
3273 continue;
3274 }
3275
3276 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3277 if (ICE->getCastKind() == CK_NoOp ||
3278 ICE->getCastKind() == CK_LValueToRValue ||
3279 ICE->getCastKind() == CK_DerivedToBase ||
3280 ICE->getCastKind() == CK_UncheckedDerivedToBase) {
3281 E = ICE->getSubExpr();
3282 continue;
3283 }
3284 }
3285
3286 if (const UnaryOperator* UnOp = dyn_cast<UnaryOperator>(E)) {
3287 if (UnOp->getOpcode() == UO_Extension) {
3288 E = UnOp->getSubExpr();
3289 continue;
3290 }
3291 }
3292
3293 if (const MaterializeTemporaryExpr *M
3294 = dyn_cast<MaterializeTemporaryExpr>(E)) {
3295 E = M->getSubExpr();
3296 continue;
3297 }
3298
3299 break;
3300 }
3301
3302 if (const CXXThisExpr *This = dyn_cast<CXXThisExpr>(E))
3303 return This->isImplicit();
3304
3305 return false;
3306 }
3307
3308 /// hasAnyTypeDependentArguments - Determines if any of the expressions
3309 /// in Exprs is type-dependent.
hasAnyTypeDependentArguments(ArrayRef<Expr * > Exprs)3310 bool Expr::hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs) {
3311 for (unsigned I = 0; I < Exprs.size(); ++I)
3312 if (Exprs[I]->isTypeDependent())
3313 return true;
3314
3315 return false;
3316 }
3317
isConstantInitializer(ASTContext & Ctx,bool IsForRef,const Expr ** Culprit) const3318 bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef,
3319 const Expr **Culprit) const {
3320 assert(!isValueDependent() &&
3321 "Expression evaluator can't be called on a dependent expression.");
3322
3323 // This function is attempting whether an expression is an initializer
3324 // which can be evaluated at compile-time. It very closely parallels
3325 // ConstExprEmitter in CGExprConstant.cpp; if they don't match, it
3326 // will lead to unexpected results. Like ConstExprEmitter, it falls back
3327 // to isEvaluatable most of the time.
3328 //
3329 // If we ever capture reference-binding directly in the AST, we can
3330 // kill the second parameter.
3331
3332 if (IsForRef) {
3333 if (auto *EWC = dyn_cast<ExprWithCleanups>(this))
3334 return EWC->getSubExpr()->isConstantInitializer(Ctx, true, Culprit);
3335 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(this))
3336 return MTE->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
3337 EvalResult Result;
3338 if (EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects)
3339 return true;
3340 if (Culprit)
3341 *Culprit = this;
3342 return false;
3343 }
3344
3345 switch (getStmtClass()) {
3346 default: break;
3347 case Stmt::ExprWithCleanupsClass:
3348 return cast<ExprWithCleanups>(this)->getSubExpr()->isConstantInitializer(
3349 Ctx, IsForRef, Culprit);
3350 case StringLiteralClass:
3351 case ObjCEncodeExprClass:
3352 return true;
3353 case CXXTemporaryObjectExprClass:
3354 case CXXConstructExprClass: {
3355 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
3356
3357 if (CE->getConstructor()->isTrivial() &&
3358 CE->getConstructor()->getParent()->hasTrivialDestructor()) {
3359 // Trivial default constructor
3360 if (!CE->getNumArgs()) return true;
3361
3362 // Trivial copy constructor
3363 assert(CE->getNumArgs() == 1 && "trivial ctor with > 1 argument");
3364 return CE->getArg(0)->isConstantInitializer(Ctx, false, Culprit);
3365 }
3366
3367 break;
3368 }
3369 case ConstantExprClass: {
3370 // FIXME: We should be able to return "true" here, but it can lead to extra
3371 // error messages. E.g. in Sema/array-init.c.
3372 const Expr *Exp = cast<ConstantExpr>(this)->getSubExpr();
3373 return Exp->isConstantInitializer(Ctx, false, Culprit);
3374 }
3375 case CompoundLiteralExprClass: {
3376 // This handles gcc's extension that allows global initializers like
3377 // "struct x {int x;} x = (struct x) {};".
3378 // FIXME: This accepts other cases it shouldn't!
3379 const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer();
3380 return Exp->isConstantInitializer(Ctx, false, Culprit);
3381 }
3382 case DesignatedInitUpdateExprClass: {
3383 const DesignatedInitUpdateExpr *DIUE = cast<DesignatedInitUpdateExpr>(this);
3384 return DIUE->getBase()->isConstantInitializer(Ctx, false, Culprit) &&
3385 DIUE->getUpdater()->isConstantInitializer(Ctx, false, Culprit);
3386 }
3387 case InitListExprClass: {
3388 // C++ [dcl.init.aggr]p2:
3389 // The elements of an aggregate are:
3390 // - for an array, the array elements in increasing subscript order, or
3391 // - for a class, the direct base classes in declaration order, followed
3392 // by the direct non-static data members (11.4) that are not members of
3393 // an anonymous union, in declaration order.
3394 const InitListExpr *ILE = cast<InitListExpr>(this);
3395 assert(ILE->isSemanticForm() && "InitListExpr must be in semantic form");
3396
3397 if (ILE->isTransparent())
3398 return ILE->getInit(0)->isConstantInitializer(Ctx, false, Culprit);
3399
3400 if (ILE->getType()->isArrayType()) {
3401 unsigned numInits = ILE->getNumInits();
3402 for (unsigned i = 0; i < numInits; i++) {
3403 if (!ILE->getInit(i)->isConstantInitializer(Ctx, false, Culprit))
3404 return false;
3405 }
3406 return true;
3407 }
3408
3409 if (ILE->getType()->isRecordType()) {
3410 unsigned ElementNo = 0;
3411 RecordDecl *RD = ILE->getType()->castAs<RecordType>()->getDecl();
3412
3413 // In C++17, bases were added to the list of members used by aggregate
3414 // initialization.
3415 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3416 for (unsigned i = 0, e = CXXRD->getNumBases(); i < e; i++) {
3417 if (ElementNo < ILE->getNumInits()) {
3418 const Expr *Elt = ILE->getInit(ElementNo++);
3419 if (!Elt->isConstantInitializer(Ctx, false, Culprit))
3420 return false;
3421 }
3422 }
3423 }
3424
3425 for (const auto *Field : RD->fields()) {
3426 // If this is a union, skip all the fields that aren't being initialized.
3427 if (RD->isUnion() && ILE->getInitializedFieldInUnion() != Field)
3428 continue;
3429
3430 // Don't emit anonymous bitfields, they just affect layout.
3431 if (Field->isUnnamedBitField())
3432 continue;
3433
3434 if (ElementNo < ILE->getNumInits()) {
3435 const Expr *Elt = ILE->getInit(ElementNo++);
3436 if (Field->isBitField()) {
3437 // Bitfields have to evaluate to an integer.
3438 EvalResult Result;
3439 if (!Elt->EvaluateAsInt(Result, Ctx)) {
3440 if (Culprit)
3441 *Culprit = Elt;
3442 return false;
3443 }
3444 } else {
3445 bool RefType = Field->getType()->isReferenceType();
3446 if (!Elt->isConstantInitializer(Ctx, RefType, Culprit))
3447 return false;
3448 }
3449 }
3450 }
3451 return true;
3452 }
3453
3454 break;
3455 }
3456 case ImplicitValueInitExprClass:
3457 case NoInitExprClass:
3458 return true;
3459 case ParenExprClass:
3460 return cast<ParenExpr>(this)->getSubExpr()
3461 ->isConstantInitializer(Ctx, IsForRef, Culprit);
3462 case GenericSelectionExprClass:
3463 return cast<GenericSelectionExpr>(this)->getResultExpr()
3464 ->isConstantInitializer(Ctx, IsForRef, Culprit);
3465 case ChooseExprClass:
3466 if (cast<ChooseExpr>(this)->isConditionDependent()) {
3467 if (Culprit)
3468 *Culprit = this;
3469 return false;
3470 }
3471 return cast<ChooseExpr>(this)->getChosenSubExpr()
3472 ->isConstantInitializer(Ctx, IsForRef, Culprit);
3473 case UnaryOperatorClass: {
3474 const UnaryOperator* Exp = cast<UnaryOperator>(this);
3475 if (Exp->getOpcode() == UO_Extension)
3476 return Exp->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
3477 break;
3478 }
3479 case PackIndexingExprClass: {
3480 return cast<PackIndexingExpr>(this)
3481 ->getSelectedExpr()
3482 ->isConstantInitializer(Ctx, false, Culprit);
3483 }
3484 case CXXFunctionalCastExprClass:
3485 case CXXStaticCastExprClass:
3486 case ImplicitCastExprClass:
3487 case CStyleCastExprClass:
3488 case ObjCBridgedCastExprClass:
3489 case CXXDynamicCastExprClass:
3490 case CXXReinterpretCastExprClass:
3491 case CXXAddrspaceCastExprClass:
3492 case CXXConstCastExprClass: {
3493 const CastExpr *CE = cast<CastExpr>(this);
3494
3495 // Handle misc casts we want to ignore.
3496 if (CE->getCastKind() == CK_NoOp ||
3497 CE->getCastKind() == CK_LValueToRValue ||
3498 CE->getCastKind() == CK_ToUnion ||
3499 CE->getCastKind() == CK_ConstructorConversion ||
3500 CE->getCastKind() == CK_NonAtomicToAtomic ||
3501 CE->getCastKind() == CK_AtomicToNonAtomic ||
3502 CE->getCastKind() == CK_NullToPointer ||
3503 CE->getCastKind() == CK_IntToOCLSampler)
3504 return CE->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
3505
3506 break;
3507 }
3508 case MaterializeTemporaryExprClass:
3509 return cast<MaterializeTemporaryExpr>(this)
3510 ->getSubExpr()
3511 ->isConstantInitializer(Ctx, false, Culprit);
3512
3513 case SubstNonTypeTemplateParmExprClass:
3514 return cast<SubstNonTypeTemplateParmExpr>(this)->getReplacement()
3515 ->isConstantInitializer(Ctx, false, Culprit);
3516 case CXXDefaultArgExprClass:
3517 return cast<CXXDefaultArgExpr>(this)->getExpr()
3518 ->isConstantInitializer(Ctx, false, Culprit);
3519 case CXXDefaultInitExprClass:
3520 return cast<CXXDefaultInitExpr>(this)->getExpr()
3521 ->isConstantInitializer(Ctx, false, Culprit);
3522 }
3523 // Allow certain forms of UB in constant initializers: signed integer
3524 // overflow and floating-point division by zero. We'll give a warning on
3525 // these, but they're common enough that we have to accept them.
3526 if (isEvaluatable(Ctx, SE_AllowUndefinedBehavior))
3527 return true;
3528 if (Culprit)
3529 *Culprit = this;
3530 return false;
3531 }
3532
isBuiltinAssumeFalse(const ASTContext & Ctx) const3533 bool CallExpr::isBuiltinAssumeFalse(const ASTContext &Ctx) const {
3534 unsigned BuiltinID = getBuiltinCallee();
3535 if (BuiltinID != Builtin::BI__assume &&
3536 BuiltinID != Builtin::BI__builtin_assume)
3537 return false;
3538
3539 const Expr* Arg = getArg(0);
3540 bool ArgVal;
3541 return !Arg->isValueDependent() &&
3542 Arg->EvaluateAsBooleanCondition(ArgVal, Ctx) && !ArgVal;
3543 }
3544
isCallToStdMove() const3545 bool CallExpr::isCallToStdMove() const {
3546 return getBuiltinCallee() == Builtin::BImove;
3547 }
3548
3549 namespace {
3550 /// Look for any side effects within a Stmt.
3551 class SideEffectFinder : public ConstEvaluatedExprVisitor<SideEffectFinder> {
3552 typedef ConstEvaluatedExprVisitor<SideEffectFinder> Inherited;
3553 const bool IncludePossibleEffects;
3554 bool HasSideEffects;
3555
3556 public:
SideEffectFinder(const ASTContext & Context,bool IncludePossible)3557 explicit SideEffectFinder(const ASTContext &Context, bool IncludePossible)
3558 : Inherited(Context),
3559 IncludePossibleEffects(IncludePossible), HasSideEffects(false) { }
3560
hasSideEffects() const3561 bool hasSideEffects() const { return HasSideEffects; }
3562
VisitDecl(const Decl * D)3563 void VisitDecl(const Decl *D) {
3564 if (!D)
3565 return;
3566
3567 // We assume the caller checks subexpressions (eg, the initializer, VLA
3568 // bounds) for side-effects on our behalf.
3569 if (auto *VD = dyn_cast<VarDecl>(D)) {
3570 // Registering a destructor is a side-effect.
3571 if (IncludePossibleEffects && VD->isThisDeclarationADefinition() &&
3572 VD->needsDestruction(Context))
3573 HasSideEffects = true;
3574 }
3575 }
3576
VisitDeclStmt(const DeclStmt * DS)3577 void VisitDeclStmt(const DeclStmt *DS) {
3578 for (auto *D : DS->decls())
3579 VisitDecl(D);
3580 Inherited::VisitDeclStmt(DS);
3581 }
3582
VisitExpr(const Expr * E)3583 void VisitExpr(const Expr *E) {
3584 if (!HasSideEffects &&
3585 E->HasSideEffects(Context, IncludePossibleEffects))
3586 HasSideEffects = true;
3587 }
3588 };
3589 }
3590
HasSideEffects(const ASTContext & Ctx,bool IncludePossibleEffects) const3591 bool Expr::HasSideEffects(const ASTContext &Ctx,
3592 bool IncludePossibleEffects) const {
3593 // In circumstances where we care about definite side effects instead of
3594 // potential side effects, we want to ignore expressions that are part of a
3595 // macro expansion as a potential side effect.
3596 if (!IncludePossibleEffects && getExprLoc().isMacroID())
3597 return false;
3598
3599 switch (getStmtClass()) {
3600 case NoStmtClass:
3601 #define ABSTRACT_STMT(Type)
3602 #define STMT(Type, Base) case Type##Class:
3603 #define EXPR(Type, Base)
3604 #include "clang/AST/StmtNodes.inc"
3605 llvm_unreachable("unexpected Expr kind");
3606
3607 case DependentScopeDeclRefExprClass:
3608 case CXXUnresolvedConstructExprClass:
3609 case CXXDependentScopeMemberExprClass:
3610 case UnresolvedLookupExprClass:
3611 case UnresolvedMemberExprClass:
3612 case PackExpansionExprClass:
3613 case SubstNonTypeTemplateParmPackExprClass:
3614 case FunctionParmPackExprClass:
3615 case RecoveryExprClass:
3616 case CXXFoldExprClass:
3617 // Make a conservative assumption for dependent nodes.
3618 return IncludePossibleEffects;
3619
3620 case DeclRefExprClass:
3621 case ObjCIvarRefExprClass:
3622 case PredefinedExprClass:
3623 case IntegerLiteralClass:
3624 case FixedPointLiteralClass:
3625 case FloatingLiteralClass:
3626 case ImaginaryLiteralClass:
3627 case StringLiteralClass:
3628 case CharacterLiteralClass:
3629 case OffsetOfExprClass:
3630 case ImplicitValueInitExprClass:
3631 case UnaryExprOrTypeTraitExprClass:
3632 case AddrLabelExprClass:
3633 case GNUNullExprClass:
3634 case ArrayInitIndexExprClass:
3635 case NoInitExprClass:
3636 case CXXBoolLiteralExprClass:
3637 case CXXNullPtrLiteralExprClass:
3638 case CXXThisExprClass:
3639 case CXXScalarValueInitExprClass:
3640 case TypeTraitExprClass:
3641 case ArrayTypeTraitExprClass:
3642 case ExpressionTraitExprClass:
3643 case CXXNoexceptExprClass:
3644 case SizeOfPackExprClass:
3645 case ObjCStringLiteralClass:
3646 case ObjCEncodeExprClass:
3647 case ObjCBoolLiteralExprClass:
3648 case ObjCAvailabilityCheckExprClass:
3649 case CXXUuidofExprClass:
3650 case OpaqueValueExprClass:
3651 case SourceLocExprClass:
3652 case EmbedExprClass:
3653 case ConceptSpecializationExprClass:
3654 case RequiresExprClass:
3655 case SYCLUniqueStableNameExprClass:
3656 case PackIndexingExprClass:
3657 case HLSLOutArgExprClass:
3658 case OpenACCAsteriskSizeExprClass:
3659 // These never have a side-effect.
3660 return false;
3661
3662 case ConstantExprClass:
3663 // FIXME: Move this into the "return false;" block above.
3664 return cast<ConstantExpr>(this)->getSubExpr()->HasSideEffects(
3665 Ctx, IncludePossibleEffects);
3666
3667 case CallExprClass:
3668 case CXXOperatorCallExprClass:
3669 case CXXMemberCallExprClass:
3670 case CUDAKernelCallExprClass:
3671 case UserDefinedLiteralClass: {
3672 // We don't know a call definitely has side effects, except for calls
3673 // to pure/const functions that definitely don't.
3674 // If the call itself is considered side-effect free, check the operands.
3675 const Decl *FD = cast<CallExpr>(this)->getCalleeDecl();
3676 bool IsPure = FD && (FD->hasAttr<ConstAttr>() || FD->hasAttr<PureAttr>());
3677 if (IsPure || !IncludePossibleEffects)
3678 break;
3679 return true;
3680 }
3681
3682 case BlockExprClass:
3683 case CXXBindTemporaryExprClass:
3684 if (!IncludePossibleEffects)
3685 break;
3686 return true;
3687
3688 case MSPropertyRefExprClass:
3689 case MSPropertySubscriptExprClass:
3690 case CompoundAssignOperatorClass:
3691 case VAArgExprClass:
3692 case AtomicExprClass:
3693 case CXXThrowExprClass:
3694 case CXXNewExprClass:
3695 case CXXDeleteExprClass:
3696 case CoawaitExprClass:
3697 case DependentCoawaitExprClass:
3698 case CoyieldExprClass:
3699 // These always have a side-effect.
3700 return true;
3701
3702 case StmtExprClass: {
3703 // StmtExprs have a side-effect if any substatement does.
3704 SideEffectFinder Finder(Ctx, IncludePossibleEffects);
3705 Finder.Visit(cast<StmtExpr>(this)->getSubStmt());
3706 return Finder.hasSideEffects();
3707 }
3708
3709 case ExprWithCleanupsClass:
3710 if (IncludePossibleEffects)
3711 if (cast<ExprWithCleanups>(this)->cleanupsHaveSideEffects())
3712 return true;
3713 break;
3714
3715 case ParenExprClass:
3716 case ArraySubscriptExprClass:
3717 case MatrixSubscriptExprClass:
3718 case ArraySectionExprClass:
3719 case OMPArrayShapingExprClass:
3720 case OMPIteratorExprClass:
3721 case MemberExprClass:
3722 case ConditionalOperatorClass:
3723 case BinaryConditionalOperatorClass:
3724 case CompoundLiteralExprClass:
3725 case ExtVectorElementExprClass:
3726 case DesignatedInitExprClass:
3727 case DesignatedInitUpdateExprClass:
3728 case ArrayInitLoopExprClass:
3729 case ParenListExprClass:
3730 case CXXPseudoDestructorExprClass:
3731 case CXXRewrittenBinaryOperatorClass:
3732 case CXXStdInitializerListExprClass:
3733 case SubstNonTypeTemplateParmExprClass:
3734 case MaterializeTemporaryExprClass:
3735 case ShuffleVectorExprClass:
3736 case ConvertVectorExprClass:
3737 case AsTypeExprClass:
3738 case CXXParenListInitExprClass:
3739 // These have a side-effect if any subexpression does.
3740 break;
3741
3742 case UnaryOperatorClass:
3743 if (cast<UnaryOperator>(this)->isIncrementDecrementOp())
3744 return true;
3745 break;
3746
3747 case BinaryOperatorClass:
3748 if (cast<BinaryOperator>(this)->isAssignmentOp())
3749 return true;
3750 break;
3751
3752 case InitListExprClass:
3753 // FIXME: The children for an InitListExpr doesn't include the array filler.
3754 if (const Expr *E = cast<InitListExpr>(this)->getArrayFiller())
3755 if (E->HasSideEffects(Ctx, IncludePossibleEffects))
3756 return true;
3757 break;
3758
3759 case GenericSelectionExprClass:
3760 return cast<GenericSelectionExpr>(this)->getResultExpr()->
3761 HasSideEffects(Ctx, IncludePossibleEffects);
3762
3763 case ChooseExprClass:
3764 return cast<ChooseExpr>(this)->getChosenSubExpr()->HasSideEffects(
3765 Ctx, IncludePossibleEffects);
3766
3767 case CXXDefaultArgExprClass:
3768 return cast<CXXDefaultArgExpr>(this)->getExpr()->HasSideEffects(
3769 Ctx, IncludePossibleEffects);
3770
3771 case CXXDefaultInitExprClass: {
3772 const FieldDecl *FD = cast<CXXDefaultInitExpr>(this)->getField();
3773 if (const Expr *E = FD->getInClassInitializer())
3774 return E->HasSideEffects(Ctx, IncludePossibleEffects);
3775 // If we've not yet parsed the initializer, assume it has side-effects.
3776 return true;
3777 }
3778
3779 case CXXDynamicCastExprClass: {
3780 // A dynamic_cast expression has side-effects if it can throw.
3781 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(this);
3782 if (DCE->getTypeAsWritten()->isReferenceType() &&
3783 DCE->getCastKind() == CK_Dynamic)
3784 return true;
3785 }
3786 [[fallthrough]];
3787 case ImplicitCastExprClass:
3788 case CStyleCastExprClass:
3789 case CXXStaticCastExprClass:
3790 case CXXReinterpretCastExprClass:
3791 case CXXConstCastExprClass:
3792 case CXXAddrspaceCastExprClass:
3793 case CXXFunctionalCastExprClass:
3794 case BuiltinBitCastExprClass: {
3795 // While volatile reads are side-effecting in both C and C++, we treat them
3796 // as having possible (not definite) side-effects. This allows idiomatic
3797 // code to behave without warning, such as sizeof(*v) for a volatile-
3798 // qualified pointer.
3799 if (!IncludePossibleEffects)
3800 break;
3801
3802 const CastExpr *CE = cast<CastExpr>(this);
3803 if (CE->getCastKind() == CK_LValueToRValue &&
3804 CE->getSubExpr()->getType().isVolatileQualified())
3805 return true;
3806 break;
3807 }
3808
3809 case CXXTypeidExprClass: {
3810 const auto *TE = cast<CXXTypeidExpr>(this);
3811 if (!TE->isPotentiallyEvaluated())
3812 return false;
3813
3814 // If this type id expression can throw because of a null pointer, that is a
3815 // side-effect independent of if the operand has a side-effect
3816 if (IncludePossibleEffects && TE->hasNullCheck())
3817 return true;
3818
3819 break;
3820 }
3821
3822 case CXXConstructExprClass:
3823 case CXXTemporaryObjectExprClass: {
3824 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
3825 if (!CE->getConstructor()->isTrivial() && IncludePossibleEffects)
3826 return true;
3827 // A trivial constructor does not add any side-effects of its own. Just look
3828 // at its arguments.
3829 break;
3830 }
3831
3832 case CXXInheritedCtorInitExprClass: {
3833 const auto *ICIE = cast<CXXInheritedCtorInitExpr>(this);
3834 if (!ICIE->getConstructor()->isTrivial() && IncludePossibleEffects)
3835 return true;
3836 break;
3837 }
3838
3839 case LambdaExprClass: {
3840 const LambdaExpr *LE = cast<LambdaExpr>(this);
3841 for (Expr *E : LE->capture_inits())
3842 if (E && E->HasSideEffects(Ctx, IncludePossibleEffects))
3843 return true;
3844 return false;
3845 }
3846
3847 case PseudoObjectExprClass: {
3848 // Only look for side-effects in the semantic form, and look past
3849 // OpaqueValueExpr bindings in that form.
3850 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
3851 for (PseudoObjectExpr::const_semantics_iterator I = PO->semantics_begin(),
3852 E = PO->semantics_end();
3853 I != E; ++I) {
3854 const Expr *Subexpr = *I;
3855 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Subexpr))
3856 Subexpr = OVE->getSourceExpr();
3857 if (Subexpr->HasSideEffects(Ctx, IncludePossibleEffects))
3858 return true;
3859 }
3860 return false;
3861 }
3862
3863 case ObjCBoxedExprClass:
3864 case ObjCArrayLiteralClass:
3865 case ObjCDictionaryLiteralClass:
3866 case ObjCSelectorExprClass:
3867 case ObjCProtocolExprClass:
3868 case ObjCIsaExprClass:
3869 case ObjCIndirectCopyRestoreExprClass:
3870 case ObjCSubscriptRefExprClass:
3871 case ObjCBridgedCastExprClass:
3872 case ObjCMessageExprClass:
3873 case ObjCPropertyRefExprClass:
3874 // FIXME: Classify these cases better.
3875 if (IncludePossibleEffects)
3876 return true;
3877 break;
3878 }
3879
3880 // Recurse to children.
3881 for (const Stmt *SubStmt : children())
3882 if (SubStmt &&
3883 cast<Expr>(SubStmt)->HasSideEffects(Ctx, IncludePossibleEffects))
3884 return true;
3885
3886 return false;
3887 }
3888
getFPFeaturesInEffect(const LangOptions & LO) const3889 FPOptions Expr::getFPFeaturesInEffect(const LangOptions &LO) const {
3890 if (auto Call = dyn_cast<CallExpr>(this))
3891 return Call->getFPFeaturesInEffect(LO);
3892 if (auto UO = dyn_cast<UnaryOperator>(this))
3893 return UO->getFPFeaturesInEffect(LO);
3894 if (auto BO = dyn_cast<BinaryOperator>(this))
3895 return BO->getFPFeaturesInEffect(LO);
3896 if (auto Cast = dyn_cast<CastExpr>(this))
3897 return Cast->getFPFeaturesInEffect(LO);
3898 if (auto ConvertVector = dyn_cast<ConvertVectorExpr>(this))
3899 return ConvertVector->getFPFeaturesInEffect(LO);
3900 return FPOptions::defaultWithoutTrailingStorage(LO);
3901 }
3902
3903 namespace {
3904 /// Look for a call to a non-trivial function within an expression.
3905 class NonTrivialCallFinder : public ConstEvaluatedExprVisitor<NonTrivialCallFinder>
3906 {
3907 typedef ConstEvaluatedExprVisitor<NonTrivialCallFinder> Inherited;
3908
3909 bool NonTrivial;
3910
3911 public:
NonTrivialCallFinder(const ASTContext & Context)3912 explicit NonTrivialCallFinder(const ASTContext &Context)
3913 : Inherited(Context), NonTrivial(false) { }
3914
hasNonTrivialCall() const3915 bool hasNonTrivialCall() const { return NonTrivial; }
3916
VisitCallExpr(const CallExpr * E)3917 void VisitCallExpr(const CallExpr *E) {
3918 if (const CXXMethodDecl *Method
3919 = dyn_cast_or_null<const CXXMethodDecl>(E->getCalleeDecl())) {
3920 if (Method->isTrivial()) {
3921 // Recurse to children of the call.
3922 Inherited::VisitStmt(E);
3923 return;
3924 }
3925 }
3926
3927 NonTrivial = true;
3928 }
3929
VisitCXXConstructExpr(const CXXConstructExpr * E)3930 void VisitCXXConstructExpr(const CXXConstructExpr *E) {
3931 if (E->getConstructor()->isTrivial()) {
3932 // Recurse to children of the call.
3933 Inherited::VisitStmt(E);
3934 return;
3935 }
3936
3937 NonTrivial = true;
3938 }
3939
VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr * E)3940 void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
3941 // Destructor of the temporary might be null if destructor declaration
3942 // is not valid.
3943 if (const CXXDestructorDecl *DtorDecl =
3944 E->getTemporary()->getDestructor()) {
3945 if (DtorDecl->isTrivial()) {
3946 Inherited::VisitStmt(E);
3947 return;
3948 }
3949 }
3950
3951 NonTrivial = true;
3952 }
3953 };
3954 }
3955
hasNonTrivialCall(const ASTContext & Ctx) const3956 bool Expr::hasNonTrivialCall(const ASTContext &Ctx) const {
3957 NonTrivialCallFinder Finder(Ctx);
3958 Finder.Visit(this);
3959 return Finder.hasNonTrivialCall();
3960 }
3961
3962 /// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null
3963 /// pointer constant or not, as well as the specific kind of constant detected.
3964 /// Null pointer constants can be integer constant expressions with the
3965 /// value zero, casts of zero to void*, nullptr (C++0X), or __null
3966 /// (a GNU extension).
3967 Expr::NullPointerConstantKind
isNullPointerConstant(ASTContext & Ctx,NullPointerConstantValueDependence NPC) const3968 Expr::isNullPointerConstant(ASTContext &Ctx,
3969 NullPointerConstantValueDependence NPC) const {
3970 if (isValueDependent() &&
3971 (!Ctx.getLangOpts().CPlusPlus11 || Ctx.getLangOpts().MSVCCompat)) {
3972 // Error-dependent expr should never be a null pointer.
3973 if (containsErrors())
3974 return NPCK_NotNull;
3975 switch (NPC) {
3976 case NPC_NeverValueDependent:
3977 llvm_unreachable("Unexpected value dependent expression!");
3978 case NPC_ValueDependentIsNull:
3979 if (isTypeDependent() || getType()->isIntegralType(Ctx))
3980 return NPCK_ZeroExpression;
3981 else
3982 return NPCK_NotNull;
3983
3984 case NPC_ValueDependentIsNotNull:
3985 return NPCK_NotNull;
3986 }
3987 }
3988
3989 // Strip off a cast to void*, if it exists. Except in C++.
3990 if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) {
3991 if (!Ctx.getLangOpts().CPlusPlus) {
3992 // Check that it is a cast to void*.
3993 if (const PointerType *PT = CE->getType()->getAs<PointerType>()) {
3994 QualType Pointee = PT->getPointeeType();
3995 Qualifiers Qs = Pointee.getQualifiers();
3996 // Only (void*)0 or equivalent are treated as nullptr. If pointee type
3997 // has non-default address space it is not treated as nullptr.
3998 // (__generic void*)0 in OpenCL 2.0 should not be treated as nullptr
3999 // since it cannot be assigned to a pointer to constant address space.
4000 if (Ctx.getLangOpts().OpenCL &&
4001 Pointee.getAddressSpace() == Ctx.getDefaultOpenCLPointeeAddrSpace())
4002 Qs.removeAddressSpace();
4003
4004 if (Pointee->isVoidType() && Qs.empty() && // to void*
4005 CE->getSubExpr()->getType()->isIntegerType()) // from int
4006 return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
4007 }
4008 }
4009 } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) {
4010 // Ignore the ImplicitCastExpr type entirely.
4011 return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
4012 } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) {
4013 // Accept ((void*)0) as a null pointer constant, as many other
4014 // implementations do.
4015 return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
4016 } else if (const GenericSelectionExpr *GE =
4017 dyn_cast<GenericSelectionExpr>(this)) {
4018 if (GE->isResultDependent())
4019 return NPCK_NotNull;
4020 return GE->getResultExpr()->isNullPointerConstant(Ctx, NPC);
4021 } else if (const ChooseExpr *CE = dyn_cast<ChooseExpr>(this)) {
4022 if (CE->isConditionDependent())
4023 return NPCK_NotNull;
4024 return CE->getChosenSubExpr()->isNullPointerConstant(Ctx, NPC);
4025 } else if (const CXXDefaultArgExpr *DefaultArg
4026 = dyn_cast<CXXDefaultArgExpr>(this)) {
4027 // See through default argument expressions.
4028 return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC);
4029 } else if (const CXXDefaultInitExpr *DefaultInit
4030 = dyn_cast<CXXDefaultInitExpr>(this)) {
4031 // See through default initializer expressions.
4032 return DefaultInit->getExpr()->isNullPointerConstant(Ctx, NPC);
4033 } else if (isa<GNUNullExpr>(this)) {
4034 // The GNU __null extension is always a null pointer constant.
4035 return NPCK_GNUNull;
4036 } else if (const MaterializeTemporaryExpr *M
4037 = dyn_cast<MaterializeTemporaryExpr>(this)) {
4038 return M->getSubExpr()->isNullPointerConstant(Ctx, NPC);
4039 } else if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(this)) {
4040 if (const Expr *Source = OVE->getSourceExpr())
4041 return Source->isNullPointerConstant(Ctx, NPC);
4042 }
4043
4044 // If the expression has no type information, it cannot be a null pointer
4045 // constant.
4046 if (getType().isNull())
4047 return NPCK_NotNull;
4048
4049 // C++11/C23 nullptr_t is always a null pointer constant.
4050 if (getType()->isNullPtrType())
4051 return NPCK_CXX11_nullptr;
4052
4053 if (const RecordType *UT = getType()->getAsUnionType())
4054 if (!Ctx.getLangOpts().CPlusPlus11 &&
4055 UT && UT->getDecl()->hasAttr<TransparentUnionAttr>())
4056 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(this)){
4057 const Expr *InitExpr = CLE->getInitializer();
4058 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(InitExpr))
4059 return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC);
4060 }
4061 // This expression must be an integer type.
4062 if (!getType()->isIntegerType() ||
4063 (Ctx.getLangOpts().CPlusPlus && getType()->isEnumeralType()))
4064 return NPCK_NotNull;
4065
4066 if (Ctx.getLangOpts().CPlusPlus11) {
4067 // C++11 [conv.ptr]p1: A null pointer constant is an integer literal with
4068 // value zero or a prvalue of type std::nullptr_t.
4069 // Microsoft mode permits C++98 rules reflecting MSVC behavior.
4070 const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(this);
4071 if (Lit && !Lit->getValue())
4072 return NPCK_ZeroLiteral;
4073 if (!Ctx.getLangOpts().MSVCCompat || !isCXX98IntegralConstantExpr(Ctx))
4074 return NPCK_NotNull;
4075 } else {
4076 // If we have an integer constant expression, we need to *evaluate* it and
4077 // test for the value 0.
4078 if (!isIntegerConstantExpr(Ctx))
4079 return NPCK_NotNull;
4080 }
4081
4082 if (EvaluateKnownConstInt(Ctx) != 0)
4083 return NPCK_NotNull;
4084
4085 if (isa<IntegerLiteral>(this))
4086 return NPCK_ZeroLiteral;
4087 return NPCK_ZeroExpression;
4088 }
4089
4090 /// If this expression is an l-value for an Objective C
4091 /// property, find the underlying property reference expression.
getObjCProperty() const4092 const ObjCPropertyRefExpr *Expr::getObjCProperty() const {
4093 const Expr *E = this;
4094 while (true) {
4095 assert((E->isLValue() && E->getObjectKind() == OK_ObjCProperty) &&
4096 "expression is not a property reference");
4097 E = E->IgnoreParenCasts();
4098 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4099 if (BO->getOpcode() == BO_Comma) {
4100 E = BO->getRHS();
4101 continue;
4102 }
4103 }
4104
4105 break;
4106 }
4107
4108 return cast<ObjCPropertyRefExpr>(E);
4109 }
4110
isObjCSelfExpr() const4111 bool Expr::isObjCSelfExpr() const {
4112 const Expr *E = IgnoreParenImpCasts();
4113
4114 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
4115 if (!DRE)
4116 return false;
4117
4118 const ImplicitParamDecl *Param = dyn_cast<ImplicitParamDecl>(DRE->getDecl());
4119 if (!Param)
4120 return false;
4121
4122 const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(Param->getDeclContext());
4123 if (!M)
4124 return false;
4125
4126 return M->getSelfDecl() == Param;
4127 }
4128
getSourceBitField()4129 FieldDecl *Expr::getSourceBitField() {
4130 Expr *E = this->IgnoreParens();
4131
4132 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
4133 if (ICE->getCastKind() == CK_LValueToRValue ||
4134 (ICE->isGLValue() && ICE->getCastKind() == CK_NoOp))
4135 E = ICE->getSubExpr()->IgnoreParens();
4136 else
4137 break;
4138 }
4139
4140 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E))
4141 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl()))
4142 if (Field->isBitField())
4143 return Field;
4144
4145 if (ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
4146 FieldDecl *Ivar = IvarRef->getDecl();
4147 if (Ivar->isBitField())
4148 return Ivar;
4149 }
4150
4151 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E)) {
4152 if (FieldDecl *Field = dyn_cast<FieldDecl>(DeclRef->getDecl()))
4153 if (Field->isBitField())
4154 return Field;
4155
4156 if (BindingDecl *BD = dyn_cast<BindingDecl>(DeclRef->getDecl()))
4157 if (Expr *E = BD->getBinding())
4158 return E->getSourceBitField();
4159 }
4160
4161 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E)) {
4162 if (BinOp->isAssignmentOp() && BinOp->getLHS())
4163 return BinOp->getLHS()->getSourceBitField();
4164
4165 if (BinOp->getOpcode() == BO_Comma && BinOp->getRHS())
4166 return BinOp->getRHS()->getSourceBitField();
4167 }
4168
4169 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E))
4170 if (UnOp->isPrefix() && UnOp->isIncrementDecrementOp())
4171 return UnOp->getSubExpr()->getSourceBitField();
4172
4173 return nullptr;
4174 }
4175
getEnumConstantDecl()4176 EnumConstantDecl *Expr::getEnumConstantDecl() {
4177 Expr *E = this->IgnoreParenImpCasts();
4178 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
4179 return dyn_cast<EnumConstantDecl>(DRE->getDecl());
4180 return nullptr;
4181 }
4182
refersToVectorElement() const4183 bool Expr::refersToVectorElement() const {
4184 // FIXME: Why do we not just look at the ObjectKind here?
4185 const Expr *E = this->IgnoreParens();
4186
4187 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
4188 if (ICE->isGLValue() && ICE->getCastKind() == CK_NoOp)
4189 E = ICE->getSubExpr()->IgnoreParens();
4190 else
4191 break;
4192 }
4193
4194 if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E))
4195 return ASE->getBase()->getType()->isVectorType();
4196
4197 if (isa<ExtVectorElementExpr>(E))
4198 return true;
4199
4200 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
4201 if (auto *BD = dyn_cast<BindingDecl>(DRE->getDecl()))
4202 if (auto *E = BD->getBinding())
4203 return E->refersToVectorElement();
4204
4205 return false;
4206 }
4207
refersToGlobalRegisterVar() const4208 bool Expr::refersToGlobalRegisterVar() const {
4209 const Expr *E = this->IgnoreParenImpCasts();
4210
4211 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
4212 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
4213 if (VD->getStorageClass() == SC_Register &&
4214 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
4215 return true;
4216
4217 return false;
4218 }
4219
isSameComparisonOperand(const Expr * E1,const Expr * E2)4220 bool Expr::isSameComparisonOperand(const Expr* E1, const Expr* E2) {
4221 E1 = E1->IgnoreParens();
4222 E2 = E2->IgnoreParens();
4223
4224 if (E1->getStmtClass() != E2->getStmtClass())
4225 return false;
4226
4227 switch (E1->getStmtClass()) {
4228 default:
4229 return false;
4230 case CXXThisExprClass:
4231 return true;
4232 case DeclRefExprClass: {
4233 // DeclRefExpr without an ImplicitCastExpr can happen for integral
4234 // template parameters.
4235 const auto *DRE1 = cast<DeclRefExpr>(E1);
4236 const auto *DRE2 = cast<DeclRefExpr>(E2);
4237 return DRE1->isPRValue() && DRE2->isPRValue() &&
4238 DRE1->getDecl() == DRE2->getDecl();
4239 }
4240 case ImplicitCastExprClass: {
4241 // Peel off implicit casts.
4242 while (true) {
4243 const auto *ICE1 = dyn_cast<ImplicitCastExpr>(E1);
4244 const auto *ICE2 = dyn_cast<ImplicitCastExpr>(E2);
4245 if (!ICE1 || !ICE2)
4246 return false;
4247 if (ICE1->getCastKind() != ICE2->getCastKind())
4248 return false;
4249 E1 = ICE1->getSubExpr()->IgnoreParens();
4250 E2 = ICE2->getSubExpr()->IgnoreParens();
4251 // The final cast must be one of these types.
4252 if (ICE1->getCastKind() == CK_LValueToRValue ||
4253 ICE1->getCastKind() == CK_ArrayToPointerDecay ||
4254 ICE1->getCastKind() == CK_FunctionToPointerDecay) {
4255 break;
4256 }
4257 }
4258
4259 const auto *DRE1 = dyn_cast<DeclRefExpr>(E1);
4260 const auto *DRE2 = dyn_cast<DeclRefExpr>(E2);
4261 if (DRE1 && DRE2)
4262 return declaresSameEntity(DRE1->getDecl(), DRE2->getDecl());
4263
4264 const auto *Ivar1 = dyn_cast<ObjCIvarRefExpr>(E1);
4265 const auto *Ivar2 = dyn_cast<ObjCIvarRefExpr>(E2);
4266 if (Ivar1 && Ivar2) {
4267 return Ivar1->isFreeIvar() && Ivar2->isFreeIvar() &&
4268 declaresSameEntity(Ivar1->getDecl(), Ivar2->getDecl());
4269 }
4270
4271 const auto *Array1 = dyn_cast<ArraySubscriptExpr>(E1);
4272 const auto *Array2 = dyn_cast<ArraySubscriptExpr>(E2);
4273 if (Array1 && Array2) {
4274 if (!isSameComparisonOperand(Array1->getBase(), Array2->getBase()))
4275 return false;
4276
4277 auto Idx1 = Array1->getIdx();
4278 auto Idx2 = Array2->getIdx();
4279 const auto Integer1 = dyn_cast<IntegerLiteral>(Idx1);
4280 const auto Integer2 = dyn_cast<IntegerLiteral>(Idx2);
4281 if (Integer1 && Integer2) {
4282 if (!llvm::APInt::isSameValue(Integer1->getValue(),
4283 Integer2->getValue()))
4284 return false;
4285 } else {
4286 if (!isSameComparisonOperand(Idx1, Idx2))
4287 return false;
4288 }
4289
4290 return true;
4291 }
4292
4293 // Walk the MemberExpr chain.
4294 while (isa<MemberExpr>(E1) && isa<MemberExpr>(E2)) {
4295 const auto *ME1 = cast<MemberExpr>(E1);
4296 const auto *ME2 = cast<MemberExpr>(E2);
4297 if (!declaresSameEntity(ME1->getMemberDecl(), ME2->getMemberDecl()))
4298 return false;
4299 if (const auto *D = dyn_cast<VarDecl>(ME1->getMemberDecl()))
4300 if (D->isStaticDataMember())
4301 return true;
4302 E1 = ME1->getBase()->IgnoreParenImpCasts();
4303 E2 = ME2->getBase()->IgnoreParenImpCasts();
4304 }
4305
4306 if (isa<CXXThisExpr>(E1) && isa<CXXThisExpr>(E2))
4307 return true;
4308
4309 // A static member variable can end the MemberExpr chain with either
4310 // a MemberExpr or a DeclRefExpr.
4311 auto getAnyDecl = [](const Expr *E) -> const ValueDecl * {
4312 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4313 return DRE->getDecl();
4314 if (const auto *ME = dyn_cast<MemberExpr>(E))
4315 return ME->getMemberDecl();
4316 return nullptr;
4317 };
4318
4319 const ValueDecl *VD1 = getAnyDecl(E1);
4320 const ValueDecl *VD2 = getAnyDecl(E2);
4321 return declaresSameEntity(VD1, VD2);
4322 }
4323 }
4324 }
4325
4326 /// isArrow - Return true if the base expression is a pointer to vector,
4327 /// return false if the base expression is a vector.
isArrow() const4328 bool ExtVectorElementExpr::isArrow() const {
4329 return getBase()->getType()->isPointerType();
4330 }
4331
getNumElements() const4332 unsigned ExtVectorElementExpr::getNumElements() const {
4333 if (const VectorType *VT = getType()->getAs<VectorType>())
4334 return VT->getNumElements();
4335 return 1;
4336 }
4337
4338 /// containsDuplicateElements - Return true if any element access is repeated.
containsDuplicateElements() const4339 bool ExtVectorElementExpr::containsDuplicateElements() const {
4340 // FIXME: Refactor this code to an accessor on the AST node which returns the
4341 // "type" of component access, and share with code below and in Sema.
4342 StringRef Comp = Accessor->getName();
4343
4344 // Halving swizzles do not contain duplicate elements.
4345 if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd")
4346 return false;
4347
4348 // Advance past s-char prefix on hex swizzles.
4349 if (Comp[0] == 's' || Comp[0] == 'S')
4350 Comp = Comp.substr(1);
4351
4352 for (unsigned i = 0, e = Comp.size(); i != e; ++i)
4353 if (Comp.substr(i + 1).contains(Comp[i]))
4354 return true;
4355
4356 return false;
4357 }
4358
4359 /// getEncodedElementAccess - We encode the fields as a llvm ConstantArray.
getEncodedElementAccess(SmallVectorImpl<uint32_t> & Elts) const4360 void ExtVectorElementExpr::getEncodedElementAccess(
4361 SmallVectorImpl<uint32_t> &Elts) const {
4362 StringRef Comp = Accessor->getName();
4363 bool isNumericAccessor = false;
4364 if (Comp[0] == 's' || Comp[0] == 'S') {
4365 Comp = Comp.substr(1);
4366 isNumericAccessor = true;
4367 }
4368
4369 bool isHi = Comp == "hi";
4370 bool isLo = Comp == "lo";
4371 bool isEven = Comp == "even";
4372 bool isOdd = Comp == "odd";
4373
4374 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
4375 uint64_t Index;
4376
4377 if (isHi)
4378 Index = e + i;
4379 else if (isLo)
4380 Index = i;
4381 else if (isEven)
4382 Index = 2 * i;
4383 else if (isOdd)
4384 Index = 2 * i + 1;
4385 else
4386 Index = ExtVectorType::getAccessorIdx(Comp[i], isNumericAccessor);
4387
4388 Elts.push_back(Index);
4389 }
4390 }
4391
ShuffleVectorExpr(const ASTContext & C,ArrayRef<Expr * > args,QualType Type,SourceLocation BLoc,SourceLocation RP)4392 ShuffleVectorExpr::ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr *> args,
4393 QualType Type, SourceLocation BLoc,
4394 SourceLocation RP)
4395 : Expr(ShuffleVectorExprClass, Type, VK_PRValue, OK_Ordinary),
4396 BuiltinLoc(BLoc), RParenLoc(RP) {
4397 ShuffleVectorExprBits.NumExprs = args.size();
4398 SubExprs = new (C) Stmt*[args.size()];
4399 for (unsigned i = 0; i != args.size(); i++)
4400 SubExprs[i] = args[i];
4401
4402 setDependence(computeDependence(this));
4403 }
4404
setExprs(const ASTContext & C,ArrayRef<Expr * > Exprs)4405 void ShuffleVectorExpr::setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs) {
4406 if (SubExprs) C.Deallocate(SubExprs);
4407
4408 this->ShuffleVectorExprBits.NumExprs = Exprs.size();
4409 SubExprs = new (C) Stmt *[ShuffleVectorExprBits.NumExprs];
4410 llvm::copy(Exprs, SubExprs);
4411 }
4412
GenericSelectionExpr(const ASTContext &,SourceLocation GenericLoc,Expr * ControllingExpr,ArrayRef<TypeSourceInfo * > AssocTypes,ArrayRef<Expr * > AssocExprs,SourceLocation DefaultLoc,SourceLocation RParenLoc,bool ContainsUnexpandedParameterPack,unsigned ResultIndex)4413 GenericSelectionExpr::GenericSelectionExpr(
4414 const ASTContext &, SourceLocation GenericLoc, Expr *ControllingExpr,
4415 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4416 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4417 bool ContainsUnexpandedParameterPack, unsigned ResultIndex)
4418 : Expr(GenericSelectionExprClass, AssocExprs[ResultIndex]->getType(),
4419 AssocExprs[ResultIndex]->getValueKind(),
4420 AssocExprs[ResultIndex]->getObjectKind()),
4421 NumAssocs(AssocExprs.size()), ResultIndex(ResultIndex),
4422 IsExprPredicate(true), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
4423 assert(AssocTypes.size() == AssocExprs.size() &&
4424 "Must have the same number of association expressions"
4425 " and TypeSourceInfo!");
4426 assert(ResultIndex < NumAssocs && "ResultIndex is out-of-bounds!");
4427
4428 GenericSelectionExprBits.GenericLoc = GenericLoc;
4429 getTrailingObjects<Stmt *>()[getIndexOfControllingExpression()] =
4430 ControllingExpr;
4431 llvm::copy(AssocExprs,
4432 getTrailingObjects<Stmt *>() + getIndexOfStartOfAssociatedExprs());
4433 llvm::copy(AssocTypes, getTrailingObjects<TypeSourceInfo *>() +
4434 getIndexOfStartOfAssociatedTypes());
4435
4436 setDependence(computeDependence(this, ContainsUnexpandedParameterPack));
4437 }
4438
GenericSelectionExpr(const ASTContext &,SourceLocation GenericLoc,TypeSourceInfo * ControllingType,ArrayRef<TypeSourceInfo * > AssocTypes,ArrayRef<Expr * > AssocExprs,SourceLocation DefaultLoc,SourceLocation RParenLoc,bool ContainsUnexpandedParameterPack,unsigned ResultIndex)4439 GenericSelectionExpr::GenericSelectionExpr(
4440 const ASTContext &, SourceLocation GenericLoc,
4441 TypeSourceInfo *ControllingType, ArrayRef<TypeSourceInfo *> AssocTypes,
4442 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
4443 SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack,
4444 unsigned ResultIndex)
4445 : Expr(GenericSelectionExprClass, AssocExprs[ResultIndex]->getType(),
4446 AssocExprs[ResultIndex]->getValueKind(),
4447 AssocExprs[ResultIndex]->getObjectKind()),
4448 NumAssocs(AssocExprs.size()), ResultIndex(ResultIndex),
4449 IsExprPredicate(false), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
4450 assert(AssocTypes.size() == AssocExprs.size() &&
4451 "Must have the same number of association expressions"
4452 " and TypeSourceInfo!");
4453 assert(ResultIndex < NumAssocs && "ResultIndex is out-of-bounds!");
4454
4455 GenericSelectionExprBits.GenericLoc = GenericLoc;
4456 getTrailingObjects<TypeSourceInfo *>()[getIndexOfControllingType()] =
4457 ControllingType;
4458 llvm::copy(AssocExprs,
4459 getTrailingObjects<Stmt *>() + getIndexOfStartOfAssociatedExprs());
4460 llvm::copy(AssocTypes, getTrailingObjects<TypeSourceInfo *>() +
4461 getIndexOfStartOfAssociatedTypes());
4462
4463 setDependence(computeDependence(this, ContainsUnexpandedParameterPack));
4464 }
4465
GenericSelectionExpr(const ASTContext & Context,SourceLocation GenericLoc,Expr * ControllingExpr,ArrayRef<TypeSourceInfo * > AssocTypes,ArrayRef<Expr * > AssocExprs,SourceLocation DefaultLoc,SourceLocation RParenLoc,bool ContainsUnexpandedParameterPack)4466 GenericSelectionExpr::GenericSelectionExpr(
4467 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4468 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4469 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4470 bool ContainsUnexpandedParameterPack)
4471 : Expr(GenericSelectionExprClass, Context.DependentTy, VK_PRValue,
4472 OK_Ordinary),
4473 NumAssocs(AssocExprs.size()), ResultIndex(ResultDependentIndex),
4474 IsExprPredicate(true), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
4475 assert(AssocTypes.size() == AssocExprs.size() &&
4476 "Must have the same number of association expressions"
4477 " and TypeSourceInfo!");
4478
4479 GenericSelectionExprBits.GenericLoc = GenericLoc;
4480 getTrailingObjects<Stmt *>()[getIndexOfControllingExpression()] =
4481 ControllingExpr;
4482 llvm::copy(AssocExprs,
4483 getTrailingObjects<Stmt *>() + getIndexOfStartOfAssociatedExprs());
4484 llvm::copy(AssocTypes, getTrailingObjects<TypeSourceInfo *>() +
4485 getIndexOfStartOfAssociatedTypes());
4486
4487 setDependence(computeDependence(this, ContainsUnexpandedParameterPack));
4488 }
4489
GenericSelectionExpr(const ASTContext & Context,SourceLocation GenericLoc,TypeSourceInfo * ControllingType,ArrayRef<TypeSourceInfo * > AssocTypes,ArrayRef<Expr * > AssocExprs,SourceLocation DefaultLoc,SourceLocation RParenLoc,bool ContainsUnexpandedParameterPack)4490 GenericSelectionExpr::GenericSelectionExpr(
4491 const ASTContext &Context, SourceLocation GenericLoc,
4492 TypeSourceInfo *ControllingType, ArrayRef<TypeSourceInfo *> AssocTypes,
4493 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
4494 SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack)
4495 : Expr(GenericSelectionExprClass, Context.DependentTy, VK_PRValue,
4496 OK_Ordinary),
4497 NumAssocs(AssocExprs.size()), ResultIndex(ResultDependentIndex),
4498 IsExprPredicate(false), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
4499 assert(AssocTypes.size() == AssocExprs.size() &&
4500 "Must have the same number of association expressions"
4501 " and TypeSourceInfo!");
4502
4503 GenericSelectionExprBits.GenericLoc = GenericLoc;
4504 getTrailingObjects<TypeSourceInfo *>()[getIndexOfControllingType()] =
4505 ControllingType;
4506 llvm::copy(AssocExprs,
4507 getTrailingObjects<Stmt *>() + getIndexOfStartOfAssociatedExprs());
4508 llvm::copy(AssocTypes, getTrailingObjects<TypeSourceInfo *>() +
4509 getIndexOfStartOfAssociatedTypes());
4510
4511 setDependence(computeDependence(this, ContainsUnexpandedParameterPack));
4512 }
4513
GenericSelectionExpr(EmptyShell Empty,unsigned NumAssocs)4514 GenericSelectionExpr::GenericSelectionExpr(EmptyShell Empty, unsigned NumAssocs)
4515 : Expr(GenericSelectionExprClass, Empty), NumAssocs(NumAssocs) {}
4516
Create(const ASTContext & Context,SourceLocation GenericLoc,Expr * ControllingExpr,ArrayRef<TypeSourceInfo * > AssocTypes,ArrayRef<Expr * > AssocExprs,SourceLocation DefaultLoc,SourceLocation RParenLoc,bool ContainsUnexpandedParameterPack,unsigned ResultIndex)4517 GenericSelectionExpr *GenericSelectionExpr::Create(
4518 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4519 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4520 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4521 bool ContainsUnexpandedParameterPack, unsigned ResultIndex) {
4522 unsigned NumAssocs = AssocExprs.size();
4523 void *Mem = Context.Allocate(
4524 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4525 alignof(GenericSelectionExpr));
4526 return new (Mem) GenericSelectionExpr(
4527 Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc,
4528 RParenLoc, ContainsUnexpandedParameterPack, ResultIndex);
4529 }
4530
Create(const ASTContext & Context,SourceLocation GenericLoc,Expr * ControllingExpr,ArrayRef<TypeSourceInfo * > AssocTypes,ArrayRef<Expr * > AssocExprs,SourceLocation DefaultLoc,SourceLocation RParenLoc,bool ContainsUnexpandedParameterPack)4531 GenericSelectionExpr *GenericSelectionExpr::Create(
4532 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4533 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4534 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4535 bool ContainsUnexpandedParameterPack) {
4536 unsigned NumAssocs = AssocExprs.size();
4537 void *Mem = Context.Allocate(
4538 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4539 alignof(GenericSelectionExpr));
4540 return new (Mem) GenericSelectionExpr(
4541 Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc,
4542 RParenLoc, ContainsUnexpandedParameterPack);
4543 }
4544
Create(const ASTContext & Context,SourceLocation GenericLoc,TypeSourceInfo * ControllingType,ArrayRef<TypeSourceInfo * > AssocTypes,ArrayRef<Expr * > AssocExprs,SourceLocation DefaultLoc,SourceLocation RParenLoc,bool ContainsUnexpandedParameterPack,unsigned ResultIndex)4545 GenericSelectionExpr *GenericSelectionExpr::Create(
4546 const ASTContext &Context, SourceLocation GenericLoc,
4547 TypeSourceInfo *ControllingType, ArrayRef<TypeSourceInfo *> AssocTypes,
4548 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
4549 SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack,
4550 unsigned ResultIndex) {
4551 unsigned NumAssocs = AssocExprs.size();
4552 void *Mem = Context.Allocate(
4553 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4554 alignof(GenericSelectionExpr));
4555 return new (Mem) GenericSelectionExpr(
4556 Context, GenericLoc, ControllingType, AssocTypes, AssocExprs, DefaultLoc,
4557 RParenLoc, ContainsUnexpandedParameterPack, ResultIndex);
4558 }
4559
Create(const ASTContext & Context,SourceLocation GenericLoc,TypeSourceInfo * ControllingType,ArrayRef<TypeSourceInfo * > AssocTypes,ArrayRef<Expr * > AssocExprs,SourceLocation DefaultLoc,SourceLocation RParenLoc,bool ContainsUnexpandedParameterPack)4560 GenericSelectionExpr *GenericSelectionExpr::Create(
4561 const ASTContext &Context, SourceLocation GenericLoc,
4562 TypeSourceInfo *ControllingType, ArrayRef<TypeSourceInfo *> AssocTypes,
4563 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
4564 SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack) {
4565 unsigned NumAssocs = AssocExprs.size();
4566 void *Mem = Context.Allocate(
4567 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4568 alignof(GenericSelectionExpr));
4569 return new (Mem) GenericSelectionExpr(
4570 Context, GenericLoc, ControllingType, AssocTypes, AssocExprs, DefaultLoc,
4571 RParenLoc, ContainsUnexpandedParameterPack);
4572 }
4573
4574 GenericSelectionExpr *
CreateEmpty(const ASTContext & Context,unsigned NumAssocs)4575 GenericSelectionExpr::CreateEmpty(const ASTContext &Context,
4576 unsigned NumAssocs) {
4577 void *Mem = Context.Allocate(
4578 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4579 alignof(GenericSelectionExpr));
4580 return new (Mem) GenericSelectionExpr(EmptyShell(), NumAssocs);
4581 }
4582
4583 //===----------------------------------------------------------------------===//
4584 // DesignatedInitExpr
4585 //===----------------------------------------------------------------------===//
4586
getFieldName() const4587 const IdentifierInfo *DesignatedInitExpr::Designator::getFieldName() const {
4588 assert(isFieldDesignator() && "Only valid on a field designator");
4589 if (FieldInfo.NameOrField & 0x01)
4590 return reinterpret_cast<IdentifierInfo *>(FieldInfo.NameOrField & ~0x01);
4591 return getFieldDecl()->getIdentifier();
4592 }
4593
DesignatedInitExpr(const ASTContext & C,QualType Ty,ArrayRef<Designator> Designators,SourceLocation EqualOrColonLoc,bool GNUSyntax,ArrayRef<Expr * > IndexExprs,Expr * Init)4594 DesignatedInitExpr::DesignatedInitExpr(const ASTContext &C, QualType Ty,
4595 ArrayRef<Designator> Designators,
4596 SourceLocation EqualOrColonLoc,
4597 bool GNUSyntax,
4598 ArrayRef<Expr *> IndexExprs, Expr *Init)
4599 : Expr(DesignatedInitExprClass, Ty, Init->getValueKind(),
4600 Init->getObjectKind()),
4601 EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax),
4602 NumDesignators(Designators.size()), NumSubExprs(IndexExprs.size() + 1) {
4603 this->Designators = new (C) Designator[NumDesignators];
4604
4605 // Record the initializer itself.
4606 child_iterator Child = child_begin();
4607 *Child++ = Init;
4608
4609 // Copy the designators and their subexpressions, computing
4610 // value-dependence along the way.
4611 unsigned IndexIdx = 0;
4612 for (unsigned I = 0; I != NumDesignators; ++I) {
4613 this->Designators[I] = Designators[I];
4614 if (this->Designators[I].isArrayDesignator()) {
4615 // Copy the index expressions into permanent storage.
4616 *Child++ = IndexExprs[IndexIdx++];
4617 } else if (this->Designators[I].isArrayRangeDesignator()) {
4618 // Copy the start/end expressions into permanent storage.
4619 *Child++ = IndexExprs[IndexIdx++];
4620 *Child++ = IndexExprs[IndexIdx++];
4621 }
4622 }
4623
4624 assert(IndexIdx == IndexExprs.size() && "Wrong number of index expressions");
4625 setDependence(computeDependence(this));
4626 }
4627
Create(const ASTContext & C,ArrayRef<Designator> Designators,ArrayRef<Expr * > IndexExprs,SourceLocation ColonOrEqualLoc,bool UsesColonSyntax,Expr * Init)4628 DesignatedInitExpr *DesignatedInitExpr::Create(const ASTContext &C,
4629 ArrayRef<Designator> Designators,
4630 ArrayRef<Expr *> IndexExprs,
4631 SourceLocation ColonOrEqualLoc,
4632 bool UsesColonSyntax,
4633 Expr *Init) {
4634 void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(IndexExprs.size() + 1),
4635 alignof(DesignatedInitExpr));
4636 return new (Mem) DesignatedInitExpr(C, C.VoidTy, Designators,
4637 ColonOrEqualLoc, UsesColonSyntax,
4638 IndexExprs, Init);
4639 }
4640
CreateEmpty(const ASTContext & C,unsigned NumIndexExprs)4641 DesignatedInitExpr *DesignatedInitExpr::CreateEmpty(const ASTContext &C,
4642 unsigned NumIndexExprs) {
4643 void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(NumIndexExprs + 1),
4644 alignof(DesignatedInitExpr));
4645 return new (Mem) DesignatedInitExpr(NumIndexExprs + 1);
4646 }
4647
setDesignators(const ASTContext & C,const Designator * Desigs,unsigned NumDesigs)4648 void DesignatedInitExpr::setDesignators(const ASTContext &C,
4649 const Designator *Desigs,
4650 unsigned NumDesigs) {
4651 Designators = new (C) Designator[NumDesigs];
4652 NumDesignators = NumDesigs;
4653 for (unsigned I = 0; I != NumDesigs; ++I)
4654 Designators[I] = Desigs[I];
4655 }
4656
getDesignatorsSourceRange() const4657 SourceRange DesignatedInitExpr::getDesignatorsSourceRange() const {
4658 DesignatedInitExpr *DIE = const_cast<DesignatedInitExpr*>(this);
4659 if (size() == 1)
4660 return DIE->getDesignator(0)->getSourceRange();
4661 return SourceRange(DIE->getDesignator(0)->getBeginLoc(),
4662 DIE->getDesignator(size() - 1)->getEndLoc());
4663 }
4664
getBeginLoc() const4665 SourceLocation DesignatedInitExpr::getBeginLoc() const {
4666 auto *DIE = const_cast<DesignatedInitExpr *>(this);
4667 Designator &First = *DIE->getDesignator(0);
4668 if (First.isFieldDesignator()) {
4669 // Skip past implicit designators for anonymous structs/unions, since
4670 // these do not have valid source locations.
4671 for (unsigned int i = 0; i < DIE->size(); i++) {
4672 Designator &Des = *DIE->getDesignator(i);
4673 SourceLocation retval = GNUSyntax ? Des.getFieldLoc() : Des.getDotLoc();
4674 if (!retval.isValid())
4675 continue;
4676 return retval;
4677 }
4678 }
4679 return First.getLBracketLoc();
4680 }
4681
getEndLoc() const4682 SourceLocation DesignatedInitExpr::getEndLoc() const {
4683 return getInit()->getEndLoc();
4684 }
4685
getArrayIndex(const Designator & D) const4686 Expr *DesignatedInitExpr::getArrayIndex(const Designator& D) const {
4687 assert(D.isArrayDesignator() && "Requires array designator");
4688 return getSubExpr(D.getArrayIndex() + 1);
4689 }
4690
getArrayRangeStart(const Designator & D) const4691 Expr *DesignatedInitExpr::getArrayRangeStart(const Designator &D) const {
4692 assert(D.isArrayRangeDesignator() && "Requires array range designator");
4693 return getSubExpr(D.getArrayIndex() + 1);
4694 }
4695
getArrayRangeEnd(const Designator & D) const4696 Expr *DesignatedInitExpr::getArrayRangeEnd(const Designator &D) const {
4697 assert(D.isArrayRangeDesignator() && "Requires array range designator");
4698 return getSubExpr(D.getArrayIndex() + 2);
4699 }
4700
4701 /// Replaces the designator at index @p Idx with the series
4702 /// of designators in [First, Last).
ExpandDesignator(const ASTContext & C,unsigned Idx,const Designator * First,const Designator * Last)4703 void DesignatedInitExpr::ExpandDesignator(const ASTContext &C, unsigned Idx,
4704 const Designator *First,
4705 const Designator *Last) {
4706 unsigned NumNewDesignators = Last - First;
4707 if (NumNewDesignators == 0) {
4708 std::copy_backward(Designators + Idx + 1,
4709 Designators + NumDesignators,
4710 Designators + Idx);
4711 --NumNewDesignators;
4712 return;
4713 }
4714 if (NumNewDesignators == 1) {
4715 Designators[Idx] = *First;
4716 return;
4717 }
4718
4719 Designator *NewDesignators
4720 = new (C) Designator[NumDesignators - 1 + NumNewDesignators];
4721 std::copy(Designators, Designators + Idx, NewDesignators);
4722 std::copy(First, Last, NewDesignators + Idx);
4723 std::copy(Designators + Idx + 1, Designators + NumDesignators,
4724 NewDesignators + Idx + NumNewDesignators);
4725 Designators = NewDesignators;
4726 NumDesignators = NumDesignators - 1 + NumNewDesignators;
4727 }
4728
DesignatedInitUpdateExpr(const ASTContext & C,SourceLocation lBraceLoc,Expr * baseExpr,SourceLocation rBraceLoc)4729 DesignatedInitUpdateExpr::DesignatedInitUpdateExpr(const ASTContext &C,
4730 SourceLocation lBraceLoc,
4731 Expr *baseExpr,
4732 SourceLocation rBraceLoc)
4733 : Expr(DesignatedInitUpdateExprClass, baseExpr->getType(), VK_PRValue,
4734 OK_Ordinary) {
4735 BaseAndUpdaterExprs[0] = baseExpr;
4736
4737 InitListExpr *ILE = new (C) InitListExpr(C, lBraceLoc, {}, rBraceLoc);
4738 ILE->setType(baseExpr->getType());
4739 BaseAndUpdaterExprs[1] = ILE;
4740
4741 // FIXME: this is wrong, set it correctly.
4742 setDependence(ExprDependence::None);
4743 }
4744
getBeginLoc() const4745 SourceLocation DesignatedInitUpdateExpr::getBeginLoc() const {
4746 return getBase()->getBeginLoc();
4747 }
4748
getEndLoc() const4749 SourceLocation DesignatedInitUpdateExpr::getEndLoc() const {
4750 return getBase()->getEndLoc();
4751 }
4752
ParenListExpr(SourceLocation LParenLoc,ArrayRef<Expr * > Exprs,SourceLocation RParenLoc)4753 ParenListExpr::ParenListExpr(SourceLocation LParenLoc, ArrayRef<Expr *> Exprs,
4754 SourceLocation RParenLoc)
4755 : Expr(ParenListExprClass, QualType(), VK_PRValue, OK_Ordinary),
4756 LParenLoc(LParenLoc), RParenLoc(RParenLoc) {
4757 ParenListExprBits.NumExprs = Exprs.size();
4758 llvm::copy(Exprs, getTrailingObjects());
4759 setDependence(computeDependence(this));
4760 }
4761
ParenListExpr(EmptyShell Empty,unsigned NumExprs)4762 ParenListExpr::ParenListExpr(EmptyShell Empty, unsigned NumExprs)
4763 : Expr(ParenListExprClass, Empty) {
4764 ParenListExprBits.NumExprs = NumExprs;
4765 }
4766
Create(const ASTContext & Ctx,SourceLocation LParenLoc,ArrayRef<Expr * > Exprs,SourceLocation RParenLoc)4767 ParenListExpr *ParenListExpr::Create(const ASTContext &Ctx,
4768 SourceLocation LParenLoc,
4769 ArrayRef<Expr *> Exprs,
4770 SourceLocation RParenLoc) {
4771 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(Exprs.size()),
4772 alignof(ParenListExpr));
4773 return new (Mem) ParenListExpr(LParenLoc, Exprs, RParenLoc);
4774 }
4775
CreateEmpty(const ASTContext & Ctx,unsigned NumExprs)4776 ParenListExpr *ParenListExpr::CreateEmpty(const ASTContext &Ctx,
4777 unsigned NumExprs) {
4778 void *Mem =
4779 Ctx.Allocate(totalSizeToAlloc<Stmt *>(NumExprs), alignof(ParenListExpr));
4780 return new (Mem) ParenListExpr(EmptyShell(), NumExprs);
4781 }
4782
4783 /// Certain overflow-dependent code patterns can have their integer overflow
4784 /// sanitization disabled. Check for the common pattern `if (a + b < a)` and
4785 /// return the resulting BinaryOperator responsible for the addition so we can
4786 /// elide overflow checks during codegen.
4787 static std::optional<BinaryOperator *>
getOverflowPatternBinOp(const BinaryOperator * E)4788 getOverflowPatternBinOp(const BinaryOperator *E) {
4789 Expr *Addition, *ComparedTo;
4790 if (E->getOpcode() == BO_LT) {
4791 Addition = E->getLHS();
4792 ComparedTo = E->getRHS();
4793 } else if (E->getOpcode() == BO_GT) {
4794 Addition = E->getRHS();
4795 ComparedTo = E->getLHS();
4796 } else {
4797 return {};
4798 }
4799
4800 const Expr *AddLHS = nullptr, *AddRHS = nullptr;
4801 BinaryOperator *BO = dyn_cast<BinaryOperator>(Addition);
4802
4803 if (BO && BO->getOpcode() == clang::BO_Add) {
4804 // now store addends for lookup on other side of '>'
4805 AddLHS = BO->getLHS();
4806 AddRHS = BO->getRHS();
4807 }
4808
4809 if (!AddLHS || !AddRHS)
4810 return {};
4811
4812 const Decl *LHSDecl, *RHSDecl, *OtherDecl;
4813
4814 LHSDecl = AddLHS->IgnoreParenImpCasts()->getReferencedDeclOfCallee();
4815 RHSDecl = AddRHS->IgnoreParenImpCasts()->getReferencedDeclOfCallee();
4816 OtherDecl = ComparedTo->IgnoreParenImpCasts()->getReferencedDeclOfCallee();
4817
4818 if (!OtherDecl)
4819 return {};
4820
4821 if (!LHSDecl && !RHSDecl)
4822 return {};
4823
4824 if ((LHSDecl && LHSDecl == OtherDecl && LHSDecl != RHSDecl) ||
4825 (RHSDecl && RHSDecl == OtherDecl && RHSDecl != LHSDecl))
4826 return BO;
4827 return {};
4828 }
4829
4830 /// Compute and set the OverflowPatternExclusion bit based on whether the
4831 /// BinaryOperator expression matches an overflow pattern being ignored by
4832 /// -fsanitize-undefined-ignore-overflow-pattern=add-signed-overflow-test or
4833 /// -fsanitize-undefined-ignore-overflow-pattern=add-unsigned-overflow-test
computeOverflowPatternExclusion(const ASTContext & Ctx,const BinaryOperator * E)4834 static void computeOverflowPatternExclusion(const ASTContext &Ctx,
4835 const BinaryOperator *E) {
4836 std::optional<BinaryOperator *> Result = getOverflowPatternBinOp(E);
4837 if (!Result.has_value())
4838 return;
4839 QualType AdditionResultType = Result.value()->getType();
4840
4841 if ((AdditionResultType->isSignedIntegerType() &&
4842 Ctx.getLangOpts().isOverflowPatternExcluded(
4843 LangOptions::OverflowPatternExclusionKind::AddSignedOverflowTest)) ||
4844 (AdditionResultType->isUnsignedIntegerType() &&
4845 Ctx.getLangOpts().isOverflowPatternExcluded(
4846 LangOptions::OverflowPatternExclusionKind::AddUnsignedOverflowTest)))
4847 Result.value()->setExcludedOverflowPattern(true);
4848 }
4849
BinaryOperator(const ASTContext & Ctx,Expr * lhs,Expr * rhs,Opcode opc,QualType ResTy,ExprValueKind VK,ExprObjectKind OK,SourceLocation opLoc,FPOptionsOverride FPFeatures)4850 BinaryOperator::BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs,
4851 Opcode opc, QualType ResTy, ExprValueKind VK,
4852 ExprObjectKind OK, SourceLocation opLoc,
4853 FPOptionsOverride FPFeatures)
4854 : Expr(BinaryOperatorClass, ResTy, VK, OK) {
4855 BinaryOperatorBits.Opc = opc;
4856 assert(!isCompoundAssignmentOp() &&
4857 "Use CompoundAssignOperator for compound assignments");
4858 BinaryOperatorBits.OpLoc = opLoc;
4859 BinaryOperatorBits.ExcludedOverflowPattern = false;
4860 SubExprs[LHS] = lhs;
4861 SubExprs[RHS] = rhs;
4862 computeOverflowPatternExclusion(Ctx, this);
4863 BinaryOperatorBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();
4864 if (hasStoredFPFeatures())
4865 setStoredFPFeatures(FPFeatures);
4866 setDependence(computeDependence(this));
4867 }
4868
BinaryOperator(const ASTContext & Ctx,Expr * lhs,Expr * rhs,Opcode opc,QualType ResTy,ExprValueKind VK,ExprObjectKind OK,SourceLocation opLoc,FPOptionsOverride FPFeatures,bool dead2)4869 BinaryOperator::BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs,
4870 Opcode opc, QualType ResTy, ExprValueKind VK,
4871 ExprObjectKind OK, SourceLocation opLoc,
4872 FPOptionsOverride FPFeatures, bool dead2)
4873 : Expr(CompoundAssignOperatorClass, ResTy, VK, OK) {
4874 BinaryOperatorBits.Opc = opc;
4875 BinaryOperatorBits.ExcludedOverflowPattern = false;
4876 assert(isCompoundAssignmentOp() &&
4877 "Use CompoundAssignOperator for compound assignments");
4878 BinaryOperatorBits.OpLoc = opLoc;
4879 SubExprs[LHS] = lhs;
4880 SubExprs[RHS] = rhs;
4881 BinaryOperatorBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();
4882 if (hasStoredFPFeatures())
4883 setStoredFPFeatures(FPFeatures);
4884 setDependence(computeDependence(this));
4885 }
4886
CreateEmpty(const ASTContext & C,bool HasFPFeatures)4887 BinaryOperator *BinaryOperator::CreateEmpty(const ASTContext &C,
4888 bool HasFPFeatures) {
4889 unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);
4890 void *Mem =
4891 C.Allocate(sizeof(BinaryOperator) + Extra, alignof(BinaryOperator));
4892 return new (Mem) BinaryOperator(EmptyShell());
4893 }
4894
Create(const ASTContext & C,Expr * lhs,Expr * rhs,Opcode opc,QualType ResTy,ExprValueKind VK,ExprObjectKind OK,SourceLocation opLoc,FPOptionsOverride FPFeatures)4895 BinaryOperator *BinaryOperator::Create(const ASTContext &C, Expr *lhs,
4896 Expr *rhs, Opcode opc, QualType ResTy,
4897 ExprValueKind VK, ExprObjectKind OK,
4898 SourceLocation opLoc,
4899 FPOptionsOverride FPFeatures) {
4900 bool HasFPFeatures = FPFeatures.requiresTrailingStorage();
4901 unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);
4902 void *Mem =
4903 C.Allocate(sizeof(BinaryOperator) + Extra, alignof(BinaryOperator));
4904 return new (Mem)
4905 BinaryOperator(C, lhs, rhs, opc, ResTy, VK, OK, opLoc, FPFeatures);
4906 }
4907
4908 CompoundAssignOperator *
CreateEmpty(const ASTContext & C,bool HasFPFeatures)4909 CompoundAssignOperator::CreateEmpty(const ASTContext &C, bool HasFPFeatures) {
4910 unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);
4911 void *Mem = C.Allocate(sizeof(CompoundAssignOperator) + Extra,
4912 alignof(CompoundAssignOperator));
4913 return new (Mem) CompoundAssignOperator(C, EmptyShell(), HasFPFeatures);
4914 }
4915
4916 CompoundAssignOperator *
Create(const ASTContext & C,Expr * lhs,Expr * rhs,Opcode opc,QualType ResTy,ExprValueKind VK,ExprObjectKind OK,SourceLocation opLoc,FPOptionsOverride FPFeatures,QualType CompLHSType,QualType CompResultType)4917 CompoundAssignOperator::Create(const ASTContext &C, Expr *lhs, Expr *rhs,
4918 Opcode opc, QualType ResTy, ExprValueKind VK,
4919 ExprObjectKind OK, SourceLocation opLoc,
4920 FPOptionsOverride FPFeatures,
4921 QualType CompLHSType, QualType CompResultType) {
4922 bool HasFPFeatures = FPFeatures.requiresTrailingStorage();
4923 unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);
4924 void *Mem = C.Allocate(sizeof(CompoundAssignOperator) + Extra,
4925 alignof(CompoundAssignOperator));
4926 return new (Mem)
4927 CompoundAssignOperator(C, lhs, rhs, opc, ResTy, VK, OK, opLoc, FPFeatures,
4928 CompLHSType, CompResultType);
4929 }
4930
CreateEmpty(const ASTContext & C,bool hasFPFeatures)4931 UnaryOperator *UnaryOperator::CreateEmpty(const ASTContext &C,
4932 bool hasFPFeatures) {
4933 void *Mem = C.Allocate(totalSizeToAlloc<FPOptionsOverride>(hasFPFeatures),
4934 alignof(UnaryOperator));
4935 return new (Mem) UnaryOperator(hasFPFeatures, EmptyShell());
4936 }
4937
UnaryOperator(const ASTContext & Ctx,Expr * input,Opcode opc,QualType type,ExprValueKind VK,ExprObjectKind OK,SourceLocation l,bool CanOverflow,FPOptionsOverride FPFeatures)4938 UnaryOperator::UnaryOperator(const ASTContext &Ctx, Expr *input, Opcode opc,
4939 QualType type, ExprValueKind VK, ExprObjectKind OK,
4940 SourceLocation l, bool CanOverflow,
4941 FPOptionsOverride FPFeatures)
4942 : Expr(UnaryOperatorClass, type, VK, OK), Val(input) {
4943 UnaryOperatorBits.Opc = opc;
4944 UnaryOperatorBits.CanOverflow = CanOverflow;
4945 UnaryOperatorBits.Loc = l;
4946 UnaryOperatorBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();
4947 if (hasStoredFPFeatures())
4948 setStoredFPFeatures(FPFeatures);
4949 setDependence(computeDependence(this, Ctx));
4950 }
4951
Create(const ASTContext & C,Expr * input,Opcode opc,QualType type,ExprValueKind VK,ExprObjectKind OK,SourceLocation l,bool CanOverflow,FPOptionsOverride FPFeatures)4952 UnaryOperator *UnaryOperator::Create(const ASTContext &C, Expr *input,
4953 Opcode opc, QualType type,
4954 ExprValueKind VK, ExprObjectKind OK,
4955 SourceLocation l, bool CanOverflow,
4956 FPOptionsOverride FPFeatures) {
4957 bool HasFPFeatures = FPFeatures.requiresTrailingStorage();
4958 unsigned Size = totalSizeToAlloc<FPOptionsOverride>(HasFPFeatures);
4959 void *Mem = C.Allocate(Size, alignof(UnaryOperator));
4960 return new (Mem)
4961 UnaryOperator(C, input, opc, type, VK, OK, l, CanOverflow, FPFeatures);
4962 }
4963
findInCopyConstruct(const Expr * e)4964 const OpaqueValueExpr *OpaqueValueExpr::findInCopyConstruct(const Expr *e) {
4965 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(e))
4966 e = ewc->getSubExpr();
4967 if (const MaterializeTemporaryExpr *m = dyn_cast<MaterializeTemporaryExpr>(e))
4968 e = m->getSubExpr();
4969 e = cast<CXXConstructExpr>(e)->getArg(0);
4970 while (const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
4971 e = ice->getSubExpr();
4972 return cast<OpaqueValueExpr>(e);
4973 }
4974
Create(const ASTContext & Context,EmptyShell sh,unsigned numSemanticExprs)4975 PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &Context,
4976 EmptyShell sh,
4977 unsigned numSemanticExprs) {
4978 void *buffer =
4979 Context.Allocate(totalSizeToAlloc<Expr *>(1 + numSemanticExprs),
4980 alignof(PseudoObjectExpr));
4981 return new(buffer) PseudoObjectExpr(sh, numSemanticExprs);
4982 }
4983
PseudoObjectExpr(EmptyShell shell,unsigned numSemanticExprs)4984 PseudoObjectExpr::PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs)
4985 : Expr(PseudoObjectExprClass, shell) {
4986 PseudoObjectExprBits.NumSubExprs = numSemanticExprs + 1;
4987 }
4988
Create(const ASTContext & C,Expr * syntax,ArrayRef<Expr * > semantics,unsigned resultIndex)4989 PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &C, Expr *syntax,
4990 ArrayRef<Expr*> semantics,
4991 unsigned resultIndex) {
4992 assert(syntax && "no syntactic expression!");
4993 assert(semantics.size() && "no semantic expressions!");
4994
4995 QualType type;
4996 ExprValueKind VK;
4997 if (resultIndex == NoResult) {
4998 type = C.VoidTy;
4999 VK = VK_PRValue;
5000 } else {
5001 assert(resultIndex < semantics.size());
5002 type = semantics[resultIndex]->getType();
5003 VK = semantics[resultIndex]->getValueKind();
5004 assert(semantics[resultIndex]->getObjectKind() == OK_Ordinary);
5005 }
5006
5007 void *buffer = C.Allocate(totalSizeToAlloc<Expr *>(semantics.size() + 1),
5008 alignof(PseudoObjectExpr));
5009 return new(buffer) PseudoObjectExpr(type, VK, syntax, semantics,
5010 resultIndex);
5011 }
5012
PseudoObjectExpr(QualType type,ExprValueKind VK,Expr * syntax,ArrayRef<Expr * > semantics,unsigned resultIndex)5013 PseudoObjectExpr::PseudoObjectExpr(QualType type, ExprValueKind VK,
5014 Expr *syntax, ArrayRef<Expr *> semantics,
5015 unsigned resultIndex)
5016 : Expr(PseudoObjectExprClass, type, VK, OK_Ordinary) {
5017 PseudoObjectExprBits.NumSubExprs = semantics.size() + 1;
5018 PseudoObjectExprBits.ResultIndex = resultIndex + 1;
5019 MutableArrayRef<Expr *> Trail = getTrailingObjects(semantics.size() + 1);
5020 Trail[0] = syntax;
5021
5022 assert(llvm::all_of(semantics,
5023 [](const Expr *E) {
5024 return !isa<OpaqueValueExpr>(E) ||
5025 cast<OpaqueValueExpr>(E)->getSourceExpr() !=
5026 nullptr;
5027 }) &&
5028 "opaque-value semantic expressions for pseudo-object "
5029 "operations must have sources");
5030
5031 llvm::copy(semantics, Trail.drop_front().begin());
5032 setDependence(computeDependence(this));
5033 }
5034
5035 //===----------------------------------------------------------------------===//
5036 // Child Iterators for iterating over subexpressions/substatements
5037 //===----------------------------------------------------------------------===//
5038
5039 // UnaryExprOrTypeTraitExpr
children()5040 Stmt::child_range UnaryExprOrTypeTraitExpr::children() {
5041 const_child_range CCR =
5042 const_cast<const UnaryExprOrTypeTraitExpr *>(this)->children();
5043 return child_range(cast_away_const(CCR.begin()), cast_away_const(CCR.end()));
5044 }
5045
children() const5046 Stmt::const_child_range UnaryExprOrTypeTraitExpr::children() const {
5047 // If this is of a type and the type is a VLA type (and not a typedef), the
5048 // size expression of the VLA needs to be treated as an executable expression.
5049 // Why isn't this weirdness documented better in StmtIterator?
5050 if (isArgumentType()) {
5051 if (const VariableArrayType *T =
5052 dyn_cast<VariableArrayType>(getArgumentType().getTypePtr()))
5053 return const_child_range(const_child_iterator(T), const_child_iterator());
5054 return const_child_range(const_child_iterator(), const_child_iterator());
5055 }
5056 return const_child_range(&Argument.Ex, &Argument.Ex + 1);
5057 }
5058
AtomicExpr(SourceLocation BLoc,ArrayRef<Expr * > args,QualType t,AtomicOp op,SourceLocation RP)5059 AtomicExpr::AtomicExpr(SourceLocation BLoc, ArrayRef<Expr *> args, QualType t,
5060 AtomicOp op, SourceLocation RP)
5061 : Expr(AtomicExprClass, t, VK_PRValue, OK_Ordinary),
5062 NumSubExprs(args.size()), BuiltinLoc(BLoc), RParenLoc(RP), Op(op) {
5063 assert(args.size() == getNumSubExprs(op) && "wrong number of subexpressions");
5064 for (unsigned i = 0; i != args.size(); i++)
5065 SubExprs[i] = args[i];
5066 setDependence(computeDependence(this));
5067 }
5068
getNumSubExprs(AtomicOp Op)5069 unsigned AtomicExpr::getNumSubExprs(AtomicOp Op) {
5070 switch (Op) {
5071 case AO__c11_atomic_init:
5072 case AO__opencl_atomic_init:
5073 case AO__c11_atomic_load:
5074 case AO__atomic_load_n:
5075 case AO__atomic_test_and_set:
5076 case AO__atomic_clear:
5077 return 2;
5078
5079 case AO__scoped_atomic_load_n:
5080 case AO__opencl_atomic_load:
5081 case AO__hip_atomic_load:
5082 case AO__c11_atomic_store:
5083 case AO__c11_atomic_exchange:
5084 case AO__atomic_load:
5085 case AO__atomic_store:
5086 case AO__atomic_store_n:
5087 case AO__atomic_exchange_n:
5088 case AO__c11_atomic_fetch_add:
5089 case AO__c11_atomic_fetch_sub:
5090 case AO__c11_atomic_fetch_and:
5091 case AO__c11_atomic_fetch_or:
5092 case AO__c11_atomic_fetch_xor:
5093 case AO__c11_atomic_fetch_nand:
5094 case AO__c11_atomic_fetch_max:
5095 case AO__c11_atomic_fetch_min:
5096 case AO__atomic_fetch_add:
5097 case AO__atomic_fetch_sub:
5098 case AO__atomic_fetch_and:
5099 case AO__atomic_fetch_or:
5100 case AO__atomic_fetch_xor:
5101 case AO__atomic_fetch_nand:
5102 case AO__atomic_add_fetch:
5103 case AO__atomic_sub_fetch:
5104 case AO__atomic_and_fetch:
5105 case AO__atomic_or_fetch:
5106 case AO__atomic_xor_fetch:
5107 case AO__atomic_nand_fetch:
5108 case AO__atomic_min_fetch:
5109 case AO__atomic_max_fetch:
5110 case AO__atomic_fetch_min:
5111 case AO__atomic_fetch_max:
5112 return 3;
5113
5114 case AO__scoped_atomic_load:
5115 case AO__scoped_atomic_store:
5116 case AO__scoped_atomic_store_n:
5117 case AO__scoped_atomic_fetch_add:
5118 case AO__scoped_atomic_fetch_sub:
5119 case AO__scoped_atomic_fetch_and:
5120 case AO__scoped_atomic_fetch_or:
5121 case AO__scoped_atomic_fetch_xor:
5122 case AO__scoped_atomic_fetch_nand:
5123 case AO__scoped_atomic_add_fetch:
5124 case AO__scoped_atomic_sub_fetch:
5125 case AO__scoped_atomic_and_fetch:
5126 case AO__scoped_atomic_or_fetch:
5127 case AO__scoped_atomic_xor_fetch:
5128 case AO__scoped_atomic_nand_fetch:
5129 case AO__scoped_atomic_min_fetch:
5130 case AO__scoped_atomic_max_fetch:
5131 case AO__scoped_atomic_fetch_min:
5132 case AO__scoped_atomic_fetch_max:
5133 case AO__scoped_atomic_exchange_n:
5134 case AO__hip_atomic_exchange:
5135 case AO__hip_atomic_fetch_add:
5136 case AO__hip_atomic_fetch_sub:
5137 case AO__hip_atomic_fetch_and:
5138 case AO__hip_atomic_fetch_or:
5139 case AO__hip_atomic_fetch_xor:
5140 case AO__hip_atomic_fetch_min:
5141 case AO__hip_atomic_fetch_max:
5142 case AO__opencl_atomic_store:
5143 case AO__hip_atomic_store:
5144 case AO__opencl_atomic_exchange:
5145 case AO__opencl_atomic_fetch_add:
5146 case AO__opencl_atomic_fetch_sub:
5147 case AO__opencl_atomic_fetch_and:
5148 case AO__opencl_atomic_fetch_or:
5149 case AO__opencl_atomic_fetch_xor:
5150 case AO__opencl_atomic_fetch_min:
5151 case AO__opencl_atomic_fetch_max:
5152 case AO__atomic_exchange:
5153 return 4;
5154
5155 case AO__scoped_atomic_exchange:
5156 case AO__c11_atomic_compare_exchange_strong:
5157 case AO__c11_atomic_compare_exchange_weak:
5158 return 5;
5159 case AO__hip_atomic_compare_exchange_strong:
5160 case AO__opencl_atomic_compare_exchange_strong:
5161 case AO__opencl_atomic_compare_exchange_weak:
5162 case AO__hip_atomic_compare_exchange_weak:
5163 case AO__atomic_compare_exchange:
5164 case AO__atomic_compare_exchange_n:
5165 return 6;
5166
5167 case AO__scoped_atomic_compare_exchange:
5168 case AO__scoped_atomic_compare_exchange_n:
5169 return 7;
5170 }
5171 llvm_unreachable("unknown atomic op");
5172 }
5173
getValueType() const5174 QualType AtomicExpr::getValueType() const {
5175 auto T = getPtr()->getType()->castAs<PointerType>()->getPointeeType();
5176 if (auto AT = T->getAs<AtomicType>())
5177 return AT->getValueType();
5178 return T;
5179 }
5180
getBaseOriginalType(const Expr * Base)5181 QualType ArraySectionExpr::getBaseOriginalType(const Expr *Base) {
5182 unsigned ArraySectionCount = 0;
5183 while (auto *OASE = dyn_cast<ArraySectionExpr>(Base->IgnoreParens())) {
5184 Base = OASE->getBase();
5185 ++ArraySectionCount;
5186 }
5187 while (auto *ASE =
5188 dyn_cast<ArraySubscriptExpr>(Base->IgnoreParenImpCasts())) {
5189 Base = ASE->getBase();
5190 ++ArraySectionCount;
5191 }
5192 Base = Base->IgnoreParenImpCasts();
5193 auto OriginalTy = Base->getType();
5194 if (auto *DRE = dyn_cast<DeclRefExpr>(Base))
5195 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
5196 OriginalTy = PVD->getOriginalType().getNonReferenceType();
5197
5198 for (unsigned Cnt = 0; Cnt < ArraySectionCount; ++Cnt) {
5199 if (OriginalTy->isAnyPointerType())
5200 OriginalTy = OriginalTy->getPointeeType();
5201 else if (OriginalTy->isArrayType())
5202 OriginalTy = OriginalTy->castAsArrayTypeUnsafe()->getElementType();
5203 else
5204 return {};
5205 }
5206 return OriginalTy;
5207 }
5208
RecoveryExpr(ASTContext & Ctx,QualType T,SourceLocation BeginLoc,SourceLocation EndLoc,ArrayRef<Expr * > SubExprs)5209 RecoveryExpr::RecoveryExpr(ASTContext &Ctx, QualType T, SourceLocation BeginLoc,
5210 SourceLocation EndLoc, ArrayRef<Expr *> SubExprs)
5211 : Expr(RecoveryExprClass, T.getNonReferenceType(),
5212 T->isDependentType() ? VK_LValue : getValueKindForType(T),
5213 OK_Ordinary),
5214 BeginLoc(BeginLoc), EndLoc(EndLoc), NumExprs(SubExprs.size()) {
5215 assert(!T.isNull());
5216 assert(!llvm::is_contained(SubExprs, nullptr));
5217
5218 llvm::copy(SubExprs, getTrailingObjects());
5219 setDependence(computeDependence(this));
5220 }
5221
Create(ASTContext & Ctx,QualType T,SourceLocation BeginLoc,SourceLocation EndLoc,ArrayRef<Expr * > SubExprs)5222 RecoveryExpr *RecoveryExpr::Create(ASTContext &Ctx, QualType T,
5223 SourceLocation BeginLoc,
5224 SourceLocation EndLoc,
5225 ArrayRef<Expr *> SubExprs) {
5226 void *Mem = Ctx.Allocate(totalSizeToAlloc<Expr *>(SubExprs.size()),
5227 alignof(RecoveryExpr));
5228 return new (Mem) RecoveryExpr(Ctx, T, BeginLoc, EndLoc, SubExprs);
5229 }
5230
CreateEmpty(ASTContext & Ctx,unsigned NumSubExprs)5231 RecoveryExpr *RecoveryExpr::CreateEmpty(ASTContext &Ctx, unsigned NumSubExprs) {
5232 void *Mem = Ctx.Allocate(totalSizeToAlloc<Expr *>(NumSubExprs),
5233 alignof(RecoveryExpr));
5234 return new (Mem) RecoveryExpr(EmptyShell(), NumSubExprs);
5235 }
5236
setDimensions(ArrayRef<Expr * > Dims)5237 void OMPArrayShapingExpr::setDimensions(ArrayRef<Expr *> Dims) {
5238 assert(
5239 NumDims == Dims.size() &&
5240 "Preallocated number of dimensions is different from the provided one.");
5241 llvm::copy(Dims, getTrailingObjects<Expr *>());
5242 }
5243
setBracketsRanges(ArrayRef<SourceRange> BR)5244 void OMPArrayShapingExpr::setBracketsRanges(ArrayRef<SourceRange> BR) {
5245 assert(
5246 NumDims == BR.size() &&
5247 "Preallocated number of dimensions is different from the provided one.");
5248 llvm::copy(BR, getTrailingObjects<SourceRange>());
5249 }
5250
OMPArrayShapingExpr(QualType ExprTy,Expr * Op,SourceLocation L,SourceLocation R,ArrayRef<Expr * > Dims)5251 OMPArrayShapingExpr::OMPArrayShapingExpr(QualType ExprTy, Expr *Op,
5252 SourceLocation L, SourceLocation R,
5253 ArrayRef<Expr *> Dims)
5254 : Expr(OMPArrayShapingExprClass, ExprTy, VK_LValue, OK_Ordinary), LPLoc(L),
5255 RPLoc(R), NumDims(Dims.size()) {
5256 setBase(Op);
5257 setDimensions(Dims);
5258 setDependence(computeDependence(this));
5259 }
5260
5261 OMPArrayShapingExpr *
Create(const ASTContext & Context,QualType T,Expr * Op,SourceLocation L,SourceLocation R,ArrayRef<Expr * > Dims,ArrayRef<SourceRange> BracketRanges)5262 OMPArrayShapingExpr::Create(const ASTContext &Context, QualType T, Expr *Op,
5263 SourceLocation L, SourceLocation R,
5264 ArrayRef<Expr *> Dims,
5265 ArrayRef<SourceRange> BracketRanges) {
5266 assert(Dims.size() == BracketRanges.size() &&
5267 "Different number of dimensions and brackets ranges.");
5268 void *Mem = Context.Allocate(
5269 totalSizeToAlloc<Expr *, SourceRange>(Dims.size() + 1, Dims.size()),
5270 alignof(OMPArrayShapingExpr));
5271 auto *E = new (Mem) OMPArrayShapingExpr(T, Op, L, R, Dims);
5272 E->setBracketsRanges(BracketRanges);
5273 return E;
5274 }
5275
CreateEmpty(const ASTContext & Context,unsigned NumDims)5276 OMPArrayShapingExpr *OMPArrayShapingExpr::CreateEmpty(const ASTContext &Context,
5277 unsigned NumDims) {
5278 void *Mem = Context.Allocate(
5279 totalSizeToAlloc<Expr *, SourceRange>(NumDims + 1, NumDims),
5280 alignof(OMPArrayShapingExpr));
5281 return new (Mem) OMPArrayShapingExpr(EmptyShell(), NumDims);
5282 }
5283
setIteratorDeclaration(unsigned I,Decl * D)5284 void OMPIteratorExpr::setIteratorDeclaration(unsigned I, Decl *D) {
5285 getTrailingObjects<Decl *>(NumIterators)[I] = D;
5286 }
5287
setAssignmentLoc(unsigned I,SourceLocation Loc)5288 void OMPIteratorExpr::setAssignmentLoc(unsigned I, SourceLocation Loc) {
5289 assert(I < NumIterators &&
5290 "Idx is greater or equal the number of iterators definitions.");
5291 getTrailingObjects<
5292 SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
5293 static_cast<int>(RangeLocOffset::AssignLoc)] = Loc;
5294 }
5295
setIteratorRange(unsigned I,Expr * Begin,SourceLocation ColonLoc,Expr * End,SourceLocation SecondColonLoc,Expr * Step)5296 void OMPIteratorExpr::setIteratorRange(unsigned I, Expr *Begin,
5297 SourceLocation ColonLoc, Expr *End,
5298 SourceLocation SecondColonLoc,
5299 Expr *Step) {
5300 assert(I < NumIterators &&
5301 "Idx is greater or equal the number of iterators definitions.");
5302 getTrailingObjects<Expr *>()[I * static_cast<int>(RangeExprOffset::Total) +
5303 static_cast<int>(RangeExprOffset::Begin)] =
5304 Begin;
5305 getTrailingObjects<Expr *>()[I * static_cast<int>(RangeExprOffset::Total) +
5306 static_cast<int>(RangeExprOffset::End)] = End;
5307 getTrailingObjects<Expr *>()[I * static_cast<int>(RangeExprOffset::Total) +
5308 static_cast<int>(RangeExprOffset::Step)] = Step;
5309 getTrailingObjects<
5310 SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
5311 static_cast<int>(RangeLocOffset::FirstColonLoc)] =
5312 ColonLoc;
5313 getTrailingObjects<
5314 SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
5315 static_cast<int>(RangeLocOffset::SecondColonLoc)] =
5316 SecondColonLoc;
5317 }
5318
getIteratorDecl(unsigned I)5319 Decl *OMPIteratorExpr::getIteratorDecl(unsigned I) {
5320 return getTrailingObjects<Decl *>()[I];
5321 }
5322
getIteratorRange(unsigned I)5323 OMPIteratorExpr::IteratorRange OMPIteratorExpr::getIteratorRange(unsigned I) {
5324 IteratorRange Res;
5325 Res.Begin =
5326 getTrailingObjects<Expr *>()[I * static_cast<int>(
5327 RangeExprOffset::Total) +
5328 static_cast<int>(RangeExprOffset::Begin)];
5329 Res.End =
5330 getTrailingObjects<Expr *>()[I * static_cast<int>(
5331 RangeExprOffset::Total) +
5332 static_cast<int>(RangeExprOffset::End)];
5333 Res.Step =
5334 getTrailingObjects<Expr *>()[I * static_cast<int>(
5335 RangeExprOffset::Total) +
5336 static_cast<int>(RangeExprOffset::Step)];
5337 return Res;
5338 }
5339
getAssignLoc(unsigned I) const5340 SourceLocation OMPIteratorExpr::getAssignLoc(unsigned I) const {
5341 return getTrailingObjects<
5342 SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
5343 static_cast<int>(RangeLocOffset::AssignLoc)];
5344 }
5345
getColonLoc(unsigned I) const5346 SourceLocation OMPIteratorExpr::getColonLoc(unsigned I) const {
5347 return getTrailingObjects<
5348 SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
5349 static_cast<int>(RangeLocOffset::FirstColonLoc)];
5350 }
5351
getSecondColonLoc(unsigned I) const5352 SourceLocation OMPIteratorExpr::getSecondColonLoc(unsigned I) const {
5353 return getTrailingObjects<
5354 SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
5355 static_cast<int>(RangeLocOffset::SecondColonLoc)];
5356 }
5357
setHelper(unsigned I,const OMPIteratorHelperData & D)5358 void OMPIteratorExpr::setHelper(unsigned I, const OMPIteratorHelperData &D) {
5359 getTrailingObjects<OMPIteratorHelperData>()[I] = D;
5360 }
5361
getHelper(unsigned I)5362 OMPIteratorHelperData &OMPIteratorExpr::getHelper(unsigned I) {
5363 return getTrailingObjects<OMPIteratorHelperData>()[I];
5364 }
5365
getHelper(unsigned I) const5366 const OMPIteratorHelperData &OMPIteratorExpr::getHelper(unsigned I) const {
5367 return getTrailingObjects<OMPIteratorHelperData>()[I];
5368 }
5369
OMPIteratorExpr(QualType ExprTy,SourceLocation IteratorKwLoc,SourceLocation L,SourceLocation R,ArrayRef<OMPIteratorExpr::IteratorDefinition> Data,ArrayRef<OMPIteratorHelperData> Helpers)5370 OMPIteratorExpr::OMPIteratorExpr(
5371 QualType ExprTy, SourceLocation IteratorKwLoc, SourceLocation L,
5372 SourceLocation R, ArrayRef<OMPIteratorExpr::IteratorDefinition> Data,
5373 ArrayRef<OMPIteratorHelperData> Helpers)
5374 : Expr(OMPIteratorExprClass, ExprTy, VK_LValue, OK_Ordinary),
5375 IteratorKwLoc(IteratorKwLoc), LPLoc(L), RPLoc(R),
5376 NumIterators(Data.size()) {
5377 for (unsigned I = 0, E = Data.size(); I < E; ++I) {
5378 const IteratorDefinition &D = Data[I];
5379 setIteratorDeclaration(I, D.IteratorDecl);
5380 setAssignmentLoc(I, D.AssignmentLoc);
5381 setIteratorRange(I, D.Range.Begin, D.ColonLoc, D.Range.End,
5382 D.SecondColonLoc, D.Range.Step);
5383 setHelper(I, Helpers[I]);
5384 }
5385 setDependence(computeDependence(this));
5386 }
5387
5388 OMPIteratorExpr *
Create(const ASTContext & Context,QualType T,SourceLocation IteratorKwLoc,SourceLocation L,SourceLocation R,ArrayRef<OMPIteratorExpr::IteratorDefinition> Data,ArrayRef<OMPIteratorHelperData> Helpers)5389 OMPIteratorExpr::Create(const ASTContext &Context, QualType T,
5390 SourceLocation IteratorKwLoc, SourceLocation L,
5391 SourceLocation R,
5392 ArrayRef<OMPIteratorExpr::IteratorDefinition> Data,
5393 ArrayRef<OMPIteratorHelperData> Helpers) {
5394 assert(Data.size() == Helpers.size() &&
5395 "Data and helpers must have the same size.");
5396 void *Mem = Context.Allocate(
5397 totalSizeToAlloc<Decl *, Expr *, SourceLocation, OMPIteratorHelperData>(
5398 Data.size(), Data.size() * static_cast<int>(RangeExprOffset::Total),
5399 Data.size() * static_cast<int>(RangeLocOffset::Total),
5400 Helpers.size()),
5401 alignof(OMPIteratorExpr));
5402 return new (Mem) OMPIteratorExpr(T, IteratorKwLoc, L, R, Data, Helpers);
5403 }
5404
CreateEmpty(const ASTContext & Context,unsigned NumIterators)5405 OMPIteratorExpr *OMPIteratorExpr::CreateEmpty(const ASTContext &Context,
5406 unsigned NumIterators) {
5407 void *Mem = Context.Allocate(
5408 totalSizeToAlloc<Decl *, Expr *, SourceLocation, OMPIteratorHelperData>(
5409 NumIterators, NumIterators * static_cast<int>(RangeExprOffset::Total),
5410 NumIterators * static_cast<int>(RangeLocOffset::Total), NumIterators),
5411 alignof(OMPIteratorExpr));
5412 return new (Mem) OMPIteratorExpr(EmptyShell(), NumIterators);
5413 }
5414
Create(const ASTContext & C,QualType Ty,OpaqueValueExpr * Base,OpaqueValueExpr * OpV,Expr * WB,bool IsInOut)5415 HLSLOutArgExpr *HLSLOutArgExpr::Create(const ASTContext &C, QualType Ty,
5416 OpaqueValueExpr *Base,
5417 OpaqueValueExpr *OpV, Expr *WB,
5418 bool IsInOut) {
5419 return new (C) HLSLOutArgExpr(Ty, Base, OpV, WB, IsInOut);
5420 }
5421
CreateEmpty(const ASTContext & C)5422 HLSLOutArgExpr *HLSLOutArgExpr::CreateEmpty(const ASTContext &C) {
5423 return new (C) HLSLOutArgExpr(EmptyShell());
5424 }
5425
Create(const ASTContext & C,SourceLocation Loc)5426 OpenACCAsteriskSizeExpr *OpenACCAsteriskSizeExpr::Create(const ASTContext &C,
5427 SourceLocation Loc) {
5428 return new (C) OpenACCAsteriskSizeExpr(Loc, C.IntTy);
5429 }
5430
5431 OpenACCAsteriskSizeExpr *
CreateEmpty(const ASTContext & C)5432 OpenACCAsteriskSizeExpr::CreateEmpty(const ASTContext &C) {
5433 return new (C) OpenACCAsteriskSizeExpr({}, C.IntTy);
5434 }
5435
CreateEmpty(const ASTContext & C,bool hasFPFeatures)5436 ConvertVectorExpr *ConvertVectorExpr::CreateEmpty(const ASTContext &C,
5437 bool hasFPFeatures) {
5438 void *Mem = C.Allocate(totalSizeToAlloc<FPOptionsOverride>(hasFPFeatures),
5439 alignof(ConvertVectorExpr));
5440 return new (Mem) ConvertVectorExpr(hasFPFeatures, EmptyShell());
5441 }
5442
Create(const ASTContext & C,Expr * SrcExpr,TypeSourceInfo * TI,QualType DstType,ExprValueKind VK,ExprObjectKind OK,SourceLocation BuiltinLoc,SourceLocation RParenLoc,FPOptionsOverride FPFeatures)5443 ConvertVectorExpr *ConvertVectorExpr::Create(
5444 const ASTContext &C, Expr *SrcExpr, TypeSourceInfo *TI, QualType DstType,
5445 ExprValueKind VK, ExprObjectKind OK, SourceLocation BuiltinLoc,
5446 SourceLocation RParenLoc, FPOptionsOverride FPFeatures) {
5447 bool HasFPFeatures = FPFeatures.requiresTrailingStorage();
5448 unsigned Size = totalSizeToAlloc<FPOptionsOverride>(HasFPFeatures);
5449 void *Mem = C.Allocate(Size, alignof(ConvertVectorExpr));
5450 return new (Mem) ConvertVectorExpr(SrcExpr, TI, DstType, VK, OK, BuiltinLoc,
5451 RParenLoc, FPFeatures);
5452 }
5453
getOrCreateStaticValue(ASTContext & Ctx) const5454 APValue &CompoundLiteralExpr::getOrCreateStaticValue(ASTContext &Ctx) const {
5455 assert(hasStaticStorage());
5456 if (!StaticValue) {
5457 StaticValue = new (Ctx) APValue;
5458 Ctx.addDestruction(StaticValue);
5459 }
5460 return *StaticValue;
5461 }
5462
getStaticValue() const5463 APValue &CompoundLiteralExpr::getStaticValue() const {
5464 assert(StaticValue);
5465 return *StaticValue;
5466 }
5467