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