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