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