1 //===--- Expr.cpp - Expression AST Node Implementation --------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements the Expr class and subclasses.
11 //===----------------------------------------------------------------------===//
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/ComputeDependence.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/DependenceFlags.h"
22 #include "clang/AST/EvaluatedExprVisitor.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/Mangle.h"
25 #include "clang/AST/RecordLayout.h"
26 #include "clang/AST/StmtVisitor.h"
27 #include "clang/Basic/Builtins.h"
28 #include "clang/Basic/CharInfo.h"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/Lexer.h"
32 #include "clang/Lex/LiteralSupport.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/raw_ostream.h"
37 using namespace clang;
39 const Expr *Expr::getBestDynamicClassTypeExpr() const {
42 E = E->ignoreParenBaseCasts();
44 // Follow the RHS of a comma operator.
45 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
46 if (BO->getOpcode() == BO_Comma) {
52 // Step into initializer for materialized temporaries.
53 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
54 E = MTE->getSubExpr();
64 const CXXRecordDecl *Expr::getBestDynamicClassType() const {
65 const Expr *E = getBestDynamicClassTypeExpr();
66 QualType DerivedType = E->getType();
67 if (const PointerType *PTy = DerivedType->getAs<PointerType>())
68 DerivedType = PTy->getPointeeType();
70 if (DerivedType->isDependentType())
73 const RecordType *Ty = DerivedType->castAs<RecordType>();
74 Decl *D = Ty->getDecl();
75 return cast<CXXRecordDecl>(D);
78 const Expr *Expr::skipRValueSubobjectAdjustments(
79 SmallVectorImpl<const Expr *> &CommaLHSs,
80 SmallVectorImpl<SubobjectAdjustment> &Adjustments) const {
83 E = E->IgnoreParens();
85 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
86 if ((CE->getCastKind() == CK_DerivedToBase ||
87 CE->getCastKind() == CK_UncheckedDerivedToBase) &&
88 E->getType()->isRecordType()) {
91 cast<CXXRecordDecl>(E->getType()->castAs<RecordType>()->getDecl());
92 Adjustments.push_back(SubobjectAdjustment(CE, Derived));
96 if (CE->getCastKind() == CK_NoOp) {
100 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
101 if (!ME->isArrow()) {
102 assert(ME->getBase()->getType()->isRecordType());
103 if (FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
104 if (!Field->isBitField() && !Field->getType()->isReferenceType()) {
106 Adjustments.push_back(SubobjectAdjustment(Field));
111 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
112 if (BO->getOpcode() == BO_PtrMemD) {
113 assert(BO->getRHS()->isRValue());
115 const MemberPointerType *MPT =
116 BO->getRHS()->getType()->getAs<MemberPointerType>();
117 Adjustments.push_back(SubobjectAdjustment(MPT, BO->getRHS()));
119 } else if (BO->getOpcode() == BO_Comma) {
120 CommaLHSs.push_back(BO->getLHS());
132 bool Expr::isKnownToHaveBooleanValue(bool Semantic) const {
133 const Expr *E = IgnoreParens();
135 // If this value has _Bool type, it is obvious 0/1.
136 if (E->getType()->isBooleanType()) return true;
137 // If this is a non-scalar-integer type, we don't care enough to try.
138 if (!E->getType()->isIntegralOrEnumerationType()) return false;
140 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
141 switch (UO->getOpcode()) {
143 return UO->getSubExpr()->isKnownToHaveBooleanValue(Semantic);
151 // Only look through implicit casts. If the user writes
152 // '(int) (a && b)' treat it as an arbitrary int.
153 // FIXME: Should we look through any cast expression in !Semantic mode?
154 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
155 return CE->getSubExpr()->isKnownToHaveBooleanValue(Semantic);
157 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
158 switch (BO->getOpcode()) {
159 default: return false;
160 case BO_LT: // Relational operators.
164 case BO_EQ: // Equality operators.
166 case BO_LAnd: // AND operator.
167 case BO_LOr: // Logical OR operator.
170 case BO_And: // Bitwise AND operator.
171 case BO_Xor: // Bitwise XOR operator.
172 case BO_Or: // Bitwise OR operator.
173 // Handle things like (x==2)|(y==12).
174 return BO->getLHS()->isKnownToHaveBooleanValue(Semantic) &&
175 BO->getRHS()->isKnownToHaveBooleanValue(Semantic);
179 return BO->getRHS()->isKnownToHaveBooleanValue(Semantic);
183 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
184 return CO->getTrueExpr()->isKnownToHaveBooleanValue(Semantic) &&
185 CO->getFalseExpr()->isKnownToHaveBooleanValue(Semantic);
187 if (isa<ObjCBoolLiteralExpr>(E))
190 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
191 return OVE->getSourceExpr()->isKnownToHaveBooleanValue(Semantic);
193 if (const FieldDecl *FD = E->getSourceBitField())
194 if (!Semantic && FD->getType()->isUnsignedIntegerType() &&
195 !FD->getBitWidth()->isValueDependent() &&
196 FD->getBitWidthValue(FD->getASTContext()) == 1)
202 // Amusing macro metaprogramming hack: check whether a class provides
203 // a more specific implementation of getExprLoc().
205 // See also Stmt.cpp:{getBeginLoc(),getEndLoc()}.
207 /// This implementation is used when a class provides a custom
208 /// implementation of getExprLoc.
209 template <class E, class T>
210 SourceLocation getExprLocImpl(const Expr *expr,
211 SourceLocation (T::*v)() const) {
212 return static_cast<const E*>(expr)->getExprLoc();
215 /// This implementation is used when a class doesn't provide
216 /// a custom implementation of getExprLoc. Overload resolution
217 /// should pick it over the implementation above because it's
218 /// more specialized according to function template partial ordering.
220 SourceLocation getExprLocImpl(const Expr *expr,
221 SourceLocation (Expr::*v)() const) {
222 return static_cast<const E *>(expr)->getBeginLoc();
226 SourceLocation Expr::getExprLoc() const {
227 switch (getStmtClass()) {
228 case Stmt::NoStmtClass: llvm_unreachable("statement without class");
229 #define ABSTRACT_STMT(type)
230 #define STMT(type, base) \
231 case Stmt::type##Class: break;
232 #define EXPR(type, base) \
233 case Stmt::type##Class: return getExprLocImpl<type>(this, &type::getExprLoc);
234 #include "clang/AST/StmtNodes.inc"
236 llvm_unreachable("unknown expression kind");
239 //===----------------------------------------------------------------------===//
240 // Primary Expressions.
241 //===----------------------------------------------------------------------===//
243 static void AssertResultStorageKind(ConstantExpr::ResultStorageKind Kind) {
244 assert((Kind == ConstantExpr::RSK_APValue ||
245 Kind == ConstantExpr::RSK_Int64 || Kind == ConstantExpr::RSK_None) &&
246 "Invalid StorageKind Value");
250 ConstantExpr::ResultStorageKind
251 ConstantExpr::getStorageKind(const APValue &Value) {
252 switch (Value.getKind()) {
254 case APValue::Indeterminate:
255 return ConstantExpr::RSK_None;
257 if (!Value.getInt().needsCleanup())
258 return ConstantExpr::RSK_Int64;
261 return ConstantExpr::RSK_APValue;
265 ConstantExpr::ResultStorageKind
266 ConstantExpr::getStorageKind(const Type *T, const ASTContext &Context) {
267 if (T->isIntegralOrEnumerationType() && Context.getTypeInfo(T).Width <= 64)
268 return ConstantExpr::RSK_Int64;
269 return ConstantExpr::RSK_APValue;
272 ConstantExpr::ConstantExpr(Expr *SubExpr, ResultStorageKind StorageKind,
273 bool IsImmediateInvocation)
274 : FullExpr(ConstantExprClass, SubExpr) {
275 ConstantExprBits.ResultKind = StorageKind;
276 ConstantExprBits.APValueKind = APValue::None;
277 ConstantExprBits.IsUnsigned = false;
278 ConstantExprBits.BitWidth = 0;
279 ConstantExprBits.HasCleanup = false;
280 ConstantExprBits.IsImmediateInvocation = IsImmediateInvocation;
282 if (StorageKind == ConstantExpr::RSK_APValue)
283 ::new (getTrailingObjects<APValue>()) APValue();
286 ConstantExpr *ConstantExpr::Create(const ASTContext &Context, Expr *E,
287 ResultStorageKind StorageKind,
288 bool IsImmediateInvocation) {
289 assert(!isa<ConstantExpr>(E));
290 AssertResultStorageKind(StorageKind);
292 unsigned Size = totalSizeToAlloc<APValue, uint64_t>(
293 StorageKind == ConstantExpr::RSK_APValue,
294 StorageKind == ConstantExpr::RSK_Int64);
295 void *Mem = Context.Allocate(Size, alignof(ConstantExpr));
296 return new (Mem) ConstantExpr(E, StorageKind, IsImmediateInvocation);
299 ConstantExpr *ConstantExpr::Create(const ASTContext &Context, Expr *E,
300 const APValue &Result) {
301 ResultStorageKind StorageKind = getStorageKind(Result);
302 ConstantExpr *Self = Create(Context, E, StorageKind);
303 Self->SetResult(Result, Context);
307 ConstantExpr::ConstantExpr(EmptyShell Empty, ResultStorageKind StorageKind)
308 : FullExpr(ConstantExprClass, Empty) {
309 ConstantExprBits.ResultKind = StorageKind;
311 if (StorageKind == ConstantExpr::RSK_APValue)
312 ::new (getTrailingObjects<APValue>()) APValue();
315 ConstantExpr *ConstantExpr::CreateEmpty(const ASTContext &Context,
316 ResultStorageKind StorageKind) {
317 AssertResultStorageKind(StorageKind);
319 unsigned Size = totalSizeToAlloc<APValue, uint64_t>(
320 StorageKind == ConstantExpr::RSK_APValue,
321 StorageKind == ConstantExpr::RSK_Int64);
322 void *Mem = Context.Allocate(Size, alignof(ConstantExpr));
323 return new (Mem) ConstantExpr(EmptyShell(), StorageKind);
326 void ConstantExpr::MoveIntoResult(APValue &Value, const ASTContext &Context) {
327 assert((unsigned)getStorageKind(Value) <= ConstantExprBits.ResultKind &&
328 "Invalid storage for this value kind");
329 ConstantExprBits.APValueKind = Value.getKind();
330 switch (ConstantExprBits.ResultKind) {
334 Int64Result() = *Value.getInt().getRawData();
335 ConstantExprBits.BitWidth = Value.getInt().getBitWidth();
336 ConstantExprBits.IsUnsigned = Value.getInt().isUnsigned();
339 if (!ConstantExprBits.HasCleanup && Value.needsCleanup()) {
340 ConstantExprBits.HasCleanup = true;
341 Context.addDestruction(&APValueResult());
343 APValueResult() = std::move(Value);
346 llvm_unreachable("Invalid ResultKind Bits");
349 llvm::APSInt ConstantExpr::getResultAsAPSInt() const {
350 switch (ConstantExprBits.ResultKind) {
351 case ConstantExpr::RSK_APValue:
352 return APValueResult().getInt();
353 case ConstantExpr::RSK_Int64:
354 return llvm::APSInt(llvm::APInt(ConstantExprBits.BitWidth, Int64Result()),
355 ConstantExprBits.IsUnsigned);
357 llvm_unreachable("invalid Accessor");
361 APValue ConstantExpr::getAPValueResult() const {
362 assert(hasAPValueResult());
364 switch (ConstantExprBits.ResultKind) {
365 case ConstantExpr::RSK_APValue:
366 return APValueResult();
367 case ConstantExpr::RSK_Int64:
369 llvm::APSInt(llvm::APInt(ConstantExprBits.BitWidth, Int64Result()),
370 ConstantExprBits.IsUnsigned));
371 case ConstantExpr::RSK_None:
374 llvm_unreachable("invalid ResultKind");
377 DeclRefExpr::DeclRefExpr(const ASTContext &Ctx, ValueDecl *D,
378 bool RefersToEnclosingVariableOrCapture, QualType T,
379 ExprValueKind VK, SourceLocation L,
380 const DeclarationNameLoc &LocInfo,
381 NonOdrUseReason NOUR)
382 : Expr(DeclRefExprClass, T, VK, OK_Ordinary), D(D), DNLoc(LocInfo) {
383 DeclRefExprBits.HasQualifier = false;
384 DeclRefExprBits.HasTemplateKWAndArgsInfo = false;
385 DeclRefExprBits.HasFoundDecl = false;
386 DeclRefExprBits.HadMultipleCandidates = false;
387 DeclRefExprBits.RefersToEnclosingVariableOrCapture =
388 RefersToEnclosingVariableOrCapture;
389 DeclRefExprBits.NonOdrUseReason = NOUR;
390 DeclRefExprBits.Loc = L;
391 setDependence(computeDependence(this, Ctx));
394 DeclRefExpr::DeclRefExpr(const ASTContext &Ctx,
395 NestedNameSpecifierLoc QualifierLoc,
396 SourceLocation TemplateKWLoc, ValueDecl *D,
397 bool RefersToEnclosingVariableOrCapture,
398 const DeclarationNameInfo &NameInfo, NamedDecl *FoundD,
399 const TemplateArgumentListInfo *TemplateArgs,
400 QualType T, ExprValueKind VK, NonOdrUseReason NOUR)
401 : Expr(DeclRefExprClass, T, VK, OK_Ordinary), D(D),
402 DNLoc(NameInfo.getInfo()) {
403 DeclRefExprBits.Loc = NameInfo.getLoc();
404 DeclRefExprBits.HasQualifier = QualifierLoc ? 1 : 0;
406 new (getTrailingObjects<NestedNameSpecifierLoc>())
407 NestedNameSpecifierLoc(QualifierLoc);
408 DeclRefExprBits.HasFoundDecl = FoundD ? 1 : 0;
410 *getTrailingObjects<NamedDecl *>() = FoundD;
411 DeclRefExprBits.HasTemplateKWAndArgsInfo
412 = (TemplateArgs || TemplateKWLoc.isValid()) ? 1 : 0;
413 DeclRefExprBits.RefersToEnclosingVariableOrCapture =
414 RefersToEnclosingVariableOrCapture;
415 DeclRefExprBits.NonOdrUseReason = NOUR;
417 auto Deps = TemplateArgumentDependence::None;
418 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
419 TemplateKWLoc, *TemplateArgs, getTrailingObjects<TemplateArgumentLoc>(),
421 assert(!(Deps & TemplateArgumentDependence::Dependent) &&
422 "built a DeclRefExpr with dependent template args");
423 } else if (TemplateKWLoc.isValid()) {
424 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
427 DeclRefExprBits.HadMultipleCandidates = 0;
428 setDependence(computeDependence(this, Ctx));
431 DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,
432 NestedNameSpecifierLoc QualifierLoc,
433 SourceLocation TemplateKWLoc, ValueDecl *D,
434 bool RefersToEnclosingVariableOrCapture,
435 SourceLocation NameLoc, QualType T,
436 ExprValueKind VK, NamedDecl *FoundD,
437 const TemplateArgumentListInfo *TemplateArgs,
438 NonOdrUseReason NOUR) {
439 return Create(Context, QualifierLoc, TemplateKWLoc, D,
440 RefersToEnclosingVariableOrCapture,
441 DeclarationNameInfo(D->getDeclName(), NameLoc),
442 T, VK, FoundD, TemplateArgs, NOUR);
445 DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,
446 NestedNameSpecifierLoc QualifierLoc,
447 SourceLocation TemplateKWLoc, ValueDecl *D,
448 bool RefersToEnclosingVariableOrCapture,
449 const DeclarationNameInfo &NameInfo,
450 QualType T, ExprValueKind VK,
452 const TemplateArgumentListInfo *TemplateArgs,
453 NonOdrUseReason NOUR) {
454 // Filter out cases where the found Decl is the same as the value refenenced.
458 bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
460 totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
461 ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
462 QualifierLoc ? 1 : 0, FoundD ? 1 : 0,
463 HasTemplateKWAndArgsInfo ? 1 : 0,
464 TemplateArgs ? TemplateArgs->size() : 0);
466 void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));
467 return new (Mem) DeclRefExpr(Context, QualifierLoc, TemplateKWLoc, D,
468 RefersToEnclosingVariableOrCapture, NameInfo,
469 FoundD, TemplateArgs, T, VK, NOUR);
472 DeclRefExpr *DeclRefExpr::CreateEmpty(const ASTContext &Context,
475 bool HasTemplateKWAndArgsInfo,
476 unsigned NumTemplateArgs) {
477 assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo);
479 totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
480 ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
481 HasQualifier ? 1 : 0, HasFoundDecl ? 1 : 0, HasTemplateKWAndArgsInfo,
483 void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));
484 return new (Mem) DeclRefExpr(EmptyShell());
487 SourceLocation DeclRefExpr::getBeginLoc() const {
489 return getQualifierLoc().getBeginLoc();
490 return getNameInfo().getBeginLoc();
492 SourceLocation DeclRefExpr::getEndLoc() const {
493 if (hasExplicitTemplateArgs())
494 return getRAngleLoc();
495 return getNameInfo().getEndLoc();
498 PredefinedExpr::PredefinedExpr(SourceLocation L, QualType FNTy, IdentKind IK,
500 : Expr(PredefinedExprClass, FNTy, VK_LValue, OK_Ordinary) {
501 PredefinedExprBits.Kind = IK;
502 assert((getIdentKind() == IK) &&
503 "IdentKind do not fit in PredefinedExprBitfields!");
504 bool HasFunctionName = SL != nullptr;
505 PredefinedExprBits.HasFunctionName = HasFunctionName;
506 PredefinedExprBits.Loc = L;
509 setDependence(computeDependence(this));
512 PredefinedExpr::PredefinedExpr(SourceLocation L, QualType FnTy, IdentKind IK,
513 TypeSourceInfo *Info)
514 : Expr(PredefinedExprClass, FnTy, VK_LValue, OK_Ordinary) {
515 PredefinedExprBits.Kind = IK;
516 assert((getIdentKind() == IK) &&
517 "IdentKind do not fit in PredefinedExprBitFields!");
518 assert(IK == UniqueStableNameType &&
519 "Constructor only valid with UniqueStableNameType");
520 PredefinedExprBits.HasFunctionName = false;
521 PredefinedExprBits.Loc = L;
522 setTypeSourceInfo(Info);
523 setDependence(computeDependence(this));
526 PredefinedExpr::PredefinedExpr(SourceLocation L, QualType FnTy, IdentKind IK,
528 : Expr(PredefinedExprClass, FnTy, VK_LValue, OK_Ordinary) {
529 PredefinedExprBits.Kind = IK;
530 assert((getIdentKind() == IK) &&
531 "IdentKind do not fit in PredefinedExprBitFields!");
532 assert(IK == UniqueStableNameExpr &&
533 "Constructor only valid with UniqueStableNameExpr");
534 PredefinedExprBits.HasFunctionName = false;
535 PredefinedExprBits.Loc = L;
537 setDependence(computeDependence(this));
540 PredefinedExpr::PredefinedExpr(EmptyShell Empty, bool HasFunctionName)
541 : Expr(PredefinedExprClass, Empty) {
542 PredefinedExprBits.HasFunctionName = HasFunctionName;
545 PredefinedExpr *PredefinedExpr::Create(const ASTContext &Ctx, SourceLocation L,
546 QualType FNTy, IdentKind IK,
548 bool HasFunctionName = SL != nullptr;
549 void *Mem = Ctx.Allocate(
550 totalSizeToAlloc<Stmt *, Expr *, TypeSourceInfo *>(HasFunctionName, 0, 0),
551 alignof(PredefinedExpr));
552 return new (Mem) PredefinedExpr(L, FNTy, IK, SL);
555 PredefinedExpr *PredefinedExpr::Create(const ASTContext &Ctx, SourceLocation L,
556 QualType FNTy, IdentKind IK,
558 TypeSourceInfo *Info) {
559 assert(IK == UniqueStableNameType && "Only valid with UniqueStableNameType");
560 bool HasFunctionName = SL != nullptr;
561 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *, Expr *, TypeSourceInfo *>(
562 HasFunctionName, 0, !HasFunctionName),
563 alignof(PredefinedExpr));
565 return new (Mem) PredefinedExpr(L, FNTy, IK, SL);
566 return new (Mem) PredefinedExpr(L, FNTy, IK, Info);
569 PredefinedExpr *PredefinedExpr::Create(const ASTContext &Ctx, SourceLocation L,
570 QualType FNTy, IdentKind IK,
571 StringLiteral *SL, Expr *E) {
572 assert(IK == UniqueStableNameExpr && "Only valid with UniqueStableNameExpr");
573 bool HasFunctionName = SL != nullptr;
574 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *, Expr *, TypeSourceInfo *>(
575 HasFunctionName, !HasFunctionName, 0),
576 alignof(PredefinedExpr));
578 return new (Mem) PredefinedExpr(L, FNTy, IK, SL);
579 return new (Mem) PredefinedExpr(L, FNTy, IK, E);
582 PredefinedExpr *PredefinedExpr::CreateEmpty(const ASTContext &Ctx,
583 bool HasFunctionName) {
584 void *Mem = Ctx.Allocate(
585 totalSizeToAlloc<Stmt *, Expr *, TypeSourceInfo *>(HasFunctionName, 0, 0),
586 alignof(PredefinedExpr));
587 return new (Mem) PredefinedExpr(EmptyShell(), HasFunctionName);
590 StringRef PredefinedExpr::getIdentKindName(PredefinedExpr::IdentKind IK) {
595 return "__FUNCTION__";
597 return "__FUNCDNAME__";
599 return "L__FUNCTION__";
601 return "__PRETTY_FUNCTION__";
603 return "__FUNCSIG__";
605 return "L__FUNCSIG__";
606 case UniqueStableNameType:
607 case UniqueStableNameExpr:
608 return "__builtin_unique_stable_name";
609 case PrettyFunctionNoVirtual:
612 llvm_unreachable("Unknown ident kind for PredefinedExpr");
615 std::string PredefinedExpr::ComputeName(ASTContext &Context, IdentKind IK,
617 std::unique_ptr<MangleContext> Ctx{ItaniumMangleContext::create(
618 Context, Context.getDiagnostics(), /*IsUniqueNameMangler*/ true)};
620 Ty = Ty.getCanonicalType();
622 SmallString<256> Buffer;
623 llvm::raw_svector_ostream Out(Buffer);
624 Ctx->mangleTypeName(Ty, Out);
625 return std::string(Buffer.str());
628 // FIXME: Maybe this should use DeclPrinter with a special "print predefined
629 // expr" policy instead.
630 std::string PredefinedExpr::ComputeName(IdentKind IK, const Decl *CurrentDecl) {
631 ASTContext &Context = CurrentDecl->getASTContext();
633 if (IK == PredefinedExpr::FuncDName) {
634 if (const NamedDecl *ND = dyn_cast<NamedDecl>(CurrentDecl)) {
635 std::unique_ptr<MangleContext> MC;
636 MC.reset(Context.createMangleContext());
638 if (MC->shouldMangleDeclName(ND)) {
639 SmallString<256> Buffer;
640 llvm::raw_svector_ostream Out(Buffer);
642 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(ND))
643 GD = GlobalDecl(CD, Ctor_Base);
644 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(ND))
645 GD = GlobalDecl(DD, Dtor_Base);
646 else if (ND->hasAttr<CUDAGlobalAttr>())
647 GD = GlobalDecl(cast<FunctionDecl>(ND));
650 MC->mangleName(GD, Out);
652 if (!Buffer.empty() && Buffer.front() == '\01')
653 return std::string(Buffer.substr(1));
654 return std::string(Buffer.str());
656 return std::string(ND->getIdentifier()->getName());
660 if (isa<BlockDecl>(CurrentDecl)) {
661 // For blocks we only emit something if it is enclosed in a function
662 // For top-level block we'd like to include the name of variable, but we
663 // don't have it at this point.
664 auto DC = CurrentDecl->getDeclContext();
665 if (DC->isFileContext())
668 SmallString<256> Buffer;
669 llvm::raw_svector_ostream Out(Buffer);
670 if (auto *DCBlock = dyn_cast<BlockDecl>(DC))
671 // For nested blocks, propagate up to the parent.
672 Out << ComputeName(IK, DCBlock);
673 else if (auto *DCDecl = dyn_cast<Decl>(DC))
674 Out << ComputeName(IK, DCDecl) << "_block_invoke";
675 return std::string(Out.str());
677 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurrentDecl)) {
678 if (IK != PrettyFunction && IK != PrettyFunctionNoVirtual &&
679 IK != FuncSig && IK != LFuncSig)
680 return FD->getNameAsString();
682 SmallString<256> Name;
683 llvm::raw_svector_ostream Out(Name);
685 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
686 if (MD->isVirtual() && IK != PrettyFunctionNoVirtual)
692 PrintingPolicy Policy(Context.getLangOpts());
694 llvm::raw_string_ostream POut(Proto);
696 const FunctionDecl *Decl = FD;
697 if (const FunctionDecl* Pattern = FD->getTemplateInstantiationPattern())
699 const FunctionType *AFT = Decl->getType()->getAs<FunctionType>();
700 const FunctionProtoType *FT = nullptr;
701 if (FD->hasWrittenPrototype())
702 FT = dyn_cast<FunctionProtoType>(AFT);
704 if (IK == FuncSig || IK == LFuncSig) {
705 switch (AFT->getCallConv()) {
706 case CC_C: POut << "__cdecl "; break;
707 case CC_X86StdCall: POut << "__stdcall "; break;
708 case CC_X86FastCall: POut << "__fastcall "; break;
709 case CC_X86ThisCall: POut << "__thiscall "; break;
710 case CC_X86VectorCall: POut << "__vectorcall "; break;
711 case CC_X86RegCall: POut << "__regcall "; break;
712 // Only bother printing the conventions that MSVC knows about.
717 FD->printQualifiedName(POut, Policy);
721 for (unsigned i = 0, e = Decl->getNumParams(); i != e; ++i) {
723 POut << Decl->getParamDecl(i)->getType().stream(Policy);
726 if (FT->isVariadic()) {
727 if (FD->getNumParams()) POut << ", ";
729 } else if ((IK == FuncSig || IK == LFuncSig ||
730 !Context.getLangOpts().CPlusPlus) &&
731 !Decl->getNumParams()) {
737 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
738 assert(FT && "We must have a written prototype in this case.");
741 if (FT->isVolatile())
743 RefQualifierKind Ref = MD->getRefQualifier();
744 if (Ref == RQ_LValue)
746 else if (Ref == RQ_RValue)
750 typedef SmallVector<const ClassTemplateSpecializationDecl *, 8> SpecsTy;
752 const DeclContext *Ctx = FD->getDeclContext();
753 while (Ctx && isa<NamedDecl>(Ctx)) {
754 const ClassTemplateSpecializationDecl *Spec
755 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx);
756 if (Spec && !Spec->isExplicitSpecialization())
757 Specs.push_back(Spec);
758 Ctx = Ctx->getParent();
761 std::string TemplateParams;
762 llvm::raw_string_ostream TOut(TemplateParams);
763 for (SpecsTy::reverse_iterator I = Specs.rbegin(), E = Specs.rend();
765 const TemplateParameterList *Params
766 = (*I)->getSpecializedTemplate()->getTemplateParameters();
767 const TemplateArgumentList &Args = (*I)->getTemplateArgs();
768 assert(Params->size() == Args.size());
769 for (unsigned i = 0, numParams = Params->size(); i != numParams; ++i) {
770 StringRef Param = Params->getParam(i)->getName();
771 if (Param.empty()) continue;
772 TOut << Param << " = ";
773 Args.get(i).print(Policy, TOut);
778 FunctionTemplateSpecializationInfo *FSI
779 = FD->getTemplateSpecializationInfo();
780 if (FSI && !FSI->isExplicitSpecialization()) {
781 const TemplateParameterList* Params
782 = FSI->getTemplate()->getTemplateParameters();
783 const TemplateArgumentList* Args = FSI->TemplateArguments;
784 assert(Params->size() == Args->size());
785 for (unsigned i = 0, e = Params->size(); i != e; ++i) {
786 StringRef Param = Params->getParam(i)->getName();
787 if (Param.empty()) continue;
788 TOut << Param << " = ";
789 Args->get(i).print(Policy, TOut);
795 if (!TemplateParams.empty()) {
796 // remove the trailing comma and space
797 TemplateParams.resize(TemplateParams.size() - 2);
798 POut << " [" << TemplateParams << "]";
803 // Print "auto" for all deduced return types. This includes C++1y return
804 // type deduction and lambdas. For trailing return types resolve the
805 // decltype expression. Otherwise print the real type when this is
806 // not a constructor or destructor.
807 if (isa<CXXMethodDecl>(FD) &&
808 cast<CXXMethodDecl>(FD)->getParent()->isLambda())
809 Proto = "auto " + Proto;
810 else if (FT && FT->getReturnType()->getAs<DecltypeType>())
812 ->getAs<DecltypeType>()
813 ->getUnderlyingType()
814 .getAsStringInternal(Proto, Policy);
815 else if (!isa<CXXConstructorDecl>(FD) && !isa<CXXDestructorDecl>(FD))
816 AFT->getReturnType().getAsStringInternal(Proto, Policy);
820 return std::string(Name);
822 if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(CurrentDecl)) {
823 for (const DeclContext *DC = CD->getParent(); DC; DC = DC->getParent())
824 // Skip to its enclosing function or method, but not its enclosing
826 if (DC->isFunctionOrMethod() && (DC->getDeclKind() != Decl::Captured)) {
827 const Decl *D = Decl::castFromDeclContext(DC);
828 return ComputeName(IK, D);
830 llvm_unreachable("CapturedDecl not inside a function or method");
832 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurrentDecl)) {
833 SmallString<256> Name;
834 llvm::raw_svector_ostream Out(Name);
835 Out << (MD->isInstanceMethod() ? '-' : '+');
838 // For incorrect code, there might not be an ObjCInterfaceDecl. Do
839 // a null check to avoid a crash.
840 if (const ObjCInterfaceDecl *ID = MD->getClassInterface())
843 if (const ObjCCategoryImplDecl *CID =
844 dyn_cast<ObjCCategoryImplDecl>(MD->getDeclContext()))
845 Out << '(' << *CID << ')';
848 MD->getSelector().print(Out);
851 return std::string(Name);
853 if (isa<TranslationUnitDecl>(CurrentDecl) && IK == PrettyFunction) {
854 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
860 void APNumericStorage::setIntValue(const ASTContext &C,
861 const llvm::APInt &Val) {
865 BitWidth = Val.getBitWidth();
866 unsigned NumWords = Val.getNumWords();
867 const uint64_t* Words = Val.getRawData();
869 pVal = new (C) uint64_t[NumWords];
870 std::copy(Words, Words + NumWords, pVal);
871 } else if (NumWords == 1)
877 IntegerLiteral::IntegerLiteral(const ASTContext &C, const llvm::APInt &V,
878 QualType type, SourceLocation l)
879 : Expr(IntegerLiteralClass, type, VK_RValue, OK_Ordinary), Loc(l) {
880 assert(type->isIntegerType() && "Illegal type in IntegerLiteral");
881 assert(V.getBitWidth() == C.getIntWidth(type) &&
882 "Integer type is not the correct size for constant.");
884 setDependence(ExprDependence::None);
888 IntegerLiteral::Create(const ASTContext &C, const llvm::APInt &V,
889 QualType type, SourceLocation l) {
890 return new (C) IntegerLiteral(C, V, type, l);
894 IntegerLiteral::Create(const ASTContext &C, EmptyShell Empty) {
895 return new (C) IntegerLiteral(Empty);
898 FixedPointLiteral::FixedPointLiteral(const ASTContext &C, const llvm::APInt &V,
899 QualType type, SourceLocation l,
901 : Expr(FixedPointLiteralClass, type, VK_RValue, OK_Ordinary), Loc(l),
903 assert(type->isFixedPointType() && "Illegal type in FixedPointLiteral");
904 assert(V.getBitWidth() == C.getTypeInfo(type).Width &&
905 "Fixed point type is not the correct size for constant.");
907 setDependence(ExprDependence::None);
910 FixedPointLiteral *FixedPointLiteral::CreateFromRawInt(const ASTContext &C,
911 const llvm::APInt &V,
915 return new (C) FixedPointLiteral(C, V, type, l, Scale);
918 FixedPointLiteral *FixedPointLiteral::Create(const ASTContext &C,
920 return new (C) FixedPointLiteral(Empty);
923 std::string FixedPointLiteral::getValueAsString(unsigned Radix) const {
924 // Currently the longest decimal number that can be printed is the max for an
925 // unsigned long _Accum: 4294967295.99999999976716935634613037109375
926 // which is 43 characters.
928 FixedPointValueToString(
929 S, llvm::APSInt::getUnsigned(getValue().getZExtValue()), Scale);
930 return std::string(S.str());
933 FloatingLiteral::FloatingLiteral(const ASTContext &C, const llvm::APFloat &V,
934 bool isexact, QualType Type, SourceLocation L)
935 : Expr(FloatingLiteralClass, Type, VK_RValue, OK_Ordinary), Loc(L) {
936 setSemantics(V.getSemantics());
937 FloatingLiteralBits.IsExact = isexact;
939 setDependence(ExprDependence::None);
942 FloatingLiteral::FloatingLiteral(const ASTContext &C, EmptyShell Empty)
943 : Expr(FloatingLiteralClass, Empty) {
944 setRawSemantics(llvm::APFloatBase::S_IEEEhalf);
945 FloatingLiteralBits.IsExact = false;
949 FloatingLiteral::Create(const ASTContext &C, const llvm::APFloat &V,
950 bool isexact, QualType Type, SourceLocation L) {
951 return new (C) FloatingLiteral(C, V, isexact, Type, L);
955 FloatingLiteral::Create(const ASTContext &C, EmptyShell Empty) {
956 return new (C) FloatingLiteral(C, Empty);
959 /// getValueAsApproximateDouble - This returns the value as an inaccurate
960 /// double. Note that this may cause loss of precision, but is useful for
961 /// debugging dumps, etc.
962 double FloatingLiteral::getValueAsApproximateDouble() const {
963 llvm::APFloat V = getValue();
965 V.convert(llvm::APFloat::IEEEdouble(), llvm::APFloat::rmNearestTiesToEven,
967 return V.convertToDouble();
970 unsigned StringLiteral::mapCharByteWidth(TargetInfo const &Target,
972 unsigned CharByteWidth = 0;
976 CharByteWidth = Target.getCharWidth();
979 CharByteWidth = Target.getWCharWidth();
982 CharByteWidth = Target.getChar16Width();
985 CharByteWidth = Target.getChar32Width();
988 assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
990 assert((CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth == 4) &&
991 "The only supported character byte widths are 1,2 and 4!");
992 return CharByteWidth;
995 StringLiteral::StringLiteral(const ASTContext &Ctx, StringRef Str,
996 StringKind Kind, bool Pascal, QualType Ty,
997 const SourceLocation *Loc,
998 unsigned NumConcatenated)
999 : Expr(StringLiteralClass, Ty, VK_LValue, OK_Ordinary) {
1000 assert(Ctx.getAsConstantArrayType(Ty) &&
1001 "StringLiteral must be of constant array type!");
1002 unsigned CharByteWidth = mapCharByteWidth(Ctx.getTargetInfo(), Kind);
1003 unsigned ByteLength = Str.size();
1004 assert((ByteLength % CharByteWidth == 0) &&
1005 "The size of the data must be a multiple of CharByteWidth!");
1007 // Avoid the expensive division. The compiler should be able to figure it
1008 // out by itself. However as of clang 7, even with the appropriate
1009 // llvm_unreachable added just here, it is not able to do so.
1011 switch (CharByteWidth) {
1013 Length = ByteLength;
1016 Length = ByteLength / 2;
1019 Length = ByteLength / 4;
1022 llvm_unreachable("Unsupported character width!");
1025 StringLiteralBits.Kind = Kind;
1026 StringLiteralBits.CharByteWidth = CharByteWidth;
1027 StringLiteralBits.IsPascal = Pascal;
1028 StringLiteralBits.NumConcatenated = NumConcatenated;
1029 *getTrailingObjects<unsigned>() = Length;
1031 // Initialize the trailing array of SourceLocation.
1032 // This is safe since SourceLocation is POD-like.
1033 std::memcpy(getTrailingObjects<SourceLocation>(), Loc,
1034 NumConcatenated * sizeof(SourceLocation));
1036 // Initialize the trailing array of char holding the string data.
1037 std::memcpy(getTrailingObjects<char>(), Str.data(), ByteLength);
1039 setDependence(ExprDependence::None);
1042 StringLiteral::StringLiteral(EmptyShell Empty, unsigned NumConcatenated,
1043 unsigned Length, unsigned CharByteWidth)
1044 : Expr(StringLiteralClass, Empty) {
1045 StringLiteralBits.CharByteWidth = CharByteWidth;
1046 StringLiteralBits.NumConcatenated = NumConcatenated;
1047 *getTrailingObjects<unsigned>() = Length;
1050 StringLiteral *StringLiteral::Create(const ASTContext &Ctx, StringRef Str,
1051 StringKind Kind, bool Pascal, QualType Ty,
1052 const SourceLocation *Loc,
1053 unsigned NumConcatenated) {
1054 void *Mem = Ctx.Allocate(totalSizeToAlloc<unsigned, SourceLocation, char>(
1055 1, NumConcatenated, Str.size()),
1056 alignof(StringLiteral));
1058 StringLiteral(Ctx, Str, Kind, Pascal, Ty, Loc, NumConcatenated);
1061 StringLiteral *StringLiteral::CreateEmpty(const ASTContext &Ctx,
1062 unsigned NumConcatenated,
1064 unsigned CharByteWidth) {
1065 void *Mem = Ctx.Allocate(totalSizeToAlloc<unsigned, SourceLocation, char>(
1066 1, NumConcatenated, Length * CharByteWidth),
1067 alignof(StringLiteral));
1069 StringLiteral(EmptyShell(), NumConcatenated, Length, CharByteWidth);
1072 void StringLiteral::outputString(raw_ostream &OS) const {
1073 switch (getKind()) {
1074 case Ascii: break; // no prefix.
1075 case Wide: OS << 'L'; break;
1076 case UTF8: OS << "u8"; break;
1077 case UTF16: OS << 'u'; break;
1078 case UTF32: OS << 'U'; break;
1081 static const char Hex[] = "0123456789ABCDEF";
1083 unsigned LastSlashX = getLength();
1084 for (unsigned I = 0, N = getLength(); I != N; ++I) {
1085 switch (uint32_t Char = getCodeUnit(I)) {
1087 // FIXME: Convert UTF-8 back to codepoints before rendering.
1089 // Convert UTF-16 surrogate pairs back to codepoints before rendering.
1090 // Leave invalid surrogates alone; we'll use \x for those.
1091 if (getKind() == UTF16 && I != N - 1 && Char >= 0xd800 &&
1093 uint32_t Trail = getCodeUnit(I + 1);
1094 if (Trail >= 0xdc00 && Trail <= 0xdfff) {
1095 Char = 0x10000 + ((Char - 0xd800) << 10) + (Trail - 0xdc00);
1101 // If this is a wide string, output characters over 0xff using \x
1102 // escapes. Otherwise, this is a UTF-16 or UTF-32 string, and Char is a
1103 // codepoint: use \x escapes for invalid codepoints.
1104 if (getKind() == Wide ||
1105 (Char >= 0xd800 && Char <= 0xdfff) || Char >= 0x110000) {
1106 // FIXME: Is this the best way to print wchar_t?
1109 while ((Char >> Shift) == 0)
1111 for (/**/; Shift >= 0; Shift -= 4)
1112 OS << Hex[(Char >> Shift) & 15];
1119 << Hex[(Char >> 20) & 15]
1120 << Hex[(Char >> 16) & 15];
1123 OS << Hex[(Char >> 12) & 15]
1124 << Hex[(Char >> 8) & 15]
1125 << Hex[(Char >> 4) & 15]
1126 << Hex[(Char >> 0) & 15];
1130 // If we used \x... for the previous character, and this character is a
1131 // hexadecimal digit, prevent it being slurped as part of the \x.
1132 if (LastSlashX + 1 == I) {
1134 case '0': case '1': case '2': case '3': case '4':
1135 case '5': case '6': case '7': case '8': case '9':
1136 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
1137 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
1142 assert(Char <= 0xff &&
1143 "Characters above 0xff should already have been handled.");
1145 if (isPrintable(Char))
1147 else // Output anything hard as an octal escape.
1149 << (char)('0' + ((Char >> 6) & 7))
1150 << (char)('0' + ((Char >> 3) & 7))
1151 << (char)('0' + ((Char >> 0) & 7));
1153 // Handle some common non-printable cases to make dumps prettier.
1154 case '\\': OS << "\\\\"; break;
1155 case '"': OS << "\\\""; break;
1156 case '\a': OS << "\\a"; break;
1157 case '\b': OS << "\\b"; break;
1158 case '\f': OS << "\\f"; break;
1159 case '\n': OS << "\\n"; break;
1160 case '\r': OS << "\\r"; break;
1161 case '\t': OS << "\\t"; break;
1162 case '\v': OS << "\\v"; break;
1168 /// getLocationOfByte - Return a source location that points to the specified
1169 /// byte of this string literal.
1171 /// Strings are amazingly complex. They can be formed from multiple tokens and
1172 /// can have escape sequences in them in addition to the usual trigraph and
1173 /// escaped newline business. This routine handles this complexity.
1175 /// The *StartToken sets the first token to be searched in this function and
1176 /// the *StartTokenByteOffset is the byte offset of the first token. Before
1177 /// returning, it updates the *StartToken to the TokNo of the token being found
1178 /// and sets *StartTokenByteOffset to the byte offset of the token in the
1180 /// Using these two parameters can reduce the time complexity from O(n^2) to
1181 /// O(n) if one wants to get the location of byte for all the tokens in a
1185 StringLiteral::getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1186 const LangOptions &Features,
1187 const TargetInfo &Target, unsigned *StartToken,
1188 unsigned *StartTokenByteOffset) const {
1189 assert((getKind() == StringLiteral::Ascii ||
1190 getKind() == StringLiteral::UTF8) &&
1191 "Only narrow string literals are currently supported");
1193 // Loop over all of the tokens in this string until we find the one that
1194 // contains the byte we're looking for.
1196 unsigned StringOffset = 0;
1198 TokNo = *StartToken;
1199 if (StartTokenByteOffset) {
1200 StringOffset = *StartTokenByteOffset;
1201 ByteNo -= StringOffset;
1204 assert(TokNo < getNumConcatenated() && "Invalid byte number!");
1205 SourceLocation StrTokLoc = getStrTokenLoc(TokNo);
1207 // Get the spelling of the string so that we can get the data that makes up
1208 // the string literal, not the identifier for the macro it is potentially
1209 // expanded through.
1210 SourceLocation StrTokSpellingLoc = SM.getSpellingLoc(StrTokLoc);
1212 // Re-lex the token to get its length and original spelling.
1213 std::pair<FileID, unsigned> LocInfo =
1214 SM.getDecomposedLoc(StrTokSpellingLoc);
1215 bool Invalid = false;
1216 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
1218 if (StartTokenByteOffset != nullptr)
1219 *StartTokenByteOffset = StringOffset;
1220 if (StartToken != nullptr)
1221 *StartToken = TokNo;
1222 return StrTokSpellingLoc;
1225 const char *StrData = Buffer.data()+LocInfo.second;
1227 // Create a lexer starting at the beginning of this token.
1228 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), Features,
1229 Buffer.begin(), StrData, Buffer.end());
1231 TheLexer.LexFromRawLexer(TheTok);
1233 // Use the StringLiteralParser to compute the length of the string in bytes.
1234 StringLiteralParser SLP(TheTok, SM, Features, Target);
1235 unsigned TokNumBytes = SLP.GetStringLength();
1237 // If the byte is in this token, return the location of the byte.
1238 if (ByteNo < TokNumBytes ||
1239 (ByteNo == TokNumBytes && TokNo == getNumConcatenated() - 1)) {
1240 unsigned Offset = SLP.getOffsetOfStringByte(TheTok, ByteNo);
1242 // Now that we know the offset of the token in the spelling, use the
1243 // preprocessor to get the offset in the original source.
1244 if (StartTokenByteOffset != nullptr)
1245 *StartTokenByteOffset = StringOffset;
1246 if (StartToken != nullptr)
1247 *StartToken = TokNo;
1248 return Lexer::AdvanceToTokenCharacter(StrTokLoc, Offset, SM, Features);
1251 // Move to the next string token.
1252 StringOffset += TokNumBytes;
1254 ByteNo -= TokNumBytes;
1258 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1259 /// corresponds to, e.g. "sizeof" or "[pre]++".
1260 StringRef UnaryOperator::getOpcodeStr(Opcode Op) {
1262 #define UNARY_OPERATION(Name, Spelling) case UO_##Name: return Spelling;
1263 #include "clang/AST/OperationKinds.def"
1265 llvm_unreachable("Unknown unary operator");
1269 UnaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix) {
1271 default: llvm_unreachable("No unary operator for overloaded function");
1272 case OO_PlusPlus: return Postfix ? UO_PostInc : UO_PreInc;
1273 case OO_MinusMinus: return Postfix ? UO_PostDec : UO_PreDec;
1274 case OO_Amp: return UO_AddrOf;
1275 case OO_Star: return UO_Deref;
1276 case OO_Plus: return UO_Plus;
1277 case OO_Minus: return UO_Minus;
1278 case OO_Tilde: return UO_Not;
1279 case OO_Exclaim: return UO_LNot;
1280 case OO_Coawait: return UO_Coawait;
1284 OverloadedOperatorKind UnaryOperator::getOverloadedOperator(Opcode Opc) {
1286 case UO_PostInc: case UO_PreInc: return OO_PlusPlus;
1287 case UO_PostDec: case UO_PreDec: return OO_MinusMinus;
1288 case UO_AddrOf: return OO_Amp;
1289 case UO_Deref: return OO_Star;
1290 case UO_Plus: return OO_Plus;
1291 case UO_Minus: return OO_Minus;
1292 case UO_Not: return OO_Tilde;
1293 case UO_LNot: return OO_Exclaim;
1294 case UO_Coawait: return OO_Coawait;
1295 default: return OO_None;
1300 //===----------------------------------------------------------------------===//
1301 // Postfix Operators.
1302 //===----------------------------------------------------------------------===//
1304 CallExpr::CallExpr(StmtClass SC, Expr *Fn, ArrayRef<Expr *> PreArgs,
1305 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
1306 SourceLocation RParenLoc, unsigned MinNumArgs,
1307 ADLCallKind UsesADL)
1308 : Expr(SC, Ty, VK, OK_Ordinary), RParenLoc(RParenLoc) {
1309 NumArgs = std::max<unsigned>(Args.size(), MinNumArgs);
1310 unsigned NumPreArgs = PreArgs.size();
1311 CallExprBits.NumPreArgs = NumPreArgs;
1312 assert((NumPreArgs == getNumPreArgs()) && "NumPreArgs overflow!");
1314 unsigned OffsetToTrailingObjects = offsetToTrailingObjects(SC);
1315 CallExprBits.OffsetToTrailingObjects = OffsetToTrailingObjects;
1316 assert((CallExprBits.OffsetToTrailingObjects == OffsetToTrailingObjects) &&
1317 "OffsetToTrailingObjects overflow!");
1319 CallExprBits.UsesADL = static_cast<bool>(UsesADL);
1322 for (unsigned I = 0; I != NumPreArgs; ++I)
1323 setPreArg(I, PreArgs[I]);
1324 for (unsigned I = 0; I != Args.size(); ++I)
1326 for (unsigned I = Args.size(); I != NumArgs; ++I)
1329 setDependence(computeDependence(this, PreArgs));
1332 CallExpr::CallExpr(StmtClass SC, unsigned NumPreArgs, unsigned NumArgs,
1334 : Expr(SC, Empty), NumArgs(NumArgs) {
1335 CallExprBits.NumPreArgs = NumPreArgs;
1336 assert((NumPreArgs == getNumPreArgs()) && "NumPreArgs overflow!");
1338 unsigned OffsetToTrailingObjects = offsetToTrailingObjects(SC);
1339 CallExprBits.OffsetToTrailingObjects = OffsetToTrailingObjects;
1340 assert((CallExprBits.OffsetToTrailingObjects == OffsetToTrailingObjects) &&
1341 "OffsetToTrailingObjects overflow!");
1344 CallExpr *CallExpr::Create(const ASTContext &Ctx, Expr *Fn,
1345 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
1346 SourceLocation RParenLoc, unsigned MinNumArgs,
1347 ADLCallKind UsesADL) {
1348 unsigned NumArgs = std::max<unsigned>(Args.size(), MinNumArgs);
1349 unsigned SizeOfTrailingObjects =
1350 CallExpr::sizeOfTrailingObjects(/*NumPreArgs=*/0, NumArgs);
1352 Ctx.Allocate(sizeof(CallExpr) + SizeOfTrailingObjects, alignof(CallExpr));
1353 return new (Mem) CallExpr(CallExprClass, Fn, /*PreArgs=*/{}, Args, Ty, VK,
1354 RParenLoc, MinNumArgs, UsesADL);
1357 CallExpr *CallExpr::CreateTemporary(void *Mem, Expr *Fn, QualType Ty,
1358 ExprValueKind VK, SourceLocation RParenLoc,
1359 ADLCallKind UsesADL) {
1360 assert(!(reinterpret_cast<uintptr_t>(Mem) % alignof(CallExpr)) &&
1361 "Misaligned memory in CallExpr::CreateTemporary!");
1362 return new (Mem) CallExpr(CallExprClass, Fn, /*PreArgs=*/{}, /*Args=*/{}, Ty,
1364 /*MinNumArgs=*/0, UsesADL);
1367 CallExpr *CallExpr::CreateEmpty(const ASTContext &Ctx, unsigned NumArgs,
1369 unsigned SizeOfTrailingObjects =
1370 CallExpr::sizeOfTrailingObjects(/*NumPreArgs=*/0, NumArgs);
1372 Ctx.Allocate(sizeof(CallExpr) + SizeOfTrailingObjects, alignof(CallExpr));
1373 return new (Mem) CallExpr(CallExprClass, /*NumPreArgs=*/0, NumArgs, Empty);
1376 unsigned CallExpr::offsetToTrailingObjects(StmtClass SC) {
1379 return sizeof(CallExpr);
1380 case CXXOperatorCallExprClass:
1381 return sizeof(CXXOperatorCallExpr);
1382 case CXXMemberCallExprClass:
1383 return sizeof(CXXMemberCallExpr);
1384 case UserDefinedLiteralClass:
1385 return sizeof(UserDefinedLiteral);
1386 case CUDAKernelCallExprClass:
1387 return sizeof(CUDAKernelCallExpr);
1389 llvm_unreachable("unexpected class deriving from CallExpr!");
1393 Decl *Expr::getReferencedDeclOfCallee() {
1394 Expr *CEE = IgnoreParenImpCasts();
1396 while (SubstNonTypeTemplateParmExpr *NTTP =
1397 dyn_cast<SubstNonTypeTemplateParmExpr>(CEE)) {
1398 CEE = NTTP->getReplacement()->IgnoreParenImpCasts();
1401 // If we're calling a dereference, look at the pointer instead.
1403 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CEE)) {
1404 if (BO->isPtrMemOp()) {
1405 CEE = BO->getRHS()->IgnoreParenImpCasts();
1408 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(CEE)) {
1409 if (UO->getOpcode() == UO_Deref || UO->getOpcode() == UO_AddrOf ||
1410 UO->getOpcode() == UO_Plus) {
1411 CEE = UO->getSubExpr()->IgnoreParenImpCasts();
1418 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE))
1419 return DRE->getDecl();
1420 if (MemberExpr *ME = dyn_cast<MemberExpr>(CEE))
1421 return ME->getMemberDecl();
1422 if (auto *BE = dyn_cast<BlockExpr>(CEE))
1423 return BE->getBlockDecl();
1428 /// If this is a call to a builtin, return the builtin ID. If not, return 0.
1429 unsigned CallExpr::getBuiltinCallee() const {
1431 dyn_cast_or_null<FunctionDecl>(getCallee()->getReferencedDeclOfCallee());
1432 return FDecl ? FDecl->getBuiltinID() : 0;
1435 bool CallExpr::isUnevaluatedBuiltinCall(const ASTContext &Ctx) const {
1436 if (unsigned BI = getBuiltinCallee())
1437 return Ctx.BuiltinInfo.isUnevaluated(BI);
1441 QualType CallExpr::getCallReturnType(const ASTContext &Ctx) const {
1442 const Expr *Callee = getCallee();
1443 QualType CalleeType = Callee->getType();
1444 if (const auto *FnTypePtr = CalleeType->getAs<PointerType>()) {
1445 CalleeType = FnTypePtr->getPointeeType();
1446 } else if (const auto *BPT = CalleeType->getAs<BlockPointerType>()) {
1447 CalleeType = BPT->getPointeeType();
1448 } else if (CalleeType->isSpecificPlaceholderType(BuiltinType::BoundMember)) {
1449 if (isa<CXXPseudoDestructorExpr>(Callee->IgnoreParens()))
1452 // This should never be overloaded and so should never return null.
1453 CalleeType = Expr::findBoundMemberType(Callee);
1456 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
1457 return FnType->getReturnType();
1460 const Attr *CallExpr::getUnusedResultAttr(const ASTContext &Ctx) const {
1461 // If the return type is a struct, union, or enum that is marked nodiscard,
1462 // then return the return type attribute.
1463 if (const TagDecl *TD = getCallReturnType(Ctx)->getAsTagDecl())
1464 if (const auto *A = TD->getAttr<WarnUnusedResultAttr>())
1467 // Otherwise, see if the callee is marked nodiscard and return that attribute
1469 const Decl *D = getCalleeDecl();
1470 return D ? D->getAttr<WarnUnusedResultAttr>() : nullptr;
1473 SourceLocation CallExpr::getBeginLoc() const {
1474 if (isa<CXXOperatorCallExpr>(this))
1475 return cast<CXXOperatorCallExpr>(this)->getBeginLoc();
1477 SourceLocation begin = getCallee()->getBeginLoc();
1478 if (begin.isInvalid() && getNumArgs() > 0 && getArg(0))
1479 begin = getArg(0)->getBeginLoc();
1482 SourceLocation CallExpr::getEndLoc() const {
1483 if (isa<CXXOperatorCallExpr>(this))
1484 return cast<CXXOperatorCallExpr>(this)->getEndLoc();
1486 SourceLocation end = getRParenLoc();
1487 if (end.isInvalid() && getNumArgs() > 0 && getArg(getNumArgs() - 1))
1488 end = getArg(getNumArgs() - 1)->getEndLoc();
1492 OffsetOfExpr *OffsetOfExpr::Create(const ASTContext &C, QualType type,
1493 SourceLocation OperatorLoc,
1494 TypeSourceInfo *tsi,
1495 ArrayRef<OffsetOfNode> comps,
1496 ArrayRef<Expr*> exprs,
1497 SourceLocation RParenLoc) {
1498 void *Mem = C.Allocate(
1499 totalSizeToAlloc<OffsetOfNode, Expr *>(comps.size(), exprs.size()));
1501 return new (Mem) OffsetOfExpr(C, type, OperatorLoc, tsi, comps, exprs,
1505 OffsetOfExpr *OffsetOfExpr::CreateEmpty(const ASTContext &C,
1506 unsigned numComps, unsigned numExprs) {
1508 C.Allocate(totalSizeToAlloc<OffsetOfNode, Expr *>(numComps, numExprs));
1509 return new (Mem) OffsetOfExpr(numComps, numExprs);
1512 OffsetOfExpr::OffsetOfExpr(const ASTContext &C, QualType type,
1513 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1514 ArrayRef<OffsetOfNode> comps, ArrayRef<Expr *> exprs,
1515 SourceLocation RParenLoc)
1516 : Expr(OffsetOfExprClass, type, VK_RValue, OK_Ordinary),
1517 OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi),
1518 NumComps(comps.size()), NumExprs(exprs.size()) {
1519 for (unsigned i = 0; i != comps.size(); ++i)
1520 setComponent(i, comps[i]);
1521 for (unsigned i = 0; i != exprs.size(); ++i)
1522 setIndexExpr(i, exprs[i]);
1524 setDependence(computeDependence(this));
1527 IdentifierInfo *OffsetOfNode::getFieldName() const {
1528 assert(getKind() == Field || getKind() == Identifier);
1529 if (getKind() == Field)
1530 return getField()->getIdentifier();
1532 return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask);
1535 UnaryExprOrTypeTraitExpr::UnaryExprOrTypeTraitExpr(
1536 UnaryExprOrTypeTrait ExprKind, Expr *E, QualType resultType,
1537 SourceLocation op, SourceLocation rp)
1538 : Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary),
1539 OpLoc(op), RParenLoc(rp) {
1540 assert(ExprKind <= UETT_Last && "invalid enum value!");
1541 UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
1542 assert(static_cast<unsigned>(ExprKind) == UnaryExprOrTypeTraitExprBits.Kind &&
1543 "UnaryExprOrTypeTraitExprBits.Kind overflow!");
1544 UnaryExprOrTypeTraitExprBits.IsType = false;
1546 setDependence(computeDependence(this));
1549 MemberExpr::MemberExpr(Expr *Base, bool IsArrow, SourceLocation OperatorLoc,
1550 ValueDecl *MemberDecl,
1551 const DeclarationNameInfo &NameInfo, QualType T,
1552 ExprValueKind VK, ExprObjectKind OK,
1553 NonOdrUseReason NOUR)
1554 : Expr(MemberExprClass, T, VK, OK), Base(Base), MemberDecl(MemberDecl),
1555 MemberDNLoc(NameInfo.getInfo()), MemberLoc(NameInfo.getLoc()) {
1556 assert(!NameInfo.getName() ||
1557 MemberDecl->getDeclName() == NameInfo.getName());
1558 MemberExprBits.IsArrow = IsArrow;
1559 MemberExprBits.HasQualifierOrFoundDecl = false;
1560 MemberExprBits.HasTemplateKWAndArgsInfo = false;
1561 MemberExprBits.HadMultipleCandidates = false;
1562 MemberExprBits.NonOdrUseReason = NOUR;
1563 MemberExprBits.OperatorLoc = OperatorLoc;
1564 setDependence(computeDependence(this));
1567 MemberExpr *MemberExpr::Create(
1568 const ASTContext &C, Expr *Base, bool IsArrow, SourceLocation OperatorLoc,
1569 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
1570 ValueDecl *MemberDecl, DeclAccessPair FoundDecl,
1571 DeclarationNameInfo NameInfo, const TemplateArgumentListInfo *TemplateArgs,
1572 QualType T, ExprValueKind VK, ExprObjectKind OK, NonOdrUseReason NOUR) {
1573 bool HasQualOrFound = QualifierLoc || FoundDecl.getDecl() != MemberDecl ||
1574 FoundDecl.getAccess() != MemberDecl->getAccess();
1575 bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
1577 totalSizeToAlloc<MemberExprNameQualifier, ASTTemplateKWAndArgsInfo,
1578 TemplateArgumentLoc>(
1579 HasQualOrFound ? 1 : 0, HasTemplateKWAndArgsInfo ? 1 : 0,
1580 TemplateArgs ? TemplateArgs->size() : 0);
1582 void *Mem = C.Allocate(Size, alignof(MemberExpr));
1583 MemberExpr *E = new (Mem) MemberExpr(Base, IsArrow, OperatorLoc, MemberDecl,
1584 NameInfo, T, VK, OK, NOUR);
1586 // FIXME: remove remaining dependence computation to computeDependence().
1587 auto Deps = E->getDependence();
1588 if (HasQualOrFound) {
1589 // FIXME: Wrong. We should be looking at the member declaration we found.
1590 if (QualifierLoc && QualifierLoc.getNestedNameSpecifier()->isDependent())
1591 Deps |= ExprDependence::TypeValueInstantiation;
1592 else if (QualifierLoc &&
1593 QualifierLoc.getNestedNameSpecifier()->isInstantiationDependent())
1594 Deps |= ExprDependence::Instantiation;
1596 E->MemberExprBits.HasQualifierOrFoundDecl = true;
1598 MemberExprNameQualifier *NQ =
1599 E->getTrailingObjects<MemberExprNameQualifier>();
1600 NQ->QualifierLoc = QualifierLoc;
1601 NQ->FoundDecl = FoundDecl;
1604 E->MemberExprBits.HasTemplateKWAndArgsInfo =
1605 TemplateArgs || TemplateKWLoc.isValid();
1608 auto TemplateArgDeps = TemplateArgumentDependence::None;
1609 E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1610 TemplateKWLoc, *TemplateArgs,
1611 E->getTrailingObjects<TemplateArgumentLoc>(), TemplateArgDeps);
1612 if (TemplateArgDeps & TemplateArgumentDependence::Instantiation)
1613 Deps |= ExprDependence::Instantiation;
1614 } else if (TemplateKWLoc.isValid()) {
1615 E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1618 E->setDependence(Deps);
1623 MemberExpr *MemberExpr::CreateEmpty(const ASTContext &Context,
1624 bool HasQualifier, bool HasFoundDecl,
1625 bool HasTemplateKWAndArgsInfo,
1626 unsigned NumTemplateArgs) {
1627 assert((!NumTemplateArgs || HasTemplateKWAndArgsInfo) &&
1628 "template args but no template arg info?");
1629 bool HasQualOrFound = HasQualifier || HasFoundDecl;
1631 totalSizeToAlloc<MemberExprNameQualifier, ASTTemplateKWAndArgsInfo,
1632 TemplateArgumentLoc>(HasQualOrFound ? 1 : 0,
1633 HasTemplateKWAndArgsInfo ? 1 : 0,
1635 void *Mem = Context.Allocate(Size, alignof(MemberExpr));
1636 return new (Mem) MemberExpr(EmptyShell());
1639 SourceLocation MemberExpr::getBeginLoc() const {
1640 if (isImplicitAccess()) {
1642 return getQualifierLoc().getBeginLoc();
1646 // FIXME: We don't want this to happen. Rather, we should be able to
1647 // detect all kinds of implicit accesses more cleanly.
1648 SourceLocation BaseStartLoc = getBase()->getBeginLoc();
1649 if (BaseStartLoc.isValid())
1650 return BaseStartLoc;
1653 SourceLocation MemberExpr::getEndLoc() const {
1654 SourceLocation EndLoc = getMemberNameInfo().getEndLoc();
1655 if (hasExplicitTemplateArgs())
1656 EndLoc = getRAngleLoc();
1657 else if (EndLoc.isInvalid())
1658 EndLoc = getBase()->getEndLoc();
1662 bool CastExpr::CastConsistency() const {
1663 switch (getCastKind()) {
1664 case CK_DerivedToBase:
1665 case CK_UncheckedDerivedToBase:
1666 case CK_DerivedToBaseMemberPointer:
1667 case CK_BaseToDerived:
1668 case CK_BaseToDerivedMemberPointer:
1669 assert(!path_empty() && "Cast kind should have a base path!");
1672 case CK_CPointerToObjCPointerCast:
1673 assert(getType()->isObjCObjectPointerType());
1674 assert(getSubExpr()->getType()->isPointerType());
1675 goto CheckNoBasePath;
1677 case CK_BlockPointerToObjCPointerCast:
1678 assert(getType()->isObjCObjectPointerType());
1679 assert(getSubExpr()->getType()->isBlockPointerType());
1680 goto CheckNoBasePath;
1682 case CK_ReinterpretMemberPointer:
1683 assert(getType()->isMemberPointerType());
1684 assert(getSubExpr()->getType()->isMemberPointerType());
1685 goto CheckNoBasePath;
1688 // Arbitrary casts to C pointer types count as bitcasts.
1689 // Otherwise, we should only have block and ObjC pointer casts
1690 // here if they stay within the type kind.
1691 if (!getType()->isPointerType()) {
1692 assert(getType()->isObjCObjectPointerType() ==
1693 getSubExpr()->getType()->isObjCObjectPointerType());
1694 assert(getType()->isBlockPointerType() ==
1695 getSubExpr()->getType()->isBlockPointerType());
1697 goto CheckNoBasePath;
1699 case CK_AnyPointerToBlockPointerCast:
1700 assert(getType()->isBlockPointerType());
1701 assert(getSubExpr()->getType()->isAnyPointerType() &&
1702 !getSubExpr()->getType()->isBlockPointerType());
1703 goto CheckNoBasePath;
1705 case CK_CopyAndAutoreleaseBlockObject:
1706 assert(getType()->isBlockPointerType());
1707 assert(getSubExpr()->getType()->isBlockPointerType());
1708 goto CheckNoBasePath;
1710 case CK_FunctionToPointerDecay:
1711 assert(getType()->isPointerType());
1712 assert(getSubExpr()->getType()->isFunctionType());
1713 goto CheckNoBasePath;
1715 case CK_AddressSpaceConversion: {
1716 auto Ty = getType();
1717 auto SETy = getSubExpr()->getType();
1718 assert(getValueKindForType(Ty) == Expr::getValueKindForType(SETy));
1719 if (isRValue() && !Ty->isDependentType() && !SETy->isDependentType()) {
1720 Ty = Ty->getPointeeType();
1721 SETy = SETy->getPointeeType();
1723 assert((Ty->isDependentType() || SETy->isDependentType()) ||
1724 (!Ty.isNull() && !SETy.isNull() &&
1725 Ty.getAddressSpace() != SETy.getAddressSpace()));
1726 goto CheckNoBasePath;
1728 // These should not have an inheritance path.
1731 case CK_ArrayToPointerDecay:
1732 case CK_NullToMemberPointer:
1733 case CK_NullToPointer:
1734 case CK_ConstructorConversion:
1735 case CK_IntegralToPointer:
1736 case CK_PointerToIntegral:
1738 case CK_VectorSplat:
1739 case CK_IntegralCast:
1740 case CK_BooleanToSignedIntegral:
1741 case CK_IntegralToFloating:
1742 case CK_FloatingToIntegral:
1743 case CK_FloatingCast:
1744 case CK_ObjCObjectLValueCast:
1745 case CK_FloatingRealToComplex:
1746 case CK_FloatingComplexToReal:
1747 case CK_FloatingComplexCast:
1748 case CK_FloatingComplexToIntegralComplex:
1749 case CK_IntegralRealToComplex:
1750 case CK_IntegralComplexToReal:
1751 case CK_IntegralComplexCast:
1752 case CK_IntegralComplexToFloatingComplex:
1753 case CK_ARCProduceObject:
1754 case CK_ARCConsumeObject:
1755 case CK_ARCReclaimReturnedObject:
1756 case CK_ARCExtendBlockObject:
1757 case CK_ZeroToOCLOpaqueType:
1758 case CK_IntToOCLSampler:
1759 case CK_FixedPointCast:
1760 case CK_FixedPointToIntegral:
1761 case CK_IntegralToFixedPoint:
1762 assert(!getType()->isBooleanType() && "unheralded conversion to bool");
1763 goto CheckNoBasePath;
1766 case CK_LValueToRValue:
1768 case CK_AtomicToNonAtomic:
1769 case CK_NonAtomicToAtomic:
1770 case CK_PointerToBoolean:
1771 case CK_IntegralToBoolean:
1772 case CK_FloatingToBoolean:
1773 case CK_MemberPointerToBoolean:
1774 case CK_FloatingComplexToBoolean:
1775 case CK_IntegralComplexToBoolean:
1776 case CK_LValueBitCast: // -> bool&
1777 case CK_LValueToRValueBitCast:
1778 case CK_UserDefinedConversion: // operator bool()
1779 case CK_BuiltinFnToFnPtr:
1780 case CK_FixedPointToBoolean:
1782 assert(path_empty() && "Cast kind should not have a base path!");
1788 const char *CastExpr::getCastKindName(CastKind CK) {
1790 #define CAST_OPERATION(Name) case CK_##Name: return #Name;
1791 #include "clang/AST/OperationKinds.def"
1793 llvm_unreachable("Unhandled cast kind!");
1797 const Expr *skipImplicitTemporary(const Expr *E) {
1798 // Skip through reference binding to temporary.
1799 if (auto *Materialize = dyn_cast<MaterializeTemporaryExpr>(E))
1800 E = Materialize->getSubExpr();
1802 // Skip any temporary bindings; they're implicit.
1803 if (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
1804 E = Binder->getSubExpr();
1810 Expr *CastExpr::getSubExprAsWritten() {
1811 const Expr *SubExpr = nullptr;
1812 const CastExpr *E = this;
1814 SubExpr = skipImplicitTemporary(E->getSubExpr());
1816 // Conversions by constructor and conversion functions have a
1817 // subexpression describing the call; strip it off.
1818 if (E->getCastKind() == CK_ConstructorConversion)
1820 skipImplicitTemporary(cast<CXXConstructExpr>(SubExpr)->getArg(0));
1821 else if (E->getCastKind() == CK_UserDefinedConversion) {
1822 assert((isa<CXXMemberCallExpr>(SubExpr) ||
1823 isa<BlockExpr>(SubExpr)) &&
1824 "Unexpected SubExpr for CK_UserDefinedConversion.");
1825 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))
1826 SubExpr = MCE->getImplicitObjectArgument();
1829 // If the subexpression we're left with is an implicit cast, look
1830 // through that, too.
1831 } while ((E = dyn_cast<ImplicitCastExpr>(SubExpr)));
1833 return const_cast<Expr*>(SubExpr);
1836 NamedDecl *CastExpr::getConversionFunction() const {
1837 const Expr *SubExpr = nullptr;
1839 for (const CastExpr *E = this; E; E = dyn_cast<ImplicitCastExpr>(SubExpr)) {
1840 SubExpr = skipImplicitTemporary(E->getSubExpr());
1842 if (E->getCastKind() == CK_ConstructorConversion)
1843 return cast<CXXConstructExpr>(SubExpr)->getConstructor();
1845 if (E->getCastKind() == CK_UserDefinedConversion) {
1846 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))
1847 return MCE->getMethodDecl();
1854 CXXBaseSpecifier **CastExpr::path_buffer() {
1855 switch (getStmtClass()) {
1856 #define ABSTRACT_STMT(x)
1857 #define CASTEXPR(Type, Base) \
1858 case Stmt::Type##Class: \
1859 return static_cast<Type *>(this)->getTrailingObjects<CXXBaseSpecifier *>();
1860 #define STMT(Type, Base)
1861 #include "clang/AST/StmtNodes.inc"
1863 llvm_unreachable("non-cast expressions not possible here");
1867 const FieldDecl *CastExpr::getTargetFieldForToUnionCast(QualType unionType,
1869 auto RD = unionType->castAs<RecordType>()->getDecl();
1870 return getTargetFieldForToUnionCast(RD, opType);
1873 const FieldDecl *CastExpr::getTargetFieldForToUnionCast(const RecordDecl *RD,
1875 auto &Ctx = RD->getASTContext();
1876 RecordDecl::field_iterator Field, FieldEnd;
1877 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
1878 Field != FieldEnd; ++Field) {
1879 if (Ctx.hasSameUnqualifiedType(Field->getType(), OpType) &&
1880 !Field->isUnnamedBitfield()) {
1887 ImplicitCastExpr *ImplicitCastExpr::Create(const ASTContext &C, QualType T,
1888 CastKind Kind, Expr *Operand,
1889 const CXXCastPath *BasePath,
1891 unsigned PathSize = (BasePath ? BasePath->size() : 0);
1892 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
1893 // Per C++ [conv.lval]p3, lvalue-to-rvalue conversions on class and
1894 // std::nullptr_t have special semantics not captured by CK_LValueToRValue.
1895 assert((Kind != CK_LValueToRValue ||
1896 !(T->isNullPtrType() || T->getAsCXXRecordDecl())) &&
1897 "invalid type for lvalue-to-rvalue conversion");
1898 ImplicitCastExpr *E =
1899 new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, VK);
1901 std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
1902 E->getTrailingObjects<CXXBaseSpecifier *>());
1906 ImplicitCastExpr *ImplicitCastExpr::CreateEmpty(const ASTContext &C,
1907 unsigned PathSize) {
1908 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
1909 return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize);
1913 CStyleCastExpr *CStyleCastExpr::Create(const ASTContext &C, QualType T,
1914 ExprValueKind VK, CastKind K, Expr *Op,
1915 const CXXCastPath *BasePath,
1916 TypeSourceInfo *WrittenTy,
1917 SourceLocation L, SourceLocation R) {
1918 unsigned PathSize = (BasePath ? BasePath->size() : 0);
1919 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
1921 new (Buffer) CStyleCastExpr(T, VK, K, Op, PathSize, WrittenTy, L, R);
1923 std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
1924 E->getTrailingObjects<CXXBaseSpecifier *>());
1928 CStyleCastExpr *CStyleCastExpr::CreateEmpty(const ASTContext &C,
1929 unsigned PathSize) {
1930 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
1931 return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize);
1934 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1935 /// corresponds to, e.g. "<<=".
1936 StringRef BinaryOperator::getOpcodeStr(Opcode Op) {
1938 #define BINARY_OPERATION(Name, Spelling) case BO_##Name: return Spelling;
1939 #include "clang/AST/OperationKinds.def"
1941 llvm_unreachable("Invalid OpCode!");
1945 BinaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO) {
1947 default: llvm_unreachable("Not an overloadable binary operator");
1948 case OO_Plus: return BO_Add;
1949 case OO_Minus: return BO_Sub;
1950 case OO_Star: return BO_Mul;
1951 case OO_Slash: return BO_Div;
1952 case OO_Percent: return BO_Rem;
1953 case OO_Caret: return BO_Xor;
1954 case OO_Amp: return BO_And;
1955 case OO_Pipe: return BO_Or;
1956 case OO_Equal: return BO_Assign;
1957 case OO_Spaceship: return BO_Cmp;
1958 case OO_Less: return BO_LT;
1959 case OO_Greater: return BO_GT;
1960 case OO_PlusEqual: return BO_AddAssign;
1961 case OO_MinusEqual: return BO_SubAssign;
1962 case OO_StarEqual: return BO_MulAssign;
1963 case OO_SlashEqual: return BO_DivAssign;
1964 case OO_PercentEqual: return BO_RemAssign;
1965 case OO_CaretEqual: return BO_XorAssign;
1966 case OO_AmpEqual: return BO_AndAssign;
1967 case OO_PipeEqual: return BO_OrAssign;
1968 case OO_LessLess: return BO_Shl;
1969 case OO_GreaterGreater: return BO_Shr;
1970 case OO_LessLessEqual: return BO_ShlAssign;
1971 case OO_GreaterGreaterEqual: return BO_ShrAssign;
1972 case OO_EqualEqual: return BO_EQ;
1973 case OO_ExclaimEqual: return BO_NE;
1974 case OO_LessEqual: return BO_LE;
1975 case OO_GreaterEqual: return BO_GE;
1976 case OO_AmpAmp: return BO_LAnd;
1977 case OO_PipePipe: return BO_LOr;
1978 case OO_Comma: return BO_Comma;
1979 case OO_ArrowStar: return BO_PtrMemI;
1983 OverloadedOperatorKind BinaryOperator::getOverloadedOperator(Opcode Opc) {
1984 static const OverloadedOperatorKind OverOps[] = {
1985 /* .* Cannot be overloaded */OO_None, OO_ArrowStar,
1986 OO_Star, OO_Slash, OO_Percent,
1988 OO_LessLess, OO_GreaterGreater,
1990 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
1991 OO_EqualEqual, OO_ExclaimEqual,
1997 OO_Equal, OO_StarEqual,
1998 OO_SlashEqual, OO_PercentEqual,
1999 OO_PlusEqual, OO_MinusEqual,
2000 OO_LessLessEqual, OO_GreaterGreaterEqual,
2001 OO_AmpEqual, OO_CaretEqual,
2005 return OverOps[Opc];
2008 bool BinaryOperator::isNullPointerArithmeticExtension(ASTContext &Ctx,
2010 Expr *LHS, Expr *RHS) {
2014 // Check that we have one pointer and one integer operand.
2016 if (LHS->getType()->isPointerType()) {
2017 if (!RHS->getType()->isIntegerType())
2020 } else if (RHS->getType()->isPointerType()) {
2021 if (!LHS->getType()->isIntegerType())
2028 // Check that the pointer is a nullptr.
2029 if (!PExp->IgnoreParenCasts()
2030 ->isNullPointerConstant(Ctx, Expr::NPC_ValueDependentIsNotNull))
2033 // Check that the pointee type is char-sized.
2034 const PointerType *PTy = PExp->getType()->getAs<PointerType>();
2035 if (!PTy || !PTy->getPointeeType()->isCharType())
2041 static QualType getDecayedSourceLocExprType(const ASTContext &Ctx,
2042 SourceLocExpr::IdentKind Kind) {
2044 case SourceLocExpr::File:
2045 case SourceLocExpr::Function: {
2046 QualType ArrTy = Ctx.getStringLiteralArrayType(Ctx.CharTy, 0);
2047 return Ctx.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType());
2049 case SourceLocExpr::Line:
2050 case SourceLocExpr::Column:
2051 return Ctx.UnsignedIntTy;
2053 llvm_unreachable("unhandled case");
2056 SourceLocExpr::SourceLocExpr(const ASTContext &Ctx, IdentKind Kind,
2057 SourceLocation BLoc, SourceLocation RParenLoc,
2058 DeclContext *ParentContext)
2059 : Expr(SourceLocExprClass, getDecayedSourceLocExprType(Ctx, Kind),
2060 VK_RValue, OK_Ordinary),
2061 BuiltinLoc(BLoc), RParenLoc(RParenLoc), ParentContext(ParentContext) {
2062 SourceLocExprBits.Kind = Kind;
2063 setDependence(ExprDependence::None);
2066 StringRef SourceLocExpr::getBuiltinStr() const {
2067 switch (getIdentKind()) {
2069 return "__builtin_FILE";
2071 return "__builtin_FUNCTION";
2073 return "__builtin_LINE";
2075 return "__builtin_COLUMN";
2077 llvm_unreachable("unexpected IdentKind!");
2080 APValue SourceLocExpr::EvaluateInContext(const ASTContext &Ctx,
2081 const Expr *DefaultExpr) const {
2083 const DeclContext *Context;
2086 Context) = [&]() -> std::pair<SourceLocation, const DeclContext *> {
2087 if (auto *DIE = dyn_cast_or_null<CXXDefaultInitExpr>(DefaultExpr))
2088 return {DIE->getUsedLocation(), DIE->getUsedContext()};
2089 if (auto *DAE = dyn_cast_or_null<CXXDefaultArgExpr>(DefaultExpr))
2090 return {DAE->getUsedLocation(), DAE->getUsedContext()};
2091 return {this->getLocation(), this->getParentContext()};
2094 PresumedLoc PLoc = Ctx.getSourceManager().getPresumedLoc(
2095 Ctx.getSourceManager().getExpansionRange(Loc).getEnd());
2097 auto MakeStringLiteral = [&](StringRef Tmp) {
2098 using LValuePathEntry = APValue::LValuePathEntry;
2099 StringLiteral *Res = Ctx.getPredefinedStringLiteralFromCache(Tmp);
2100 // Decay the string to a pointer to the first character.
2101 LValuePathEntry Path[1] = {LValuePathEntry::ArrayIndex(0)};
2102 return APValue(Res, CharUnits::Zero(), Path, /*OnePastTheEnd=*/false);
2105 switch (getIdentKind()) {
2106 case SourceLocExpr::File:
2107 return MakeStringLiteral(PLoc.getFilename());
2108 case SourceLocExpr::Function: {
2109 const Decl *CurDecl = dyn_cast_or_null<Decl>(Context);
2110 return MakeStringLiteral(
2111 CurDecl ? PredefinedExpr::ComputeName(PredefinedExpr::Function, CurDecl)
2114 case SourceLocExpr::Line:
2115 case SourceLocExpr::Column: {
2116 llvm::APSInt IntVal(Ctx.getIntWidth(Ctx.UnsignedIntTy),
2117 /*isUnsigned=*/true);
2118 IntVal = getIdentKind() == SourceLocExpr::Line ? PLoc.getLine()
2120 return APValue(IntVal);
2123 llvm_unreachable("unhandled case");
2126 InitListExpr::InitListExpr(const ASTContext &C, SourceLocation lbraceloc,
2127 ArrayRef<Expr *> initExprs, SourceLocation rbraceloc)
2128 : Expr(InitListExprClass, QualType(), VK_RValue, OK_Ordinary),
2129 InitExprs(C, initExprs.size()), LBraceLoc(lbraceloc),
2130 RBraceLoc(rbraceloc), AltForm(nullptr, true) {
2131 sawArrayRangeDesignator(false);
2132 InitExprs.insert(C, InitExprs.end(), initExprs.begin(), initExprs.end());
2134 setDependence(computeDependence(this));
2137 void InitListExpr::reserveInits(const ASTContext &C, unsigned NumInits) {
2138 if (NumInits > InitExprs.size())
2139 InitExprs.reserve(C, NumInits);
2142 void InitListExpr::resizeInits(const ASTContext &C, unsigned NumInits) {
2143 InitExprs.resize(C, NumInits, nullptr);
2146 Expr *InitListExpr::updateInit(const ASTContext &C, unsigned Init, Expr *expr) {
2147 if (Init >= InitExprs.size()) {
2148 InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, nullptr);
2149 setInit(Init, expr);
2153 Expr *Result = cast_or_null<Expr>(InitExprs[Init]);
2154 setInit(Init, expr);
2158 void InitListExpr::setArrayFiller(Expr *filler) {
2159 assert(!hasArrayFiller() && "Filler already set!");
2160 ArrayFillerOrUnionFieldInit = filler;
2161 // Fill out any "holes" in the array due to designated initializers.
2162 Expr **inits = getInits();
2163 for (unsigned i = 0, e = getNumInits(); i != e; ++i)
2164 if (inits[i] == nullptr)
2168 bool InitListExpr::isStringLiteralInit() const {
2169 if (getNumInits() != 1)
2171 const ArrayType *AT = getType()->getAsArrayTypeUnsafe();
2172 if (!AT || !AT->getElementType()->isIntegerType())
2174 // It is possible for getInit() to return null.
2175 const Expr *Init = getInit(0);
2178 Init = Init->IgnoreParens();
2179 return isa<StringLiteral>(Init) || isa<ObjCEncodeExpr>(Init);
2182 bool InitListExpr::isTransparent() const {
2183 assert(isSemanticForm() && "syntactic form never semantically transparent");
2185 // A glvalue InitListExpr is always just sugar.
2187 assert(getNumInits() == 1 && "multiple inits in glvalue init list");
2191 // Otherwise, we're sugar if and only if we have exactly one initializer that
2192 // is of the same type.
2193 if (getNumInits() != 1 || !getInit(0))
2196 // Don't confuse aggregate initialization of a struct X { X &x; }; with a
2197 // transparent struct copy.
2198 if (!getInit(0)->isRValue() && getType()->isRecordType())
2201 return getType().getCanonicalType() ==
2202 getInit(0)->getType().getCanonicalType();
2205 bool InitListExpr::isIdiomaticZeroInitializer(const LangOptions &LangOpts) const {
2206 assert(isSyntacticForm() && "only test syntactic form as zero initializer");
2208 if (LangOpts.CPlusPlus || getNumInits() != 1 || !getInit(0)) {
2212 const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(getInit(0)->IgnoreImplicit());
2213 return Lit && Lit->getValue() == 0;
2216 SourceLocation InitListExpr::getBeginLoc() const {
2217 if (InitListExpr *SyntacticForm = getSyntacticForm())
2218 return SyntacticForm->getBeginLoc();
2219 SourceLocation Beg = LBraceLoc;
2220 if (Beg.isInvalid()) {
2221 // Find the first non-null initializer.
2222 for (InitExprsTy::const_iterator I = InitExprs.begin(),
2223 E = InitExprs.end();
2226 Beg = S->getBeginLoc();
2234 SourceLocation InitListExpr::getEndLoc() const {
2235 if (InitListExpr *SyntacticForm = getSyntacticForm())
2236 return SyntacticForm->getEndLoc();
2237 SourceLocation End = RBraceLoc;
2238 if (End.isInvalid()) {
2239 // Find the first non-null initializer from the end.
2240 for (InitExprsTy::const_reverse_iterator I = InitExprs.rbegin(),
2241 E = InitExprs.rend();
2244 End = S->getEndLoc();
2252 /// getFunctionType - Return the underlying function type for this block.
2254 const FunctionProtoType *BlockExpr::getFunctionType() const {
2255 // The block pointer is never sugared, but the function type might be.
2256 return cast<BlockPointerType>(getType())
2257 ->getPointeeType()->castAs<FunctionProtoType>();
2260 SourceLocation BlockExpr::getCaretLocation() const {
2261 return TheBlock->getCaretLocation();
2263 const Stmt *BlockExpr::getBody() const {
2264 return TheBlock->getBody();
2266 Stmt *BlockExpr::getBody() {
2267 return TheBlock->getBody();
2271 //===----------------------------------------------------------------------===//
2272 // Generic Expression Routines
2273 //===----------------------------------------------------------------------===//
2275 bool Expr::isReadIfDiscardedInCPlusPlus11() const {
2276 // In C++11, discarded-value expressions of a certain form are special,
2277 // according to [expr]p10:
2278 // The lvalue-to-rvalue conversion (4.1) is applied only if the
2279 // expression is an lvalue of volatile-qualified type and it has
2280 // one of the following forms:
2281 if (!isGLValue() || !getType().isVolatileQualified())
2284 const Expr *E = IgnoreParens();
2286 // - id-expression (5.1.1),
2287 if (isa<DeclRefExpr>(E))
2290 // - subscripting (5.2.1),
2291 if (isa<ArraySubscriptExpr>(E))
2294 // - class member access (5.2.5),
2295 if (isa<MemberExpr>(E))
2298 // - indirection (5.3.1),
2299 if (auto *UO = dyn_cast<UnaryOperator>(E))
2300 if (UO->getOpcode() == UO_Deref)
2303 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
2304 // - pointer-to-member operation (5.5),
2305 if (BO->isPtrMemOp())
2308 // - comma expression (5.18) where the right operand is one of the above.
2309 if (BO->getOpcode() == BO_Comma)
2310 return BO->getRHS()->isReadIfDiscardedInCPlusPlus11();
2313 // - conditional expression (5.16) where both the second and the third
2314 // operands are one of the above, or
2315 if (auto *CO = dyn_cast<ConditionalOperator>(E))
2316 return CO->getTrueExpr()->isReadIfDiscardedInCPlusPlus11() &&
2317 CO->getFalseExpr()->isReadIfDiscardedInCPlusPlus11();
2318 // The related edge case of "*x ?: *x".
2320 dyn_cast<BinaryConditionalOperator>(E)) {
2321 if (auto *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
2322 return OVE->getSourceExpr()->isReadIfDiscardedInCPlusPlus11() &&
2323 BCO->getFalseExpr()->isReadIfDiscardedInCPlusPlus11();
2326 // Objective-C++ extensions to the rule.
2327 if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
2333 /// isUnusedResultAWarning - Return true if this immediate expression should
2334 /// be warned about if the result is unused. If so, fill in Loc and Ranges
2335 /// with location to warn on and the source range[s] to report with the
2337 bool Expr::isUnusedResultAWarning(const Expr *&WarnE, SourceLocation &Loc,
2338 SourceRange &R1, SourceRange &R2,
2339 ASTContext &Ctx) const {
2340 // Don't warn if the expr is type dependent. The type could end up
2341 // instantiating to void.
2342 if (isTypeDependent())
2345 switch (getStmtClass()) {
2347 if (getType()->isVoidType())
2351 R1 = getSourceRange();
2353 case ParenExprClass:
2354 return cast<ParenExpr>(this)->getSubExpr()->
2355 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2356 case GenericSelectionExprClass:
2357 return cast<GenericSelectionExpr>(this)->getResultExpr()->
2358 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2359 case CoawaitExprClass:
2360 case CoyieldExprClass:
2361 return cast<CoroutineSuspendExpr>(this)->getResumeExpr()->
2362 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2363 case ChooseExprClass:
2364 return cast<ChooseExpr>(this)->getChosenSubExpr()->
2365 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2366 case UnaryOperatorClass: {
2367 const UnaryOperator *UO = cast<UnaryOperator>(this);
2369 switch (UO->getOpcode()) {
2378 // This is just the 'operator co_await' call inside the guts of a
2379 // dependent co_await call.
2383 case UO_PreDec: // ++/--
2384 return false; // Not a warning.
2387 // accessing a piece of a volatile complex is a side-effect.
2388 if (Ctx.getCanonicalType(UO->getSubExpr()->getType())
2389 .isVolatileQualified())
2393 return UO->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2396 Loc = UO->getOperatorLoc();
2397 R1 = UO->getSubExpr()->getSourceRange();
2400 case BinaryOperatorClass: {
2401 const BinaryOperator *BO = cast<BinaryOperator>(this);
2402 switch (BO->getOpcode()) {
2405 // Consider the RHS of comma for side effects. LHS was checked by
2406 // Sema::CheckCommaOperands.
2408 // ((foo = <blah>), 0) is an idiom for hiding the result (and
2409 // lvalue-ness) of an assignment written in a macro.
2410 if (IntegerLiteral *IE =
2411 dyn_cast<IntegerLiteral>(BO->getRHS()->IgnoreParens()))
2412 if (IE->getValue() == 0)
2414 return BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2415 // Consider '||', '&&' to have side effects if the LHS or RHS does.
2418 if (!BO->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) ||
2419 !BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
2423 if (BO->isAssignmentOp())
2426 Loc = BO->getOperatorLoc();
2427 R1 = BO->getLHS()->getSourceRange();
2428 R2 = BO->getRHS()->getSourceRange();
2431 case CompoundAssignOperatorClass:
2432 case VAArgExprClass:
2433 case AtomicExprClass:
2436 case ConditionalOperatorClass: {
2437 // If only one of the LHS or RHS is a warning, the operator might
2438 // be being used for control flow. Only warn if both the LHS and
2439 // RHS are warnings.
2440 const auto *Exp = cast<ConditionalOperator>(this);
2441 return Exp->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) &&
2442 Exp->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2444 case BinaryConditionalOperatorClass: {
2445 const auto *Exp = cast<BinaryConditionalOperator>(this);
2446 return Exp->getFalseExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2449 case MemberExprClass:
2451 Loc = cast<MemberExpr>(this)->getMemberLoc();
2452 R1 = SourceRange(Loc, Loc);
2453 R2 = cast<MemberExpr>(this)->getBase()->getSourceRange();
2456 case ArraySubscriptExprClass:
2458 Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc();
2459 R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange();
2460 R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange();
2463 case CXXOperatorCallExprClass: {
2464 // Warn about operator ==,!=,<,>,<=, and >= even when user-defined operator
2465 // overloads as there is no reasonable way to define these such that they
2466 // have non-trivial, desirable side-effects. See the -Wunused-comparison
2467 // warning: operators == and != are commonly typo'ed, and so warning on them
2468 // provides additional value as well. If this list is updated,
2469 // DiagnoseUnusedComparison should be as well.
2470 const CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(this);
2471 switch (Op->getOperator()) {
2475 case OO_ExclaimEqual:
2478 case OO_GreaterEqual:
2480 if (Op->getCallReturnType(Ctx)->isReferenceType() ||
2481 Op->getCallReturnType(Ctx)->isVoidType())
2484 Loc = Op->getOperatorLoc();
2485 R1 = Op->getSourceRange();
2489 // Fallthrough for generic call handling.
2493 case CXXMemberCallExprClass:
2494 case UserDefinedLiteralClass: {
2495 // If this is a direct call, get the callee.
2496 const CallExpr *CE = cast<CallExpr>(this);
2497 if (const Decl *FD = CE->getCalleeDecl()) {
2498 // If the callee has attribute pure, const, or warn_unused_result, warn
2499 // about it. void foo() { strlen("bar"); } should warn.
2501 // Note: If new cases are added here, DiagnoseUnusedExprResult should be
2502 // updated to match for QoI.
2503 if (CE->hasUnusedResultAttr(Ctx) ||
2504 FD->hasAttr<PureAttr>() || FD->hasAttr<ConstAttr>()) {
2506 Loc = CE->getCallee()->getBeginLoc();
2507 R1 = CE->getCallee()->getSourceRange();
2509 if (unsigned NumArgs = CE->getNumArgs())
2510 R2 = SourceRange(CE->getArg(0)->getBeginLoc(),
2511 CE->getArg(NumArgs - 1)->getEndLoc());
2518 // If we don't know precisely what we're looking at, let's not warn.
2519 case UnresolvedLookupExprClass:
2520 case CXXUnresolvedConstructExprClass:
2521 case RecoveryExprClass:
2524 case CXXTemporaryObjectExprClass:
2525 case CXXConstructExprClass: {
2526 if (const CXXRecordDecl *Type = getType()->getAsCXXRecordDecl()) {
2527 const auto *WarnURAttr = Type->getAttr<WarnUnusedResultAttr>();
2528 if (Type->hasAttr<WarnUnusedAttr>() ||
2529 (WarnURAttr && WarnURAttr->IsCXX11NoDiscard())) {
2531 Loc = getBeginLoc();
2532 R1 = getSourceRange();
2537 const auto *CE = cast<CXXConstructExpr>(this);
2538 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) {
2539 const auto *WarnURAttr = Ctor->getAttr<WarnUnusedResultAttr>();
2540 if (WarnURAttr && WarnURAttr->IsCXX11NoDiscard()) {
2542 Loc = getBeginLoc();
2543 R1 = getSourceRange();
2545 if (unsigned NumArgs = CE->getNumArgs())
2546 R2 = SourceRange(CE->getArg(0)->getBeginLoc(),
2547 CE->getArg(NumArgs - 1)->getEndLoc());
2555 case ObjCMessageExprClass: {
2556 const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(this);
2557 if (Ctx.getLangOpts().ObjCAutoRefCount &&
2558 ME->isInstanceMessage() &&
2559 !ME->getType()->isVoidType() &&
2560 ME->getMethodFamily() == OMF_init) {
2563 R1 = ME->getSourceRange();
2567 if (const ObjCMethodDecl *MD = ME->getMethodDecl())
2568 if (MD->hasAttr<WarnUnusedResultAttr>()) {
2577 case ObjCPropertyRefExprClass:
2580 R1 = getSourceRange();
2583 case PseudoObjectExprClass: {
2584 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
2586 // Only complain about things that have the form of a getter.
2587 if (isa<UnaryOperator>(PO->getSyntacticForm()) ||
2588 isa<BinaryOperator>(PO->getSyntacticForm()))
2593 R1 = getSourceRange();
2597 case StmtExprClass: {
2598 // Statement exprs don't logically have side effects themselves, but are
2599 // sometimes used in macros in ways that give them a type that is unused.
2600 // For example ({ blah; foo(); }) will end up with a type if foo has a type.
2601 // however, if the result of the stmt expr is dead, we don't want to emit a
2603 const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt();
2604 if (!CS->body_empty()) {
2605 if (const Expr *E = dyn_cast<Expr>(CS->body_back()))
2606 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2607 if (const LabelStmt *Label = dyn_cast<LabelStmt>(CS->body_back()))
2608 if (const Expr *E = dyn_cast<Expr>(Label->getSubStmt()))
2609 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2612 if (getType()->isVoidType())
2615 Loc = cast<StmtExpr>(this)->getLParenLoc();
2616 R1 = getSourceRange();
2619 case CXXFunctionalCastExprClass:
2620 case CStyleCastExprClass: {
2621 // Ignore an explicit cast to void, except in C++98 if the operand is a
2622 // volatile glvalue for which we would trigger an implicit read in any
2623 // other language mode. (Such an implicit read always happens as part of
2624 // the lvalue conversion in C, and happens in C++ for expressions of all
2625 // forms where it seems likely the user intended to trigger a volatile
2627 const CastExpr *CE = cast<CastExpr>(this);
2628 const Expr *SubE = CE->getSubExpr()->IgnoreParens();
2629 if (CE->getCastKind() == CK_ToVoid) {
2630 if (Ctx.getLangOpts().CPlusPlus && !Ctx.getLangOpts().CPlusPlus11 &&
2631 SubE->isReadIfDiscardedInCPlusPlus11()) {
2632 // Suppress the "unused value" warning for idiomatic usage of
2633 // '(void)var;' used to suppress "unused variable" warnings.
2634 if (auto *DRE = dyn_cast<DeclRefExpr>(SubE))
2635 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
2636 if (!VD->isExternallyVisible())
2639 // The lvalue-to-rvalue conversion would have no effect for an array.
2640 // It's implausible that the programmer expected this to result in a
2641 // volatile array load, so don't warn.
2642 if (SubE->getType()->isArrayType())
2645 return SubE->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2650 // If this is a cast to a constructor conversion, check the operand.
2651 // Otherwise, the result of the cast is unused.
2652 if (CE->getCastKind() == CK_ConstructorConversion)
2653 return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2656 if (const CXXFunctionalCastExpr *CXXCE =
2657 dyn_cast<CXXFunctionalCastExpr>(this)) {
2658 Loc = CXXCE->getBeginLoc();
2659 R1 = CXXCE->getSubExpr()->getSourceRange();
2661 const CStyleCastExpr *CStyleCE = cast<CStyleCastExpr>(this);
2662 Loc = CStyleCE->getLParenLoc();
2663 R1 = CStyleCE->getSubExpr()->getSourceRange();
2667 case ImplicitCastExprClass: {
2668 const CastExpr *ICE = cast<ImplicitCastExpr>(this);
2670 // lvalue-to-rvalue conversion on a volatile lvalue is a side-effect.
2671 if (ICE->getCastKind() == CK_LValueToRValue &&
2672 ICE->getSubExpr()->getType().isVolatileQualified())
2675 return ICE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2677 case CXXDefaultArgExprClass:
2678 return (cast<CXXDefaultArgExpr>(this)
2679 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
2680 case CXXDefaultInitExprClass:
2681 return (cast<CXXDefaultInitExpr>(this)
2682 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
2684 case CXXNewExprClass:
2685 // FIXME: In theory, there might be new expressions that don't have side
2686 // effects (e.g. a placement new with an uninitialized POD).
2687 case CXXDeleteExprClass:
2689 case MaterializeTemporaryExprClass:
2690 return cast<MaterializeTemporaryExpr>(this)
2692 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2693 case CXXBindTemporaryExprClass:
2694 return cast<CXXBindTemporaryExpr>(this)->getSubExpr()
2695 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2696 case ExprWithCleanupsClass:
2697 return cast<ExprWithCleanups>(this)->getSubExpr()
2698 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2702 /// isOBJCGCCandidate - Check if an expression is objc gc'able.
2703 /// returns true, if it is; false otherwise.
2704 bool Expr::isOBJCGCCandidate(ASTContext &Ctx) const {
2705 const Expr *E = IgnoreParens();
2706 switch (E->getStmtClass()) {
2709 case ObjCIvarRefExprClass:
2711 case Expr::UnaryOperatorClass:
2712 return cast<UnaryOperator>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
2713 case ImplicitCastExprClass:
2714 return cast<ImplicitCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
2715 case MaterializeTemporaryExprClass:
2716 return cast<MaterializeTemporaryExpr>(E)->getSubExpr()->isOBJCGCCandidate(
2718 case CStyleCastExprClass:
2719 return cast<CStyleCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
2720 case DeclRefExprClass: {
2721 const Decl *D = cast<DeclRefExpr>(E)->getDecl();
2723 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2724 if (VD->hasGlobalStorage())
2726 QualType T = VD->getType();
2727 // dereferencing to a pointer is always a gc'able candidate,
2728 // unless it is __weak.
2729 return T->isPointerType() &&
2730 (Ctx.getObjCGCAttrKind(T) != Qualifiers::Weak);
2734 case MemberExprClass: {
2735 const MemberExpr *M = cast<MemberExpr>(E);
2736 return M->getBase()->isOBJCGCCandidate(Ctx);
2738 case ArraySubscriptExprClass:
2739 return cast<ArraySubscriptExpr>(E)->getBase()->isOBJCGCCandidate(Ctx);
2743 bool Expr::isBoundMemberFunction(ASTContext &Ctx) const {
2744 if (isTypeDependent())
2746 return ClassifyLValue(Ctx) == Expr::LV_MemberFunction;
2749 QualType Expr::findBoundMemberType(const Expr *expr) {
2750 assert(expr->hasPlaceholderType(BuiltinType::BoundMember));
2752 // Bound member expressions are always one of these possibilities:
2753 // x->m x.m x->*y x.*y
2754 // (possibly parenthesized)
2756 expr = expr->IgnoreParens();
2757 if (const MemberExpr *mem = dyn_cast<MemberExpr>(expr)) {
2758 assert(isa<CXXMethodDecl>(mem->getMemberDecl()));
2759 return mem->getMemberDecl()->getType();
2762 if (const BinaryOperator *op = dyn_cast<BinaryOperator>(expr)) {
2763 QualType type = op->getRHS()->getType()->castAs<MemberPointerType>()
2765 assert(type->isFunctionType());
2769 assert(isa<UnresolvedMemberExpr>(expr) || isa<CXXPseudoDestructorExpr>(expr));
2773 static Expr *IgnoreImpCastsSingleStep(Expr *E) {
2774 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
2775 return ICE->getSubExpr();
2777 if (auto *FE = dyn_cast<FullExpr>(E))
2778 return FE->getSubExpr();
2783 static Expr *IgnoreImpCastsExtraSingleStep(Expr *E) {
2784 // FIXME: Skip MaterializeTemporaryExpr and SubstNonTypeTemplateParmExpr in
2785 // addition to what IgnoreImpCasts() skips to account for the current
2786 // behaviour of IgnoreParenImpCasts().
2787 Expr *SubE = IgnoreImpCastsSingleStep(E);
2791 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2792 return MTE->getSubExpr();
2794 if (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
2795 return NTTP->getReplacement();
2800 static Expr *IgnoreCastsSingleStep(Expr *E) {
2801 if (auto *CE = dyn_cast<CastExpr>(E))
2802 return CE->getSubExpr();
2804 if (auto *FE = dyn_cast<FullExpr>(E))
2805 return FE->getSubExpr();
2807 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2808 return MTE->getSubExpr();
2810 if (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
2811 return NTTP->getReplacement();
2816 static Expr *IgnoreLValueCastsSingleStep(Expr *E) {
2817 // Skip what IgnoreCastsSingleStep skips, except that only
2818 // lvalue-to-rvalue casts are skipped.
2819 if (auto *CE = dyn_cast<CastExpr>(E))
2820 if (CE->getCastKind() != CK_LValueToRValue)
2823 return IgnoreCastsSingleStep(E);
2826 static Expr *IgnoreBaseCastsSingleStep(Expr *E) {
2827 if (auto *CE = dyn_cast<CastExpr>(E))
2828 if (CE->getCastKind() == CK_DerivedToBase ||
2829 CE->getCastKind() == CK_UncheckedDerivedToBase ||
2830 CE->getCastKind() == CK_NoOp)
2831 return CE->getSubExpr();
2836 static Expr *IgnoreImplicitSingleStep(Expr *E) {
2837 Expr *SubE = IgnoreImpCastsSingleStep(E);
2841 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2842 return MTE->getSubExpr();
2844 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(E))
2845 return BTE->getSubExpr();
2850 static Expr *IgnoreImplicitAsWrittenSingleStep(Expr *E) {
2851 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
2852 return ICE->getSubExprAsWritten();
2854 return IgnoreImplicitSingleStep(E);
2857 static Expr *IgnoreParensOnlySingleStep(Expr *E) {
2858 if (auto *PE = dyn_cast<ParenExpr>(E))
2859 return PE->getSubExpr();
2863 static Expr *IgnoreParensSingleStep(Expr *E) {
2864 if (auto *PE = dyn_cast<ParenExpr>(E))
2865 return PE->getSubExpr();
2867 if (auto *UO = dyn_cast<UnaryOperator>(E)) {
2868 if (UO->getOpcode() == UO_Extension)
2869 return UO->getSubExpr();
2872 else if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
2873 if (!GSE->isResultDependent())
2874 return GSE->getResultExpr();
2877 else if (auto *CE = dyn_cast<ChooseExpr>(E)) {
2878 if (!CE->isConditionDependent())
2879 return CE->getChosenSubExpr();
2885 static Expr *IgnoreNoopCastsSingleStep(const ASTContext &Ctx, Expr *E) {
2886 if (auto *CE = dyn_cast<CastExpr>(E)) {
2887 // We ignore integer <-> casts that are of the same width, ptr<->ptr and
2888 // ptr<->int casts of the same width. We also ignore all identity casts.
2889 Expr *SubExpr = CE->getSubExpr();
2890 bool IsIdentityCast =
2891 Ctx.hasSameUnqualifiedType(E->getType(), SubExpr->getType());
2892 bool IsSameWidthCast =
2893 (E->getType()->isPointerType() || E->getType()->isIntegralType(Ctx)) &&
2894 (SubExpr->getType()->isPointerType() ||
2895 SubExpr->getType()->isIntegralType(Ctx)) &&
2896 (Ctx.getTypeSize(E->getType()) == Ctx.getTypeSize(SubExpr->getType()));
2898 if (IsIdentityCast || IsSameWidthCast)
2902 else if (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
2903 return NTTP->getReplacement();
2908 static Expr *IgnoreExprNodesImpl(Expr *E) { return E; }
2909 template <typename FnTy, typename... FnTys>
2910 static Expr *IgnoreExprNodesImpl(Expr *E, FnTy &&Fn, FnTys &&... Fns) {
2911 return IgnoreExprNodesImpl(Fn(E), std::forward<FnTys>(Fns)...);
2914 /// Given an expression E and functions Fn_1,...,Fn_n : Expr * -> Expr *,
2915 /// Recursively apply each of the functions to E until reaching a fixed point.
2916 /// Note that a null E is valid; in this case nothing is done.
2917 template <typename... FnTys>
2918 static Expr *IgnoreExprNodes(Expr *E, FnTys &&... Fns) {
2919 Expr *LastE = nullptr;
2920 while (E != LastE) {
2922 E = IgnoreExprNodesImpl(E, std::forward<FnTys>(Fns)...);
2927 Expr *Expr::IgnoreImpCasts() {
2928 return IgnoreExprNodes(this, IgnoreImpCastsSingleStep);
2931 Expr *Expr::IgnoreCasts() {
2932 return IgnoreExprNodes(this, IgnoreCastsSingleStep);
2935 Expr *Expr::IgnoreImplicit() {
2936 return IgnoreExprNodes(this, IgnoreImplicitSingleStep);
2939 Expr *Expr::IgnoreImplicitAsWritten() {
2940 return IgnoreExprNodes(this, IgnoreImplicitAsWrittenSingleStep);
2943 Expr *Expr::IgnoreParens() {
2944 return IgnoreExprNodes(this, IgnoreParensSingleStep);
2947 Expr *Expr::IgnoreParenImpCasts() {
2948 return IgnoreExprNodes(this, IgnoreParensSingleStep,
2949 IgnoreImpCastsExtraSingleStep);
2952 Expr *Expr::IgnoreParenCasts() {
2953 return IgnoreExprNodes(this, IgnoreParensSingleStep, IgnoreCastsSingleStep);
2956 Expr *Expr::IgnoreConversionOperator() {
2957 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(this)) {
2958 if (MCE->getMethodDecl() && isa<CXXConversionDecl>(MCE->getMethodDecl()))
2959 return MCE->getImplicitObjectArgument();
2964 Expr *Expr::IgnoreParenLValueCasts() {
2965 return IgnoreExprNodes(this, IgnoreParensSingleStep,
2966 IgnoreLValueCastsSingleStep);
2969 Expr *Expr::ignoreParenBaseCasts() {
2970 return IgnoreExprNodes(this, IgnoreParensSingleStep,
2971 IgnoreBaseCastsSingleStep);
2974 Expr *Expr::IgnoreParenNoopCasts(const ASTContext &Ctx) {
2975 return IgnoreExprNodes(this, IgnoreParensSingleStep, [&Ctx](Expr *E) {
2976 return IgnoreNoopCastsSingleStep(Ctx, E);
2980 Expr *Expr::IgnoreUnlessSpelledInSource() {
2983 Expr *LastE = nullptr;
2984 while (E != LastE) {
2986 E = IgnoreExprNodes(E, IgnoreImplicitSingleStep,
2987 IgnoreImpCastsExtraSingleStep,
2988 IgnoreParensOnlySingleStep);
2990 auto SR = E->getSourceRange();
2992 if (auto *C = dyn_cast<CXXConstructExpr>(E)) {
2993 auto NumArgs = C->getNumArgs();
2995 (NumArgs > 1 && isa<CXXDefaultArgExpr>(C->getArg(1)))) {
2996 Expr *A = C->getArg(0);
2997 if (A->getSourceRange() == SR || !isa<CXXTemporaryObjectExpr>(C))
3002 if (auto *C = dyn_cast<CXXMemberCallExpr>(E)) {
3003 Expr *ExprNode = C->getImplicitObjectArgument();
3004 if (ExprNode->getSourceRange() == SR) {
3008 if (auto *PE = dyn_cast<ParenExpr>(ExprNode)) {
3009 if (PE->getSourceRange() == C->getSourceRange()) {
3014 ExprNode = ExprNode->IgnoreParenImpCasts();
3015 if (ExprNode->getSourceRange() == SR)
3023 bool Expr::isDefaultArgument() const {
3024 const Expr *E = this;
3025 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
3026 E = M->getSubExpr();
3028 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3029 E = ICE->getSubExprAsWritten();
3031 return isa<CXXDefaultArgExpr>(E);
3034 /// Skip over any no-op casts and any temporary-binding
3036 static const Expr *skipTemporaryBindingsNoOpCastsAndParens(const Expr *E) {
3037 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
3038 E = M->getSubExpr();
3040 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3041 if (ICE->getCastKind() == CK_NoOp)
3042 E = ICE->getSubExpr();
3047 while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
3048 E = BE->getSubExpr();
3050 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3051 if (ICE->getCastKind() == CK_NoOp)
3052 E = ICE->getSubExpr();
3057 return E->IgnoreParens();
3060 /// isTemporaryObject - Determines if this expression produces a
3061 /// temporary of the given class type.
3062 bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const {
3063 if (!C.hasSameUnqualifiedType(getType(), C.getTypeDeclType(TempTy)))
3066 const Expr *E = skipTemporaryBindingsNoOpCastsAndParens(this);
3068 // Temporaries are by definition pr-values of class type.
3069 if (!E->Classify(C).isPRValue()) {
3070 // In this context, property reference is a message call and is pr-value.
3071 if (!isa<ObjCPropertyRefExpr>(E))
3075 // Black-list a few cases which yield pr-values of class type that don't
3076 // refer to temporaries of that type:
3078 // - implicit derived-to-base conversions
3079 if (isa<ImplicitCastExpr>(E)) {
3080 switch (cast<ImplicitCastExpr>(E)->getCastKind()) {
3081 case CK_DerivedToBase:
3082 case CK_UncheckedDerivedToBase:
3089 // - member expressions (all)
3090 if (isa<MemberExpr>(E))
3093 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E))
3094 if (BO->isPtrMemOp())
3097 // - opaque values (all)
3098 if (isa<OpaqueValueExpr>(E))
3104 bool Expr::isImplicitCXXThis() const {
3105 const Expr *E = this;
3107 // Strip away parentheses and casts we don't care about.
3109 if (const ParenExpr *Paren = dyn_cast<ParenExpr>(E)) {
3110 E = Paren->getSubExpr();
3114 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3115 if (ICE->getCastKind() == CK_NoOp ||
3116 ICE->getCastKind() == CK_LValueToRValue ||
3117 ICE->getCastKind() == CK_DerivedToBase ||
3118 ICE->getCastKind() == CK_UncheckedDerivedToBase) {
3119 E = ICE->getSubExpr();
3124 if (const UnaryOperator* UnOp = dyn_cast<UnaryOperator>(E)) {
3125 if (UnOp->getOpcode() == UO_Extension) {
3126 E = UnOp->getSubExpr();
3131 if (const MaterializeTemporaryExpr *M
3132 = dyn_cast<MaterializeTemporaryExpr>(E)) {
3133 E = M->getSubExpr();
3140 if (const CXXThisExpr *This = dyn_cast<CXXThisExpr>(E))
3141 return This->isImplicit();
3146 /// hasAnyTypeDependentArguments - Determines if any of the expressions
3147 /// in Exprs is type-dependent.
3148 bool Expr::hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs) {
3149 for (unsigned I = 0; I < Exprs.size(); ++I)
3150 if (Exprs[I]->isTypeDependent())
3156 bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef,
3157 const Expr **Culprit) const {
3158 assert(!isValueDependent() &&
3159 "Expression evaluator can't be called on a dependent expression.");
3161 // This function is attempting whether an expression is an initializer
3162 // which can be evaluated at compile-time. It very closely parallels
3163 // ConstExprEmitter in CGExprConstant.cpp; if they don't match, it
3164 // will lead to unexpected results. Like ConstExprEmitter, it falls back
3165 // to isEvaluatable most of the time.
3167 // If we ever capture reference-binding directly in the AST, we can
3168 // kill the second parameter.
3172 if (EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects)
3179 switch (getStmtClass()) {
3181 case Stmt::ExprWithCleanupsClass:
3182 return cast<ExprWithCleanups>(this)->getSubExpr()->isConstantInitializer(
3183 Ctx, IsForRef, Culprit);
3184 case StringLiteralClass:
3185 case ObjCEncodeExprClass:
3187 case CXXTemporaryObjectExprClass:
3188 case CXXConstructExprClass: {
3189 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
3191 if (CE->getConstructor()->isTrivial() &&
3192 CE->getConstructor()->getParent()->hasTrivialDestructor()) {
3193 // Trivial default constructor
3194 if (!CE->getNumArgs()) return true;
3196 // Trivial copy constructor
3197 assert(CE->getNumArgs() == 1 && "trivial ctor with > 1 argument");
3198 return CE->getArg(0)->isConstantInitializer(Ctx, false, Culprit);
3203 case ConstantExprClass: {
3204 // FIXME: We should be able to return "true" here, but it can lead to extra
3205 // error messages. E.g. in Sema/array-init.c.
3206 const Expr *Exp = cast<ConstantExpr>(this)->getSubExpr();
3207 return Exp->isConstantInitializer(Ctx, false, Culprit);
3209 case CompoundLiteralExprClass: {
3210 // This handles gcc's extension that allows global initializers like
3211 // "struct x {int x;} x = (struct x) {};".
3212 // FIXME: This accepts other cases it shouldn't!
3213 const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer();
3214 return Exp->isConstantInitializer(Ctx, false, Culprit);
3216 case DesignatedInitUpdateExprClass: {
3217 const DesignatedInitUpdateExpr *DIUE = cast<DesignatedInitUpdateExpr>(this);
3218 return DIUE->getBase()->isConstantInitializer(Ctx, false, Culprit) &&
3219 DIUE->getUpdater()->isConstantInitializer(Ctx, false, Culprit);
3221 case InitListExprClass: {
3222 const InitListExpr *ILE = cast<InitListExpr>(this);
3223 assert(ILE->isSemanticForm() && "InitListExpr must be in semantic form");
3224 if (ILE->getType()->isArrayType()) {
3225 unsigned numInits = ILE->getNumInits();
3226 for (unsigned i = 0; i < numInits; i++) {
3227 if (!ILE->getInit(i)->isConstantInitializer(Ctx, false, Culprit))
3233 if (ILE->getType()->isRecordType()) {
3234 unsigned ElementNo = 0;
3235 RecordDecl *RD = ILE->getType()->castAs<RecordType>()->getDecl();
3236 for (const auto *Field : RD->fields()) {
3237 // If this is a union, skip all the fields that aren't being initialized.
3238 if (RD->isUnion() && ILE->getInitializedFieldInUnion() != Field)
3241 // Don't emit anonymous bitfields, they just affect layout.
3242 if (Field->isUnnamedBitfield())
3245 if (ElementNo < ILE->getNumInits()) {
3246 const Expr *Elt = ILE->getInit(ElementNo++);
3247 if (Field->isBitField()) {
3248 // Bitfields have to evaluate to an integer.
3250 if (!Elt->EvaluateAsInt(Result, Ctx)) {
3256 bool RefType = Field->getType()->isReferenceType();
3257 if (!Elt->isConstantInitializer(Ctx, RefType, Culprit))
3267 case ImplicitValueInitExprClass:
3268 case NoInitExprClass:
3270 case ParenExprClass:
3271 return cast<ParenExpr>(this)->getSubExpr()
3272 ->isConstantInitializer(Ctx, IsForRef, Culprit);
3273 case GenericSelectionExprClass:
3274 return cast<GenericSelectionExpr>(this)->getResultExpr()
3275 ->isConstantInitializer(Ctx, IsForRef, Culprit);
3276 case ChooseExprClass:
3277 if (cast<ChooseExpr>(this)->isConditionDependent()) {
3282 return cast<ChooseExpr>(this)->getChosenSubExpr()
3283 ->isConstantInitializer(Ctx, IsForRef, Culprit);
3284 case UnaryOperatorClass: {
3285 const UnaryOperator* Exp = cast<UnaryOperator>(this);
3286 if (Exp->getOpcode() == UO_Extension)
3287 return Exp->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
3290 case CXXFunctionalCastExprClass:
3291 case CXXStaticCastExprClass:
3292 case ImplicitCastExprClass:
3293 case CStyleCastExprClass:
3294 case ObjCBridgedCastExprClass:
3295 case CXXDynamicCastExprClass:
3296 case CXXReinterpretCastExprClass:
3297 case CXXAddrspaceCastExprClass:
3298 case CXXConstCastExprClass: {
3299 const CastExpr *CE = cast<CastExpr>(this);
3301 // Handle misc casts we want to ignore.
3302 if (CE->getCastKind() == CK_NoOp ||
3303 CE->getCastKind() == CK_LValueToRValue ||
3304 CE->getCastKind() == CK_ToUnion ||
3305 CE->getCastKind() == CK_ConstructorConversion ||
3306 CE->getCastKind() == CK_NonAtomicToAtomic ||
3307 CE->getCastKind() == CK_AtomicToNonAtomic ||
3308 CE->getCastKind() == CK_IntToOCLSampler)
3309 return CE->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
3313 case MaterializeTemporaryExprClass:
3314 return cast<MaterializeTemporaryExpr>(this)
3316 ->isConstantInitializer(Ctx, false, Culprit);
3318 case SubstNonTypeTemplateParmExprClass:
3319 return cast<SubstNonTypeTemplateParmExpr>(this)->getReplacement()
3320 ->isConstantInitializer(Ctx, false, Culprit);
3321 case CXXDefaultArgExprClass:
3322 return cast<CXXDefaultArgExpr>(this)->getExpr()
3323 ->isConstantInitializer(Ctx, false, Culprit);
3324 case CXXDefaultInitExprClass:
3325 return cast<CXXDefaultInitExpr>(this)->getExpr()
3326 ->isConstantInitializer(Ctx, false, Culprit);
3328 // Allow certain forms of UB in constant initializers: signed integer
3329 // overflow and floating-point division by zero. We'll give a warning on
3330 // these, but they're common enough that we have to accept them.
3331 if (isEvaluatable(Ctx, SE_AllowUndefinedBehavior))
3338 bool CallExpr::isBuiltinAssumeFalse(const ASTContext &Ctx) const {
3339 const FunctionDecl* FD = getDirectCallee();
3340 if (!FD || (FD->getBuiltinID() != Builtin::BI__assume &&
3341 FD->getBuiltinID() != Builtin::BI__builtin_assume))
3344 const Expr* Arg = getArg(0);
3346 return !Arg->isValueDependent() &&
3347 Arg->EvaluateAsBooleanCondition(ArgVal, Ctx) && !ArgVal;
3351 /// Look for any side effects within a Stmt.
3352 class SideEffectFinder : public ConstEvaluatedExprVisitor<SideEffectFinder> {
3353 typedef ConstEvaluatedExprVisitor<SideEffectFinder> Inherited;
3354 const bool IncludePossibleEffects;
3355 bool HasSideEffects;
3358 explicit SideEffectFinder(const ASTContext &Context, bool IncludePossible)
3359 : Inherited(Context),
3360 IncludePossibleEffects(IncludePossible), HasSideEffects(false) { }
3362 bool hasSideEffects() const { return HasSideEffects; }
3364 void VisitDecl(const Decl *D) {
3368 // We assume the caller checks subexpressions (eg, the initializer, VLA
3369 // bounds) for side-effects on our behalf.
3370 if (auto *VD = dyn_cast<VarDecl>(D)) {
3371 // Registering a destructor is a side-effect.
3372 if (IncludePossibleEffects && VD->isThisDeclarationADefinition() &&
3373 VD->needsDestruction(Context))
3374 HasSideEffects = true;
3378 void VisitDeclStmt(const DeclStmt *DS) {
3379 for (auto *D : DS->decls())
3381 Inherited::VisitDeclStmt(DS);
3384 void VisitExpr(const Expr *E) {
3385 if (!HasSideEffects &&
3386 E->HasSideEffects(Context, IncludePossibleEffects))
3387 HasSideEffects = true;
3392 bool Expr::HasSideEffects(const ASTContext &Ctx,
3393 bool IncludePossibleEffects) const {
3394 // In circumstances where we care about definite side effects instead of
3395 // potential side effects, we want to ignore expressions that are part of a
3396 // macro expansion as a potential side effect.
3397 if (!IncludePossibleEffects && getExprLoc().isMacroID())
3400 if (isInstantiationDependent())
3401 return IncludePossibleEffects;
3403 switch (getStmtClass()) {
3405 #define ABSTRACT_STMT(Type)
3406 #define STMT(Type, Base) case Type##Class:
3407 #define EXPR(Type, Base)
3408 #include "clang/AST/StmtNodes.inc"
3409 llvm_unreachable("unexpected Expr kind");
3411 case DependentScopeDeclRefExprClass:
3412 case CXXUnresolvedConstructExprClass:
3413 case CXXDependentScopeMemberExprClass:
3414 case UnresolvedLookupExprClass:
3415 case UnresolvedMemberExprClass:
3416 case PackExpansionExprClass:
3417 case SubstNonTypeTemplateParmPackExprClass:
3418 case FunctionParmPackExprClass:
3420 case RecoveryExprClass:
3421 case CXXFoldExprClass:
3422 llvm_unreachable("shouldn't see dependent / unresolved nodes here");
3424 case DeclRefExprClass:
3425 case ObjCIvarRefExprClass:
3426 case PredefinedExprClass:
3427 case IntegerLiteralClass:
3428 case FixedPointLiteralClass:
3429 case FloatingLiteralClass:
3430 case ImaginaryLiteralClass:
3431 case StringLiteralClass:
3432 case CharacterLiteralClass:
3433 case OffsetOfExprClass:
3434 case ImplicitValueInitExprClass:
3435 case UnaryExprOrTypeTraitExprClass:
3436 case AddrLabelExprClass:
3437 case GNUNullExprClass:
3438 case ArrayInitIndexExprClass:
3439 case NoInitExprClass:
3440 case CXXBoolLiteralExprClass:
3441 case CXXNullPtrLiteralExprClass:
3442 case CXXThisExprClass:
3443 case CXXScalarValueInitExprClass:
3444 case TypeTraitExprClass:
3445 case ArrayTypeTraitExprClass:
3446 case ExpressionTraitExprClass:
3447 case CXXNoexceptExprClass:
3448 case SizeOfPackExprClass:
3449 case ObjCStringLiteralClass:
3450 case ObjCEncodeExprClass:
3451 case ObjCBoolLiteralExprClass:
3452 case ObjCAvailabilityCheckExprClass:
3453 case CXXUuidofExprClass:
3454 case OpaqueValueExprClass:
3455 case SourceLocExprClass:
3456 case ConceptSpecializationExprClass:
3457 case RequiresExprClass:
3458 // These never have a side-effect.
3461 case ConstantExprClass:
3462 // FIXME: Move this into the "return false;" block above.
3463 return cast<ConstantExpr>(this)->getSubExpr()->HasSideEffects(
3464 Ctx, IncludePossibleEffects);
3467 case CXXOperatorCallExprClass:
3468 case CXXMemberCallExprClass:
3469 case CUDAKernelCallExprClass:
3470 case UserDefinedLiteralClass: {
3471 // We don't know a call definitely has side effects, except for calls
3472 // to pure/const functions that definitely don't.
3473 // If the call itself is considered side-effect free, check the operands.
3474 const Decl *FD = cast<CallExpr>(this)->getCalleeDecl();
3475 bool IsPure = FD && (FD->hasAttr<ConstAttr>() || FD->hasAttr<PureAttr>());
3476 if (IsPure || !IncludePossibleEffects)
3481 case BlockExprClass:
3482 case CXXBindTemporaryExprClass:
3483 if (!IncludePossibleEffects)
3487 case MSPropertyRefExprClass:
3488 case MSPropertySubscriptExprClass:
3489 case CompoundAssignOperatorClass:
3490 case VAArgExprClass:
3491 case AtomicExprClass:
3492 case CXXThrowExprClass:
3493 case CXXNewExprClass:
3494 case CXXDeleteExprClass:
3495 case CoawaitExprClass:
3496 case DependentCoawaitExprClass:
3497 case CoyieldExprClass:
3498 // These always have a side-effect.
3501 case StmtExprClass: {
3502 // StmtExprs have a side-effect if any substatement does.
3503 SideEffectFinder Finder(Ctx, IncludePossibleEffects);
3504 Finder.Visit(cast<StmtExpr>(this)->getSubStmt());
3505 return Finder.hasSideEffects();
3508 case ExprWithCleanupsClass:
3509 if (IncludePossibleEffects)
3510 if (cast<ExprWithCleanups>(this)->cleanupsHaveSideEffects())
3514 case ParenExprClass:
3515 case ArraySubscriptExprClass:
3516 case MatrixSubscriptExprClass:
3517 case OMPArraySectionExprClass:
3518 case OMPArrayShapingExprClass:
3519 case OMPIteratorExprClass:
3520 case MemberExprClass:
3521 case ConditionalOperatorClass:
3522 case BinaryConditionalOperatorClass:
3523 case CompoundLiteralExprClass:
3524 case ExtVectorElementExprClass:
3525 case DesignatedInitExprClass:
3526 case DesignatedInitUpdateExprClass:
3527 case ArrayInitLoopExprClass:
3528 case ParenListExprClass:
3529 case CXXPseudoDestructorExprClass:
3530 case CXXRewrittenBinaryOperatorClass:
3531 case CXXStdInitializerListExprClass:
3532 case SubstNonTypeTemplateParmExprClass:
3533 case MaterializeTemporaryExprClass:
3534 case ShuffleVectorExprClass:
3535 case ConvertVectorExprClass:
3536 case AsTypeExprClass:
3537 // These have a side-effect if any subexpression does.
3540 case UnaryOperatorClass:
3541 if (cast<UnaryOperator>(this)->isIncrementDecrementOp())
3545 case BinaryOperatorClass:
3546 if (cast<BinaryOperator>(this)->isAssignmentOp())
3550 case InitListExprClass:
3551 // FIXME: The children for an InitListExpr doesn't include the array filler.
3552 if (const Expr *E = cast<InitListExpr>(this)->getArrayFiller())
3553 if (E->HasSideEffects(Ctx, IncludePossibleEffects))
3557 case GenericSelectionExprClass:
3558 return cast<GenericSelectionExpr>(this)->getResultExpr()->
3559 HasSideEffects(Ctx, IncludePossibleEffects);
3561 case ChooseExprClass:
3562 return cast<ChooseExpr>(this)->getChosenSubExpr()->HasSideEffects(
3563 Ctx, IncludePossibleEffects);
3565 case CXXDefaultArgExprClass:
3566 return cast<CXXDefaultArgExpr>(this)->getExpr()->HasSideEffects(
3567 Ctx, IncludePossibleEffects);
3569 case CXXDefaultInitExprClass: {
3570 const FieldDecl *FD = cast<CXXDefaultInitExpr>(this)->getField();
3571 if (const Expr *E = FD->getInClassInitializer())
3572 return E->HasSideEffects(Ctx, IncludePossibleEffects);
3573 // If we've not yet parsed the initializer, assume it has side-effects.
3577 case CXXDynamicCastExprClass: {
3578 // A dynamic_cast expression has side-effects if it can throw.
3579 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(this);
3580 if (DCE->getTypeAsWritten()->isReferenceType() &&
3581 DCE->getCastKind() == CK_Dynamic)
3585 case ImplicitCastExprClass:
3586 case CStyleCastExprClass:
3587 case CXXStaticCastExprClass:
3588 case CXXReinterpretCastExprClass:
3589 case CXXConstCastExprClass:
3590 case CXXAddrspaceCastExprClass:
3591 case CXXFunctionalCastExprClass:
3592 case BuiltinBitCastExprClass: {
3593 // While volatile reads are side-effecting in both C and C++, we treat them
3594 // as having possible (not definite) side-effects. This allows idiomatic
3595 // code to behave without warning, such as sizeof(*v) for a volatile-
3596 // qualified pointer.
3597 if (!IncludePossibleEffects)
3600 const CastExpr *CE = cast<CastExpr>(this);
3601 if (CE->getCastKind() == CK_LValueToRValue &&
3602 CE->getSubExpr()->getType().isVolatileQualified())
3607 case CXXTypeidExprClass:
3608 // typeid might throw if its subexpression is potentially-evaluated, so has
3609 // side-effects in that case whether or not its subexpression does.
3610 return cast<CXXTypeidExpr>(this)->isPotentiallyEvaluated();
3612 case CXXConstructExprClass:
3613 case CXXTemporaryObjectExprClass: {
3614 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
3615 if (!CE->getConstructor()->isTrivial() && IncludePossibleEffects)
3617 // A trivial constructor does not add any side-effects of its own. Just look
3618 // at its arguments.
3622 case CXXInheritedCtorInitExprClass: {
3623 const auto *ICIE = cast<CXXInheritedCtorInitExpr>(this);
3624 if (!ICIE->getConstructor()->isTrivial() && IncludePossibleEffects)
3629 case LambdaExprClass: {
3630 const LambdaExpr *LE = cast<LambdaExpr>(this);
3631 for (Expr *E : LE->capture_inits())
3632 if (E && E->HasSideEffects(Ctx, IncludePossibleEffects))
3637 case PseudoObjectExprClass: {
3638 // Only look for side-effects in the semantic form, and look past
3639 // OpaqueValueExpr bindings in that form.
3640 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
3641 for (PseudoObjectExpr::const_semantics_iterator I = PO->semantics_begin(),
3642 E = PO->semantics_end();
3644 const Expr *Subexpr = *I;
3645 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Subexpr))
3646 Subexpr = OVE->getSourceExpr();
3647 if (Subexpr->HasSideEffects(Ctx, IncludePossibleEffects))
3653 case ObjCBoxedExprClass:
3654 case ObjCArrayLiteralClass:
3655 case ObjCDictionaryLiteralClass:
3656 case ObjCSelectorExprClass:
3657 case ObjCProtocolExprClass:
3658 case ObjCIsaExprClass:
3659 case ObjCIndirectCopyRestoreExprClass:
3660 case ObjCSubscriptRefExprClass:
3661 case ObjCBridgedCastExprClass:
3662 case ObjCMessageExprClass:
3663 case ObjCPropertyRefExprClass:
3664 // FIXME: Classify these cases better.
3665 if (IncludePossibleEffects)
3670 // Recurse to children.
3671 for (const Stmt *SubStmt : children())
3673 cast<Expr>(SubStmt)->HasSideEffects(Ctx, IncludePossibleEffects))
3680 /// Look for a call to a non-trivial function within an expression.
3681 class NonTrivialCallFinder : public ConstEvaluatedExprVisitor<NonTrivialCallFinder>
3683 typedef ConstEvaluatedExprVisitor<NonTrivialCallFinder> Inherited;
3688 explicit NonTrivialCallFinder(const ASTContext &Context)
3689 : Inherited(Context), NonTrivial(false) { }
3691 bool hasNonTrivialCall() const { return NonTrivial; }
3693 void VisitCallExpr(const CallExpr *E) {
3694 if (const CXXMethodDecl *Method
3695 = dyn_cast_or_null<const CXXMethodDecl>(E->getCalleeDecl())) {
3696 if (Method->isTrivial()) {
3697 // Recurse to children of the call.
3698 Inherited::VisitStmt(E);
3706 void VisitCXXConstructExpr(const CXXConstructExpr *E) {
3707 if (E->getConstructor()->isTrivial()) {
3708 // Recurse to children of the call.
3709 Inherited::VisitStmt(E);
3716 void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
3717 if (E->getTemporary()->getDestructor()->isTrivial()) {
3718 Inherited::VisitStmt(E);
3727 bool Expr::hasNonTrivialCall(const ASTContext &Ctx) const {
3728 NonTrivialCallFinder Finder(Ctx);
3730 return Finder.hasNonTrivialCall();
3733 /// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null
3734 /// pointer constant or not, as well as the specific kind of constant detected.
3735 /// Null pointer constants can be integer constant expressions with the
3736 /// value zero, casts of zero to void*, nullptr (C++0X), or __null
3737 /// (a GNU extension).
3738 Expr::NullPointerConstantKind
3739 Expr::isNullPointerConstant(ASTContext &Ctx,
3740 NullPointerConstantValueDependence NPC) const {
3741 if (isValueDependent() &&
3742 (!Ctx.getLangOpts().CPlusPlus11 || Ctx.getLangOpts().MSVCCompat)) {
3744 case NPC_NeverValueDependent:
3745 llvm_unreachable("Unexpected value dependent expression!");
3746 case NPC_ValueDependentIsNull:
3747 if (isTypeDependent() || getType()->isIntegralType(Ctx))
3748 return NPCK_ZeroExpression;
3750 return NPCK_NotNull;
3752 case NPC_ValueDependentIsNotNull:
3753 return NPCK_NotNull;
3757 // Strip off a cast to void*, if it exists. Except in C++.
3758 if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) {
3759 if (!Ctx.getLangOpts().CPlusPlus) {
3760 // Check that it is a cast to void*.
3761 if (const PointerType *PT = CE->getType()->getAs<PointerType>()) {
3762 QualType Pointee = PT->getPointeeType();
3763 Qualifiers Qs = Pointee.getQualifiers();
3764 // Only (void*)0 or equivalent are treated as nullptr. If pointee type
3765 // has non-default address space it is not treated as nullptr.
3766 // (__generic void*)0 in OpenCL 2.0 should not be treated as nullptr
3767 // since it cannot be assigned to a pointer to constant address space.
3768 if ((Ctx.getLangOpts().OpenCLVersion >= 200 &&
3769 Pointee.getAddressSpace() == LangAS::opencl_generic) ||
3770 (Ctx.getLangOpts().OpenCL &&
3771 Ctx.getLangOpts().OpenCLVersion < 200 &&
3772 Pointee.getAddressSpace() == LangAS::opencl_private))
3773 Qs.removeAddressSpace();
3775 if (Pointee->isVoidType() && Qs.empty() && // to void*
3776 CE->getSubExpr()->getType()->isIntegerType()) // from int
3777 return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3780 } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) {
3781 // Ignore the ImplicitCastExpr type entirely.
3782 return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3783 } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) {
3784 // Accept ((void*)0) as a null pointer constant, as many other
3785 // implementations do.
3786 return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3787 } else if (const GenericSelectionExpr *GE =
3788 dyn_cast<GenericSelectionExpr>(this)) {
3789 if (GE->isResultDependent())
3790 return NPCK_NotNull;
3791 return GE->getResultExpr()->isNullPointerConstant(Ctx, NPC);
3792 } else if (const ChooseExpr *CE = dyn_cast<ChooseExpr>(this)) {
3793 if (CE->isConditionDependent())
3794 return NPCK_NotNull;
3795 return CE->getChosenSubExpr()->isNullPointerConstant(Ctx, NPC);
3796 } else if (const CXXDefaultArgExpr *DefaultArg
3797 = dyn_cast<CXXDefaultArgExpr>(this)) {
3798 // See through default argument expressions.
3799 return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC);
3800 } else if (const CXXDefaultInitExpr *DefaultInit
3801 = dyn_cast<CXXDefaultInitExpr>(this)) {
3802 // See through default initializer expressions.
3803 return DefaultInit->getExpr()->isNullPointerConstant(Ctx, NPC);
3804 } else if (isa<GNUNullExpr>(this)) {
3805 // The GNU __null extension is always a null pointer constant.
3806 return NPCK_GNUNull;
3807 } else if (const MaterializeTemporaryExpr *M
3808 = dyn_cast<MaterializeTemporaryExpr>(this)) {
3809 return M->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3810 } else if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(this)) {
3811 if (const Expr *Source = OVE->getSourceExpr())
3812 return Source->isNullPointerConstant(Ctx, NPC);
3815 // If the expression has no type information, it cannot be a null pointer
3817 if (getType().isNull())
3818 return NPCK_NotNull;
3820 // C++11 nullptr_t is always a null pointer constant.
3821 if (getType()->isNullPtrType())
3822 return NPCK_CXX11_nullptr;
3824 if (const RecordType *UT = getType()->getAsUnionType())
3825 if (!Ctx.getLangOpts().CPlusPlus11 &&
3826 UT && UT->getDecl()->hasAttr<TransparentUnionAttr>())
3827 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(this)){
3828 const Expr *InitExpr = CLE->getInitializer();
3829 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(InitExpr))
3830 return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC);
3832 // This expression must be an integer type.
3833 if (!getType()->isIntegerType() ||
3834 (Ctx.getLangOpts().CPlusPlus && getType()->isEnumeralType()))
3835 return NPCK_NotNull;
3837 if (Ctx.getLangOpts().CPlusPlus11) {
3838 // C++11 [conv.ptr]p1: A null pointer constant is an integer literal with
3839 // value zero or a prvalue of type std::nullptr_t.
3840 // Microsoft mode permits C++98 rules reflecting MSVC behavior.
3841 const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(this);
3842 if (Lit && !Lit->getValue())
3843 return NPCK_ZeroLiteral;
3844 else if (!Ctx.getLangOpts().MSVCCompat || !isCXX98IntegralConstantExpr(Ctx))
3845 return NPCK_NotNull;
3847 // If we have an integer constant expression, we need to *evaluate* it and
3848 // test for the value 0.
3849 if (!isIntegerConstantExpr(Ctx))
3850 return NPCK_NotNull;
3853 if (EvaluateKnownConstInt(Ctx) != 0)
3854 return NPCK_NotNull;
3856 if (isa<IntegerLiteral>(this))
3857 return NPCK_ZeroLiteral;
3858 return NPCK_ZeroExpression;
3861 /// If this expression is an l-value for an Objective C
3862 /// property, find the underlying property reference expression.
3863 const ObjCPropertyRefExpr *Expr::getObjCProperty() const {
3864 const Expr *E = this;
3866 assert((E->getValueKind() == VK_LValue &&
3867 E->getObjectKind() == OK_ObjCProperty) &&
3868 "expression is not a property reference");
3869 E = E->IgnoreParenCasts();
3870 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3871 if (BO->getOpcode() == BO_Comma) {
3880 return cast<ObjCPropertyRefExpr>(E);
3883 bool Expr::isObjCSelfExpr() const {
3884 const Expr *E = IgnoreParenImpCasts();
3886 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
3890 const ImplicitParamDecl *Param = dyn_cast<ImplicitParamDecl>(DRE->getDecl());
3894 const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(Param->getDeclContext());
3898 return M->getSelfDecl() == Param;
3901 FieldDecl *Expr::getSourceBitField() {
3902 Expr *E = this->IgnoreParens();
3904 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3905 if (ICE->getCastKind() == CK_LValueToRValue ||
3906 (ICE->getValueKind() != VK_RValue && ICE->getCastKind() == CK_NoOp))
3907 E = ICE->getSubExpr()->IgnoreParens();
3912 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E))
3913 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl()))
3914 if (Field->isBitField())
3917 if (ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
3918 FieldDecl *Ivar = IvarRef->getDecl();
3919 if (Ivar->isBitField())
3923 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E)) {
3924 if (FieldDecl *Field = dyn_cast<FieldDecl>(DeclRef->getDecl()))
3925 if (Field->isBitField())
3928 if (BindingDecl *BD = dyn_cast<BindingDecl>(DeclRef->getDecl()))
3929 if (Expr *E = BD->getBinding())
3930 return E->getSourceBitField();
3933 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E)) {
3934 if (BinOp->isAssignmentOp() && BinOp->getLHS())
3935 return BinOp->getLHS()->getSourceBitField();
3937 if (BinOp->getOpcode() == BO_Comma && BinOp->getRHS())
3938 return BinOp->getRHS()->getSourceBitField();
3941 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E))
3942 if (UnOp->isPrefix() && UnOp->isIncrementDecrementOp())
3943 return UnOp->getSubExpr()->getSourceBitField();
3948 bool Expr::refersToVectorElement() const {
3949 // FIXME: Why do we not just look at the ObjectKind here?
3950 const Expr *E = this->IgnoreParens();
3952 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3953 if (ICE->getValueKind() != VK_RValue &&
3954 ICE->getCastKind() == CK_NoOp)
3955 E = ICE->getSubExpr()->IgnoreParens();
3960 if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E))
3961 return ASE->getBase()->getType()->isVectorType();
3963 if (isa<ExtVectorElementExpr>(E))
3966 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3967 if (auto *BD = dyn_cast<BindingDecl>(DRE->getDecl()))
3968 if (auto *E = BD->getBinding())
3969 return E->refersToVectorElement();
3974 bool Expr::refersToGlobalRegisterVar() const {
3975 const Expr *E = this->IgnoreParenImpCasts();
3977 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3978 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
3979 if (VD->getStorageClass() == SC_Register &&
3980 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
3986 bool Expr::isSameComparisonOperand(const Expr* E1, const Expr* E2) {
3987 E1 = E1->IgnoreParens();
3988 E2 = E2->IgnoreParens();
3990 if (E1->getStmtClass() != E2->getStmtClass())
3993 switch (E1->getStmtClass()) {
3996 case CXXThisExprClass:
3998 case DeclRefExprClass: {
3999 // DeclRefExpr without an ImplicitCastExpr can happen for integral
4000 // template parameters.
4001 const auto *DRE1 = cast<DeclRefExpr>(E1);
4002 const auto *DRE2 = cast<DeclRefExpr>(E2);
4003 return DRE1->isRValue() && DRE2->isRValue() &&
4004 DRE1->getDecl() == DRE2->getDecl();
4006 case ImplicitCastExprClass: {
4007 // Peel off implicit casts.
4009 const auto *ICE1 = dyn_cast<ImplicitCastExpr>(E1);
4010 const auto *ICE2 = dyn_cast<ImplicitCastExpr>(E2);
4013 if (ICE1->getCastKind() != ICE2->getCastKind())
4015 E1 = ICE1->getSubExpr()->IgnoreParens();
4016 E2 = ICE2->getSubExpr()->IgnoreParens();
4017 // The final cast must be one of these types.
4018 if (ICE1->getCastKind() == CK_LValueToRValue ||
4019 ICE1->getCastKind() == CK_ArrayToPointerDecay ||
4020 ICE1->getCastKind() == CK_FunctionToPointerDecay) {
4025 const auto *DRE1 = dyn_cast<DeclRefExpr>(E1);
4026 const auto *DRE2 = dyn_cast<DeclRefExpr>(E2);
4028 return declaresSameEntity(DRE1->getDecl(), DRE2->getDecl());
4030 const auto *Ivar1 = dyn_cast<ObjCIvarRefExpr>(E1);
4031 const auto *Ivar2 = dyn_cast<ObjCIvarRefExpr>(E2);
4032 if (Ivar1 && Ivar2) {
4033 return Ivar1->isFreeIvar() && Ivar2->isFreeIvar() &&
4034 declaresSameEntity(Ivar1->getDecl(), Ivar2->getDecl());
4037 const auto *Array1 = dyn_cast<ArraySubscriptExpr>(E1);
4038 const auto *Array2 = dyn_cast<ArraySubscriptExpr>(E2);
4039 if (Array1 && Array2) {
4040 if (!isSameComparisonOperand(Array1->getBase(), Array2->getBase()))
4043 auto Idx1 = Array1->getIdx();
4044 auto Idx2 = Array2->getIdx();
4045 const auto Integer1 = dyn_cast<IntegerLiteral>(Idx1);
4046 const auto Integer2 = dyn_cast<IntegerLiteral>(Idx2);
4047 if (Integer1 && Integer2) {
4048 if (!llvm::APInt::isSameValue(Integer1->getValue(),
4049 Integer2->getValue()))
4052 if (!isSameComparisonOperand(Idx1, Idx2))
4059 // Walk the MemberExpr chain.
4060 while (isa<MemberExpr>(E1) && isa<MemberExpr>(E2)) {
4061 const auto *ME1 = cast<MemberExpr>(E1);
4062 const auto *ME2 = cast<MemberExpr>(E2);
4063 if (!declaresSameEntity(ME1->getMemberDecl(), ME2->getMemberDecl()))
4065 if (const auto *D = dyn_cast<VarDecl>(ME1->getMemberDecl()))
4066 if (D->isStaticDataMember())
4068 E1 = ME1->getBase()->IgnoreParenImpCasts();
4069 E2 = ME2->getBase()->IgnoreParenImpCasts();
4072 if (isa<CXXThisExpr>(E1) && isa<CXXThisExpr>(E2))
4075 // A static member variable can end the MemberExpr chain with either
4076 // a MemberExpr or a DeclRefExpr.
4077 auto getAnyDecl = [](const Expr *E) -> const ValueDecl * {
4078 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4079 return DRE->getDecl();
4080 if (const auto *ME = dyn_cast<MemberExpr>(E))
4081 return ME->getMemberDecl();
4085 const ValueDecl *VD1 = getAnyDecl(E1);
4086 const ValueDecl *VD2 = getAnyDecl(E2);
4087 return declaresSameEntity(VD1, VD2);
4092 /// isArrow - Return true if the base expression is a pointer to vector,
4093 /// return false if the base expression is a vector.
4094 bool ExtVectorElementExpr::isArrow() const {
4095 return getBase()->getType()->isPointerType();
4098 unsigned ExtVectorElementExpr::getNumElements() const {
4099 if (const VectorType *VT = getType()->getAs<VectorType>())
4100 return VT->getNumElements();
4104 /// containsDuplicateElements - Return true if any element access is repeated.
4105 bool ExtVectorElementExpr::containsDuplicateElements() const {
4106 // FIXME: Refactor this code to an accessor on the AST node which returns the
4107 // "type" of component access, and share with code below and in Sema.
4108 StringRef Comp = Accessor->getName();
4110 // Halving swizzles do not contain duplicate elements.
4111 if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd")
4114 // Advance past s-char prefix on hex swizzles.
4115 if (Comp[0] == 's' || Comp[0] == 'S')
4116 Comp = Comp.substr(1);
4118 for (unsigned i = 0, e = Comp.size(); i != e; ++i)
4119 if (Comp.substr(i + 1).find(Comp[i]) != StringRef::npos)
4125 /// getEncodedElementAccess - We encode the fields as a llvm ConstantArray.
4126 void ExtVectorElementExpr::getEncodedElementAccess(
4127 SmallVectorImpl<uint32_t> &Elts) const {
4128 StringRef Comp = Accessor->getName();
4129 bool isNumericAccessor = false;
4130 if (Comp[0] == 's' || Comp[0] == 'S') {
4131 Comp = Comp.substr(1);
4132 isNumericAccessor = true;
4135 bool isHi = Comp == "hi";
4136 bool isLo = Comp == "lo";
4137 bool isEven = Comp == "even";
4138 bool isOdd = Comp == "odd";
4140 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
4152 Index = ExtVectorType::getAccessorIdx(Comp[i], isNumericAccessor);
4154 Elts.push_back(Index);
4158 ShuffleVectorExpr::ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr *> args,
4159 QualType Type, SourceLocation BLoc,
4161 : Expr(ShuffleVectorExprClass, Type, VK_RValue, OK_Ordinary),
4162 BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(args.size()) {
4163 SubExprs = new (C) Stmt*[args.size()];
4164 for (unsigned i = 0; i != args.size(); i++)
4165 SubExprs[i] = args[i];
4167 setDependence(computeDependence(this));
4170 void ShuffleVectorExpr::setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs) {
4171 if (SubExprs) C.Deallocate(SubExprs);
4173 this->NumExprs = Exprs.size();
4174 SubExprs = new (C) Stmt*[NumExprs];
4175 memcpy(SubExprs, Exprs.data(), sizeof(Expr *) * Exprs.size());
4178 GenericSelectionExpr::GenericSelectionExpr(
4179 const ASTContext &, SourceLocation GenericLoc, Expr *ControllingExpr,
4180 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4181 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4182 bool ContainsUnexpandedParameterPack, unsigned ResultIndex)
4183 : Expr(GenericSelectionExprClass, AssocExprs[ResultIndex]->getType(),
4184 AssocExprs[ResultIndex]->getValueKind(),
4185 AssocExprs[ResultIndex]->getObjectKind()),
4186 NumAssocs(AssocExprs.size()), ResultIndex(ResultIndex),
4187 DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
4188 assert(AssocTypes.size() == AssocExprs.size() &&
4189 "Must have the same number of association expressions"
4190 " and TypeSourceInfo!");
4191 assert(ResultIndex < NumAssocs && "ResultIndex is out-of-bounds!");
4193 GenericSelectionExprBits.GenericLoc = GenericLoc;
4194 getTrailingObjects<Stmt *>()[ControllingIndex] = ControllingExpr;
4195 std::copy(AssocExprs.begin(), AssocExprs.end(),
4196 getTrailingObjects<Stmt *>() + AssocExprStartIndex);
4197 std::copy(AssocTypes.begin(), AssocTypes.end(),
4198 getTrailingObjects<TypeSourceInfo *>());
4200 setDependence(computeDependence(this, ContainsUnexpandedParameterPack));
4203 GenericSelectionExpr::GenericSelectionExpr(
4204 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4205 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4206 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4207 bool ContainsUnexpandedParameterPack)
4208 : Expr(GenericSelectionExprClass, Context.DependentTy, VK_RValue,
4210 NumAssocs(AssocExprs.size()), ResultIndex(ResultDependentIndex),
4211 DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
4212 assert(AssocTypes.size() == AssocExprs.size() &&
4213 "Must have the same number of association expressions"
4214 " and TypeSourceInfo!");
4216 GenericSelectionExprBits.GenericLoc = GenericLoc;
4217 getTrailingObjects<Stmt *>()[ControllingIndex] = ControllingExpr;
4218 std::copy(AssocExprs.begin(), AssocExprs.end(),
4219 getTrailingObjects<Stmt *>() + AssocExprStartIndex);
4220 std::copy(AssocTypes.begin(), AssocTypes.end(),
4221 getTrailingObjects<TypeSourceInfo *>());
4223 setDependence(computeDependence(this, ContainsUnexpandedParameterPack));
4226 GenericSelectionExpr::GenericSelectionExpr(EmptyShell Empty, unsigned NumAssocs)
4227 : Expr(GenericSelectionExprClass, Empty), NumAssocs(NumAssocs) {}
4229 GenericSelectionExpr *GenericSelectionExpr::Create(
4230 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4231 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4232 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4233 bool ContainsUnexpandedParameterPack, unsigned ResultIndex) {
4234 unsigned NumAssocs = AssocExprs.size();
4235 void *Mem = Context.Allocate(
4236 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4237 alignof(GenericSelectionExpr));
4238 return new (Mem) GenericSelectionExpr(
4239 Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc,
4240 RParenLoc, ContainsUnexpandedParameterPack, ResultIndex);
4243 GenericSelectionExpr *GenericSelectionExpr::Create(
4244 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4245 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4246 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4247 bool ContainsUnexpandedParameterPack) {
4248 unsigned NumAssocs = AssocExprs.size();
4249 void *Mem = Context.Allocate(
4250 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4251 alignof(GenericSelectionExpr));
4252 return new (Mem) GenericSelectionExpr(
4253 Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc,
4254 RParenLoc, ContainsUnexpandedParameterPack);
4257 GenericSelectionExpr *
4258 GenericSelectionExpr::CreateEmpty(const ASTContext &Context,
4259 unsigned NumAssocs) {
4260 void *Mem = Context.Allocate(
4261 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4262 alignof(GenericSelectionExpr));
4263 return new (Mem) GenericSelectionExpr(EmptyShell(), NumAssocs);
4266 //===----------------------------------------------------------------------===//
4267 // DesignatedInitExpr
4268 //===----------------------------------------------------------------------===//
4270 IdentifierInfo *DesignatedInitExpr::Designator::getFieldName() const {
4271 assert(Kind == FieldDesignator && "Only valid on a field designator");
4272 if (Field.NameOrField & 0x01)
4273 return reinterpret_cast<IdentifierInfo *>(Field.NameOrField&~0x01);
4275 return getField()->getIdentifier();
4278 DesignatedInitExpr::DesignatedInitExpr(const ASTContext &C, QualType Ty,
4279 llvm::ArrayRef<Designator> Designators,
4280 SourceLocation EqualOrColonLoc,
4282 ArrayRef<Expr *> IndexExprs, Expr *Init)
4283 : Expr(DesignatedInitExprClass, Ty, Init->getValueKind(),
4284 Init->getObjectKind()),
4285 EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax),
4286 NumDesignators(Designators.size()), NumSubExprs(IndexExprs.size() + 1) {
4287 this->Designators = new (C) Designator[NumDesignators];
4289 // Record the initializer itself.
4290 child_iterator Child = child_begin();
4293 // Copy the designators and their subexpressions, computing
4294 // value-dependence along the way.
4295 unsigned IndexIdx = 0;
4296 for (unsigned I = 0; I != NumDesignators; ++I) {
4297 this->Designators[I] = Designators[I];
4298 if (this->Designators[I].isArrayDesignator()) {
4299 // Copy the index expressions into permanent storage.
4300 *Child++ = IndexExprs[IndexIdx++];
4301 } else if (this->Designators[I].isArrayRangeDesignator()) {
4302 // Copy the start/end expressions into permanent storage.
4303 *Child++ = IndexExprs[IndexIdx++];
4304 *Child++ = IndexExprs[IndexIdx++];
4308 assert(IndexIdx == IndexExprs.size() && "Wrong number of index expressions");
4309 setDependence(computeDependence(this));
4312 DesignatedInitExpr *
4313 DesignatedInitExpr::Create(const ASTContext &C,
4314 llvm::ArrayRef<Designator> Designators,
4315 ArrayRef<Expr*> IndexExprs,
4316 SourceLocation ColonOrEqualLoc,
4317 bool UsesColonSyntax, Expr *Init) {
4318 void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(IndexExprs.size() + 1),
4319 alignof(DesignatedInitExpr));
4320 return new (Mem) DesignatedInitExpr(C, C.VoidTy, Designators,
4321 ColonOrEqualLoc, UsesColonSyntax,
4325 DesignatedInitExpr *DesignatedInitExpr::CreateEmpty(const ASTContext &C,
4326 unsigned NumIndexExprs) {
4327 void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(NumIndexExprs + 1),
4328 alignof(DesignatedInitExpr));
4329 return new (Mem) DesignatedInitExpr(NumIndexExprs + 1);
4332 void DesignatedInitExpr::setDesignators(const ASTContext &C,
4333 const Designator *Desigs,
4334 unsigned NumDesigs) {
4335 Designators = new (C) Designator[NumDesigs];
4336 NumDesignators = NumDesigs;
4337 for (unsigned I = 0; I != NumDesigs; ++I)
4338 Designators[I] = Desigs[I];
4341 SourceRange DesignatedInitExpr::getDesignatorsSourceRange() const {
4342 DesignatedInitExpr *DIE = const_cast<DesignatedInitExpr*>(this);
4344 return DIE->getDesignator(0)->getSourceRange();
4345 return SourceRange(DIE->getDesignator(0)->getBeginLoc(),
4346 DIE->getDesignator(size() - 1)->getEndLoc());
4349 SourceLocation DesignatedInitExpr::getBeginLoc() const {
4350 SourceLocation StartLoc;
4351 auto *DIE = const_cast<DesignatedInitExpr *>(this);
4352 Designator &First = *DIE->getDesignator(0);
4353 if (First.isFieldDesignator()) {
4355 StartLoc = SourceLocation::getFromRawEncoding(First.Field.FieldLoc);
4357 StartLoc = SourceLocation::getFromRawEncoding(First.Field.DotLoc);
4360 SourceLocation::getFromRawEncoding(First.ArrayOrRange.LBracketLoc);
4364 SourceLocation DesignatedInitExpr::getEndLoc() const {
4365 return getInit()->getEndLoc();
4368 Expr *DesignatedInitExpr::getArrayIndex(const Designator& D) const {
4369 assert(D.Kind == Designator::ArrayDesignator && "Requires array designator");
4370 return getSubExpr(D.ArrayOrRange.Index + 1);
4373 Expr *DesignatedInitExpr::getArrayRangeStart(const Designator &D) const {
4374 assert(D.Kind == Designator::ArrayRangeDesignator &&
4375 "Requires array range designator");
4376 return getSubExpr(D.ArrayOrRange.Index + 1);
4379 Expr *DesignatedInitExpr::getArrayRangeEnd(const Designator &D) const {
4380 assert(D.Kind == Designator::ArrayRangeDesignator &&
4381 "Requires array range designator");
4382 return getSubExpr(D.ArrayOrRange.Index + 2);
4385 /// Replaces the designator at index @p Idx with the series
4386 /// of designators in [First, Last).
4387 void DesignatedInitExpr::ExpandDesignator(const ASTContext &C, unsigned Idx,
4388 const Designator *First,
4389 const Designator *Last) {
4390 unsigned NumNewDesignators = Last - First;
4391 if (NumNewDesignators == 0) {
4392 std::copy_backward(Designators + Idx + 1,
4393 Designators + NumDesignators,
4395 --NumNewDesignators;
4397 } else if (NumNewDesignators == 1) {
4398 Designators[Idx] = *First;
4402 Designator *NewDesignators
4403 = new (C) Designator[NumDesignators - 1 + NumNewDesignators];
4404 std::copy(Designators, Designators + Idx, NewDesignators);
4405 std::copy(First, Last, NewDesignators + Idx);
4406 std::copy(Designators + Idx + 1, Designators + NumDesignators,
4407 NewDesignators + Idx + NumNewDesignators);
4408 Designators = NewDesignators;
4409 NumDesignators = NumDesignators - 1 + NumNewDesignators;
4412 DesignatedInitUpdateExpr::DesignatedInitUpdateExpr(const ASTContext &C,
4413 SourceLocation lBraceLoc,
4415 SourceLocation rBraceLoc)
4416 : Expr(DesignatedInitUpdateExprClass, baseExpr->getType(), VK_RValue,
4418 BaseAndUpdaterExprs[0] = baseExpr;
4420 InitListExpr *ILE = new (C) InitListExpr(C, lBraceLoc, None, rBraceLoc);
4421 ILE->setType(baseExpr->getType());
4422 BaseAndUpdaterExprs[1] = ILE;
4424 // FIXME: this is wrong, set it correctly.
4425 setDependence(ExprDependence::None);
4428 SourceLocation DesignatedInitUpdateExpr::getBeginLoc() const {
4429 return getBase()->getBeginLoc();
4432 SourceLocation DesignatedInitUpdateExpr::getEndLoc() const {
4433 return getBase()->getEndLoc();
4436 ParenListExpr::ParenListExpr(SourceLocation LParenLoc, ArrayRef<Expr *> Exprs,
4437 SourceLocation RParenLoc)
4438 : Expr(ParenListExprClass, QualType(), VK_RValue, OK_Ordinary),
4439 LParenLoc(LParenLoc), RParenLoc(RParenLoc) {
4440 ParenListExprBits.NumExprs = Exprs.size();
4442 for (unsigned I = 0, N = Exprs.size(); I != N; ++I)
4443 getTrailingObjects<Stmt *>()[I] = Exprs[I];
4444 setDependence(computeDependence(this));
4447 ParenListExpr::ParenListExpr(EmptyShell Empty, unsigned NumExprs)
4448 : Expr(ParenListExprClass, Empty) {
4449 ParenListExprBits.NumExprs = NumExprs;
4452 ParenListExpr *ParenListExpr::Create(const ASTContext &Ctx,
4453 SourceLocation LParenLoc,
4454 ArrayRef<Expr *> Exprs,
4455 SourceLocation RParenLoc) {
4456 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(Exprs.size()),
4457 alignof(ParenListExpr));
4458 return new (Mem) ParenListExpr(LParenLoc, Exprs, RParenLoc);
4461 ParenListExpr *ParenListExpr::CreateEmpty(const ASTContext &Ctx,
4462 unsigned NumExprs) {
4464 Ctx.Allocate(totalSizeToAlloc<Stmt *>(NumExprs), alignof(ParenListExpr));
4465 return new (Mem) ParenListExpr(EmptyShell(), NumExprs);
4468 BinaryOperator::BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs,
4469 Opcode opc, QualType ResTy, ExprValueKind VK,
4470 ExprObjectKind OK, SourceLocation opLoc,
4471 FPOptionsOverride FPFeatures)
4472 : Expr(BinaryOperatorClass, ResTy, VK, OK) {
4473 BinaryOperatorBits.Opc = opc;
4474 assert(!isCompoundAssignmentOp() &&
4475 "Use CompoundAssignOperator for compound assignments");
4476 BinaryOperatorBits.OpLoc = opLoc;
4477 SubExprs[LHS] = lhs;
4478 SubExprs[RHS] = rhs;
4479 BinaryOperatorBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();
4480 if (BinaryOperatorBits.HasFPFeatures)
4481 *getTrailingFPFeatures() = FPFeatures;
4482 setDependence(computeDependence(this));
4485 BinaryOperator::BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs,
4486 Opcode opc, QualType ResTy, ExprValueKind VK,
4487 ExprObjectKind OK, SourceLocation opLoc,
4488 FPOptionsOverride FPFeatures, bool dead2)
4489 : Expr(CompoundAssignOperatorClass, ResTy, VK, OK) {
4490 BinaryOperatorBits.Opc = opc;
4491 assert(isCompoundAssignmentOp() &&
4492 "Use CompoundAssignOperator for compound assignments");
4493 BinaryOperatorBits.OpLoc = opLoc;
4494 SubExprs[LHS] = lhs;
4495 SubExprs[RHS] = rhs;
4496 BinaryOperatorBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();
4497 if (BinaryOperatorBits.HasFPFeatures)
4498 *getTrailingFPFeatures() = FPFeatures;
4499 setDependence(computeDependence(this));
4502 BinaryOperator *BinaryOperator::CreateEmpty(const ASTContext &C,
4503 bool HasFPFeatures) {
4504 unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);
4506 C.Allocate(sizeof(BinaryOperator) + Extra, alignof(BinaryOperator));
4507 return new (Mem) BinaryOperator(EmptyShell());
4510 BinaryOperator *BinaryOperator::Create(const ASTContext &C, Expr *lhs,
4511 Expr *rhs, Opcode opc, QualType ResTy,
4512 ExprValueKind VK, ExprObjectKind OK,
4513 SourceLocation opLoc,
4514 FPOptionsOverride FPFeatures) {
4515 bool HasFPFeatures = FPFeatures.requiresTrailingStorage();
4516 unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);
4518 C.Allocate(sizeof(BinaryOperator) + Extra, alignof(BinaryOperator));
4520 BinaryOperator(C, lhs, rhs, opc, ResTy, VK, OK, opLoc, FPFeatures);
4523 CompoundAssignOperator *
4524 CompoundAssignOperator::CreateEmpty(const ASTContext &C, bool HasFPFeatures) {
4525 unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);
4526 void *Mem = C.Allocate(sizeof(CompoundAssignOperator) + Extra,
4527 alignof(CompoundAssignOperator));
4528 return new (Mem) CompoundAssignOperator(C, EmptyShell(), HasFPFeatures);
4531 CompoundAssignOperator *
4532 CompoundAssignOperator::Create(const ASTContext &C, Expr *lhs, Expr *rhs,
4533 Opcode opc, QualType ResTy, ExprValueKind VK,
4534 ExprObjectKind OK, SourceLocation opLoc,
4535 FPOptionsOverride FPFeatures,
4536 QualType CompLHSType, QualType CompResultType) {
4537 bool HasFPFeatures = FPFeatures.requiresTrailingStorage();
4538 unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);
4539 void *Mem = C.Allocate(sizeof(CompoundAssignOperator) + Extra,
4540 alignof(CompoundAssignOperator));
4542 CompoundAssignOperator(C, lhs, rhs, opc, ResTy, VK, OK, opLoc, FPFeatures,
4543 CompLHSType, CompResultType);
4546 UnaryOperator *UnaryOperator::CreateEmpty(const ASTContext &C,
4547 bool hasFPFeatures) {
4548 void *Mem = C.Allocate(totalSizeToAlloc<FPOptionsOverride>(hasFPFeatures),
4549 alignof(UnaryOperator));
4550 return new (Mem) UnaryOperator(hasFPFeatures, EmptyShell());
4553 UnaryOperator::UnaryOperator(const ASTContext &Ctx, Expr *input, Opcode opc,
4554 QualType type, ExprValueKind VK, ExprObjectKind OK,
4555 SourceLocation l, bool CanOverflow,
4556 FPOptionsOverride FPFeatures)
4557 : Expr(UnaryOperatorClass, type, VK, OK), Val(input) {
4558 UnaryOperatorBits.Opc = opc;
4559 UnaryOperatorBits.CanOverflow = CanOverflow;
4560 UnaryOperatorBits.Loc = l;
4561 UnaryOperatorBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();
4562 setDependence(computeDependence(this));
4565 UnaryOperator *UnaryOperator::Create(const ASTContext &C, Expr *input,
4566 Opcode opc, QualType type,
4567 ExprValueKind VK, ExprObjectKind OK,
4568 SourceLocation l, bool CanOverflow,
4569 FPOptionsOverride FPFeatures) {
4570 bool HasFPFeatures = FPFeatures.requiresTrailingStorage();
4571 unsigned Size = totalSizeToAlloc<FPOptionsOverride>(HasFPFeatures);
4572 void *Mem = C.Allocate(Size, alignof(UnaryOperator));
4574 UnaryOperator(C, input, opc, type, VK, OK, l, CanOverflow, FPFeatures);
4577 const OpaqueValueExpr *OpaqueValueExpr::findInCopyConstruct(const Expr *e) {
4578 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(e))
4579 e = ewc->getSubExpr();
4580 if (const MaterializeTemporaryExpr *m = dyn_cast<MaterializeTemporaryExpr>(e))
4581 e = m->getSubExpr();
4582 e = cast<CXXConstructExpr>(e)->getArg(0);
4583 while (const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
4584 e = ice->getSubExpr();
4585 return cast<OpaqueValueExpr>(e);
4588 PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &Context,
4590 unsigned numSemanticExprs) {
4592 Context.Allocate(totalSizeToAlloc<Expr *>(1 + numSemanticExprs),
4593 alignof(PseudoObjectExpr));
4594 return new(buffer) PseudoObjectExpr(sh, numSemanticExprs);
4597 PseudoObjectExpr::PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs)
4598 : Expr(PseudoObjectExprClass, shell) {
4599 PseudoObjectExprBits.NumSubExprs = numSemanticExprs + 1;
4602 PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &C, Expr *syntax,
4603 ArrayRef<Expr*> semantics,
4604 unsigned resultIndex) {
4605 assert(syntax && "no syntactic expression!");
4606 assert(semantics.size() && "no semantic expressions!");
4610 if (resultIndex == NoResult) {
4614 assert(resultIndex < semantics.size());
4615 type = semantics[resultIndex]->getType();
4616 VK = semantics[resultIndex]->getValueKind();
4617 assert(semantics[resultIndex]->getObjectKind() == OK_Ordinary);
4620 void *buffer = C.Allocate(totalSizeToAlloc<Expr *>(semantics.size() + 1),
4621 alignof(PseudoObjectExpr));
4622 return new(buffer) PseudoObjectExpr(type, VK, syntax, semantics,
4626 PseudoObjectExpr::PseudoObjectExpr(QualType type, ExprValueKind VK,
4627 Expr *syntax, ArrayRef<Expr *> semantics,
4628 unsigned resultIndex)
4629 : Expr(PseudoObjectExprClass, type, VK, OK_Ordinary) {
4630 PseudoObjectExprBits.NumSubExprs = semantics.size() + 1;
4631 PseudoObjectExprBits.ResultIndex = resultIndex + 1;
4633 for (unsigned i = 0, e = semantics.size() + 1; i != e; ++i) {
4634 Expr *E = (i == 0 ? syntax : semantics[i-1]);
4635 getSubExprsBuffer()[i] = E;
4637 if (isa<OpaqueValueExpr>(E))
4638 assert(cast<OpaqueValueExpr>(E)->getSourceExpr() != nullptr &&
4639 "opaque-value semantic expressions for pseudo-object "
4640 "operations must have sources");
4643 setDependence(computeDependence(this));
4646 //===----------------------------------------------------------------------===//
4647 // Child Iterators for iterating over subexpressions/substatements
4648 //===----------------------------------------------------------------------===//
4650 // UnaryExprOrTypeTraitExpr
4651 Stmt::child_range UnaryExprOrTypeTraitExpr::children() {
4652 const_child_range CCR =
4653 const_cast<const UnaryExprOrTypeTraitExpr *>(this)->children();
4654 return child_range(cast_away_const(CCR.begin()), cast_away_const(CCR.end()));
4657 Stmt::const_child_range UnaryExprOrTypeTraitExpr::children() const {
4658 // If this is of a type and the type is a VLA type (and not a typedef), the
4659 // size expression of the VLA needs to be treated as an executable expression.
4660 // Why isn't this weirdness documented better in StmtIterator?
4661 if (isArgumentType()) {
4662 if (const VariableArrayType *T =
4663 dyn_cast<VariableArrayType>(getArgumentType().getTypePtr()))
4664 return const_child_range(const_child_iterator(T), const_child_iterator());
4665 return const_child_range(const_child_iterator(), const_child_iterator());
4667 return const_child_range(&Argument.Ex, &Argument.Ex + 1);
4670 AtomicExpr::AtomicExpr(SourceLocation BLoc, ArrayRef<Expr *> args, QualType t,
4671 AtomicOp op, SourceLocation RP)
4672 : Expr(AtomicExprClass, t, VK_RValue, OK_Ordinary),
4673 NumSubExprs(args.size()), BuiltinLoc(BLoc), RParenLoc(RP), Op(op) {
4674 assert(args.size() == getNumSubExprs(op) && "wrong number of subexpressions");
4675 for (unsigned i = 0; i != args.size(); i++)
4676 SubExprs[i] = args[i];
4677 setDependence(computeDependence(this));
4680 unsigned AtomicExpr::getNumSubExprs(AtomicOp Op) {
4682 case AO__c11_atomic_init:
4683 case AO__opencl_atomic_init:
4684 case AO__c11_atomic_load:
4685 case AO__atomic_load_n:
4688 case AO__opencl_atomic_load:
4689 case AO__c11_atomic_store:
4690 case AO__c11_atomic_exchange:
4691 case AO__atomic_load:
4692 case AO__atomic_store:
4693 case AO__atomic_store_n:
4694 case AO__atomic_exchange_n:
4695 case AO__c11_atomic_fetch_add:
4696 case AO__c11_atomic_fetch_sub:
4697 case AO__c11_atomic_fetch_and:
4698 case AO__c11_atomic_fetch_or:
4699 case AO__c11_atomic_fetch_xor:
4700 case AO__c11_atomic_fetch_max:
4701 case AO__c11_atomic_fetch_min:
4702 case AO__atomic_fetch_add:
4703 case AO__atomic_fetch_sub:
4704 case AO__atomic_fetch_and:
4705 case AO__atomic_fetch_or:
4706 case AO__atomic_fetch_xor:
4707 case AO__atomic_fetch_nand:
4708 case AO__atomic_add_fetch:
4709 case AO__atomic_sub_fetch:
4710 case AO__atomic_and_fetch:
4711 case AO__atomic_or_fetch:
4712 case AO__atomic_xor_fetch:
4713 case AO__atomic_nand_fetch:
4714 case AO__atomic_min_fetch:
4715 case AO__atomic_max_fetch:
4716 case AO__atomic_fetch_min:
4717 case AO__atomic_fetch_max:
4720 case AO__opencl_atomic_store:
4721 case AO__opencl_atomic_exchange:
4722 case AO__opencl_atomic_fetch_add:
4723 case AO__opencl_atomic_fetch_sub:
4724 case AO__opencl_atomic_fetch_and:
4725 case AO__opencl_atomic_fetch_or:
4726 case AO__opencl_atomic_fetch_xor:
4727 case AO__opencl_atomic_fetch_min:
4728 case AO__opencl_atomic_fetch_max:
4729 case AO__atomic_exchange:
4732 case AO__c11_atomic_compare_exchange_strong:
4733 case AO__c11_atomic_compare_exchange_weak:
4736 case AO__opencl_atomic_compare_exchange_strong:
4737 case AO__opencl_atomic_compare_exchange_weak:
4738 case AO__atomic_compare_exchange:
4739 case AO__atomic_compare_exchange_n:
4742 llvm_unreachable("unknown atomic op");
4745 QualType AtomicExpr::getValueType() const {
4746 auto T = getPtr()->getType()->castAs<PointerType>()->getPointeeType();
4747 if (auto AT = T->getAs<AtomicType>())
4748 return AT->getValueType();
4752 QualType OMPArraySectionExpr::getBaseOriginalType(const Expr *Base) {
4753 unsigned ArraySectionCount = 0;
4754 while (auto *OASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParens())) {
4755 Base = OASE->getBase();
4756 ++ArraySectionCount;
4759 dyn_cast<ArraySubscriptExpr>(Base->IgnoreParenImpCasts())) {
4760 Base = ASE->getBase();
4761 ++ArraySectionCount;
4763 Base = Base->IgnoreParenImpCasts();
4764 auto OriginalTy = Base->getType();
4765 if (auto *DRE = dyn_cast<DeclRefExpr>(Base))
4766 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
4767 OriginalTy = PVD->getOriginalType().getNonReferenceType();
4769 for (unsigned Cnt = 0; Cnt < ArraySectionCount; ++Cnt) {
4770 if (OriginalTy->isAnyPointerType())
4771 OriginalTy = OriginalTy->getPointeeType();
4773 assert (OriginalTy->isArrayType());
4774 OriginalTy = OriginalTy->castAsArrayTypeUnsafe()->getElementType();
4780 RecoveryExpr::RecoveryExpr(ASTContext &Ctx, QualType T, SourceLocation BeginLoc,
4781 SourceLocation EndLoc, ArrayRef<Expr *> SubExprs)
4782 : Expr(RecoveryExprClass, T.getNonReferenceType(),
4783 T->isDependentType() ? VK_LValue : getValueKindForType(T),
4785 BeginLoc(BeginLoc), EndLoc(EndLoc), NumExprs(SubExprs.size()) {
4786 assert(!T.isNull());
4787 assert(llvm::all_of(SubExprs, [](Expr* E) { return E != nullptr; }));
4789 llvm::copy(SubExprs, getTrailingObjects<Expr *>());
4790 setDependence(computeDependence(this));
4793 RecoveryExpr *RecoveryExpr::Create(ASTContext &Ctx, QualType T,
4794 SourceLocation BeginLoc,
4795 SourceLocation EndLoc,
4796 ArrayRef<Expr *> SubExprs) {
4797 void *Mem = Ctx.Allocate(totalSizeToAlloc<Expr *>(SubExprs.size()),
4798 alignof(RecoveryExpr));
4799 return new (Mem) RecoveryExpr(Ctx, T, BeginLoc, EndLoc, SubExprs);
4802 RecoveryExpr *RecoveryExpr::CreateEmpty(ASTContext &Ctx, unsigned NumSubExprs) {
4803 void *Mem = Ctx.Allocate(totalSizeToAlloc<Expr *>(NumSubExprs),
4804 alignof(RecoveryExpr));
4805 return new (Mem) RecoveryExpr(EmptyShell(), NumSubExprs);
4808 void OMPArrayShapingExpr::setDimensions(ArrayRef<Expr *> Dims) {
4810 NumDims == Dims.size() &&
4811 "Preallocated number of dimensions is different from the provided one.");
4812 llvm::copy(Dims, getTrailingObjects<Expr *>());
4815 void OMPArrayShapingExpr::setBracketsRanges(ArrayRef<SourceRange> BR) {
4817 NumDims == BR.size() &&
4818 "Preallocated number of dimensions is different from the provided one.");
4819 llvm::copy(BR, getTrailingObjects<SourceRange>());
4822 OMPArrayShapingExpr::OMPArrayShapingExpr(QualType ExprTy, Expr *Op,
4823 SourceLocation L, SourceLocation R,
4824 ArrayRef<Expr *> Dims)
4825 : Expr(OMPArrayShapingExprClass, ExprTy, VK_LValue, OK_Ordinary), LPLoc(L),
4826 RPLoc(R), NumDims(Dims.size()) {
4828 setDimensions(Dims);
4829 setDependence(computeDependence(this));
4832 OMPArrayShapingExpr *
4833 OMPArrayShapingExpr::Create(const ASTContext &Context, QualType T, Expr *Op,
4834 SourceLocation L, SourceLocation R,
4835 ArrayRef<Expr *> Dims,
4836 ArrayRef<SourceRange> BracketRanges) {
4837 assert(Dims.size() == BracketRanges.size() &&
4838 "Different number of dimensions and brackets ranges.");
4839 void *Mem = Context.Allocate(
4840 totalSizeToAlloc<Expr *, SourceRange>(Dims.size() + 1, Dims.size()),
4841 alignof(OMPArrayShapingExpr));
4842 auto *E = new (Mem) OMPArrayShapingExpr(T, Op, L, R, Dims);
4843 E->setBracketsRanges(BracketRanges);
4847 OMPArrayShapingExpr *OMPArrayShapingExpr::CreateEmpty(const ASTContext &Context,
4849 void *Mem = Context.Allocate(
4850 totalSizeToAlloc<Expr *, SourceRange>(NumDims + 1, NumDims),
4851 alignof(OMPArrayShapingExpr));
4852 return new (Mem) OMPArrayShapingExpr(EmptyShell(), NumDims);
4855 void OMPIteratorExpr::setIteratorDeclaration(unsigned I, Decl *D) {
4856 assert(I < NumIterators &&
4857 "Idx is greater or equal the number of iterators definitions.");
4858 getTrailingObjects<Decl *>()[I] = D;
4861 void OMPIteratorExpr::setAssignmentLoc(unsigned I, SourceLocation Loc) {
4862 assert(I < NumIterators &&
4863 "Idx is greater or equal the number of iterators definitions.");
4865 SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
4866 static_cast<int>(RangeLocOffset::AssignLoc)] = Loc;
4869 void OMPIteratorExpr::setIteratorRange(unsigned I, Expr *Begin,
4870 SourceLocation ColonLoc, Expr *End,
4871 SourceLocation SecondColonLoc,
4873 assert(I < NumIterators &&
4874 "Idx is greater or equal the number of iterators definitions.");
4875 getTrailingObjects<Expr *>()[I * static_cast<int>(RangeExprOffset::Total) +
4876 static_cast<int>(RangeExprOffset::Begin)] =
4878 getTrailingObjects<Expr *>()[I * static_cast<int>(RangeExprOffset::Total) +
4879 static_cast<int>(RangeExprOffset::End)] = End;
4880 getTrailingObjects<Expr *>()[I * static_cast<int>(RangeExprOffset::Total) +
4881 static_cast<int>(RangeExprOffset::Step)] = Step;
4883 SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
4884 static_cast<int>(RangeLocOffset::FirstColonLoc)] =
4887 SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
4888 static_cast<int>(RangeLocOffset::SecondColonLoc)] =
4892 Decl *OMPIteratorExpr::getIteratorDecl(unsigned I) {
4893 return getTrailingObjects<Decl *>()[I];
4896 OMPIteratorExpr::IteratorRange OMPIteratorExpr::getIteratorRange(unsigned I) {
4899 getTrailingObjects<Expr *>()[I * static_cast<int>(
4900 RangeExprOffset::Total) +
4901 static_cast<int>(RangeExprOffset::Begin)];
4903 getTrailingObjects<Expr *>()[I * static_cast<int>(
4904 RangeExprOffset::Total) +
4905 static_cast<int>(RangeExprOffset::End)];
4907 getTrailingObjects<Expr *>()[I * static_cast<int>(
4908 RangeExprOffset::Total) +
4909 static_cast<int>(RangeExprOffset::Step)];
4913 SourceLocation OMPIteratorExpr::getAssignLoc(unsigned I) const {
4914 return getTrailingObjects<
4915 SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
4916 static_cast<int>(RangeLocOffset::AssignLoc)];
4919 SourceLocation OMPIteratorExpr::getColonLoc(unsigned I) const {
4920 return getTrailingObjects<
4921 SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
4922 static_cast<int>(RangeLocOffset::FirstColonLoc)];
4925 SourceLocation OMPIteratorExpr::getSecondColonLoc(unsigned I) const {
4926 return getTrailingObjects<
4927 SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
4928 static_cast<int>(RangeLocOffset::SecondColonLoc)];
4931 void OMPIteratorExpr::setHelper(unsigned I, const OMPIteratorHelperData &D) {
4932 getTrailingObjects<OMPIteratorHelperData>()[I] = D;
4935 OMPIteratorHelperData &OMPIteratorExpr::getHelper(unsigned I) {
4936 return getTrailingObjects<OMPIteratorHelperData>()[I];
4939 const OMPIteratorHelperData &OMPIteratorExpr::getHelper(unsigned I) const {
4940 return getTrailingObjects<OMPIteratorHelperData>()[I];
4943 OMPIteratorExpr::OMPIteratorExpr(
4944 QualType ExprTy, SourceLocation IteratorKwLoc, SourceLocation L,
4945 SourceLocation R, ArrayRef<OMPIteratorExpr::IteratorDefinition> Data,
4946 ArrayRef<OMPIteratorHelperData> Helpers)
4947 : Expr(OMPIteratorExprClass, ExprTy, VK_LValue, OK_Ordinary),
4948 IteratorKwLoc(IteratorKwLoc), LPLoc(L), RPLoc(R),
4949 NumIterators(Data.size()) {
4950 for (unsigned I = 0, E = Data.size(); I < E; ++I) {
4951 const IteratorDefinition &D = Data[I];
4952 setIteratorDeclaration(I, D.IteratorDecl);
4953 setAssignmentLoc(I, D.AssignmentLoc);
4954 setIteratorRange(I, D.Range.Begin, D.ColonLoc, D.Range.End,
4955 D.SecondColonLoc, D.Range.Step);
4956 setHelper(I, Helpers[I]);
4958 setDependence(computeDependence(this));
4962 OMPIteratorExpr::Create(const ASTContext &Context, QualType T,
4963 SourceLocation IteratorKwLoc, SourceLocation L,
4965 ArrayRef<OMPIteratorExpr::IteratorDefinition> Data,
4966 ArrayRef<OMPIteratorHelperData> Helpers) {
4967 assert(Data.size() == Helpers.size() &&
4968 "Data and helpers must have the same size.");
4969 void *Mem = Context.Allocate(
4970 totalSizeToAlloc<Decl *, Expr *, SourceLocation, OMPIteratorHelperData>(
4971 Data.size(), Data.size() * static_cast<int>(RangeExprOffset::Total),
4972 Data.size() * static_cast<int>(RangeLocOffset::Total),
4974 alignof(OMPIteratorExpr));
4975 return new (Mem) OMPIteratorExpr(T, IteratorKwLoc, L, R, Data, Helpers);
4978 OMPIteratorExpr *OMPIteratorExpr::CreateEmpty(const ASTContext &Context,
4979 unsigned NumIterators) {
4980 void *Mem = Context.Allocate(
4981 totalSizeToAlloc<Decl *, Expr *, SourceLocation, OMPIteratorHelperData>(
4982 NumIterators, NumIterators * static_cast<int>(RangeExprOffset::Total),
4983 NumIterators * static_cast<int>(RangeLocOffset::Total), NumIterators),
4984 alignof(OMPIteratorExpr));
4985 return new (Mem) OMPIteratorExpr(EmptyShell(), NumIterators);