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