Coverage Report

Created: 2022-05-17 06:19

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Sema/SemaExpr.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
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 semantic analysis for expressions.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "TreeTransform.h"
14
#include "UsedDeclVisitor.h"
15
#include "clang/AST/ASTConsumer.h"
16
#include "clang/AST/ASTContext.h"
17
#include "clang/AST/ASTLambda.h"
18
#include "clang/AST/ASTMutationListener.h"
19
#include "clang/AST/CXXInheritance.h"
20
#include "clang/AST/DeclObjC.h"
21
#include "clang/AST/DeclTemplate.h"
22
#include "clang/AST/EvaluatedExprVisitor.h"
23
#include "clang/AST/Expr.h"
24
#include "clang/AST/ExprCXX.h"
25
#include "clang/AST/ExprObjC.h"
26
#include "clang/AST/ExprOpenMP.h"
27
#include "clang/AST/OperationKinds.h"
28
#include "clang/AST/ParentMapContext.h"
29
#include "clang/AST/RecursiveASTVisitor.h"
30
#include "clang/AST/Type.h"
31
#include "clang/AST/TypeLoc.h"
32
#include "clang/Basic/Builtins.h"
33
#include "clang/Basic/DiagnosticSema.h"
34
#include "clang/Basic/PartialDiagnostic.h"
35
#include "clang/Basic/SourceManager.h"
36
#include "clang/Basic/Specifiers.h"
37
#include "clang/Basic/TargetInfo.h"
38
#include "clang/Lex/LiteralSupport.h"
39
#include "clang/Lex/Preprocessor.h"
40
#include "clang/Sema/AnalysisBasedWarnings.h"
41
#include "clang/Sema/DeclSpec.h"
42
#include "clang/Sema/DelayedDiagnostic.h"
43
#include "clang/Sema/Designator.h"
44
#include "clang/Sema/Initialization.h"
45
#include "clang/Sema/Lookup.h"
46
#include "clang/Sema/Overload.h"
47
#include "clang/Sema/ParsedTemplate.h"
48
#include "clang/Sema/Scope.h"
49
#include "clang/Sema/ScopeInfo.h"
50
#include "clang/Sema/SemaFixItUtils.h"
51
#include "clang/Sema/SemaInternal.h"
52
#include "clang/Sema/Template.h"
53
#include "llvm/ADT/STLExtras.h"
54
#include "llvm/ADT/StringExtras.h"
55
#include "llvm/Support/Casting.h"
56
#include "llvm/Support/ConvertUTF.h"
57
#include "llvm/Support/SaveAndRestore.h"
58
#include "llvm/Support/TypeSize.h"
59
60
using namespace clang;
61
using namespace sema;
62
63
/// Determine whether the use of this declaration is valid, without
64
/// emitting diagnostics.
65
36.9k
bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
66
  // See if this is an auto-typed variable whose initializer we are parsing.
67
36.9k
  if (ParsingInitForAutoVars.count(D))
68
0
    return false;
69
70
  // See if this is a deleted function.
71
36.9k
  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
72
8
    if (FD->isDeleted())
73
1
      return false;
74
75
    // If the function has a deduced return type, and we can't deduce it,
76
    // then we can't use it either.
77
7
    if (getLangOpts().CPlusPlus14 && 
FD->getReturnType()->isUndeducedType()0
&&
78
7
        
DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)0
)
79
0
      return false;
80
81
    // See if this is an aligned allocation/deallocation function that is
82
    // unavailable.
83
7
    if (TreatUnavailableAsInvalid &&
84
7
        
isUnavailableAlignedAllocationFunction(*FD)0
)
85
0
      return false;
86
7
  }
87
88
  // See if this function is unavailable.
89
36.9k
  if (TreatUnavailableAsInvalid && 
D->getAvailability() == AR_Unavailable18.7k
&&
90
36.9k
      
cast<Decl>(CurContext)->getAvailability() != AR_Unavailable0
)
91
0
    return false;
92
93
36.9k
  if (isa<UnresolvedUsingIfExistsDecl>(D))
94
0
    return false;
95
96
36.9k
  return true;
97
36.9k
}
98
99
119M
static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
100
  // Warn if this is used but marked unused.
101
119M
  if (const auto *A = D->getAttr<UnusedAttr>()) {
102
    // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
103
    // should diagnose them.
104
110k
    if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
105
110k
        
A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused110k
) {
106
110k
      const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
107
110k
      if (DC && !DC->hasAttr<UnusedAttr>())
108
110k
        S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
109
110k
    }
110
110k
  }
111
119M
}
112
113
/// Emit a note explaining that this function is deleted.
114
1.16k
void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
115
1.16k
  assert(Decl && Decl->isDeleted());
116
117
1.16k
  if (Decl->isDefaulted()) {
118
    // If the method was explicitly defaulted, point at that declaration.
119
610
    if (!Decl->isImplicit())
120
50
      Diag(Decl->getLocation(), diag::note_implicitly_deleted);
121
122
    // Try to diagnose why this special member function was implicitly
123
    // deleted. This might fail, if that reason no longer applies.
124
610
    DiagnoseDeletedDefaultedFunction(Decl);
125
610
    return;
126
610
  }
127
128
559
  auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
129
559
  if (Ctor && 
Ctor->isInheritingConstructor()342
)
130
8
    return NoteDeletedInheritingConstructor(Ctor);
131
132
551
  Diag(Decl->getLocation(), diag::note_availability_specified_here)
133
551
    << Decl << 1;
134
551
}
135
136
/// Determine whether a FunctionDecl was ever declared with an
137
/// explicit storage class.
138
35
static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
139
35
  for (auto I : D->redecls()) {
140
35
    if (I->getStorageClass() != SC_None)
141
5
      return true;
142
35
  }
143
30
  return false;
144
35
}
145
146
/// Check whether we're in an extern inline function and referring to a
147
/// variable or function with internal linkage (C11 6.7.4p3).
148
///
149
/// This is only a warning because we used to silently accept this code, but
150
/// in many cases it will not behave correctly. This is not enabled in C++ mode
151
/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
152
/// and so while there may still be user mistakes, most of the time we can't
153
/// prove that there are errors.
154
static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
155
                                                      const NamedDecl *D,
156
119M
                                                      SourceLocation Loc) {
157
  // This is disabled under C++; there are too many ways for this to fire in
158
  // contexts where the warning is a false positive, or where it is technically
159
  // correct but benign.
160
119M
  if (S.getLangOpts().CPlusPlus)
161
53.4M
    return;
162
163
  // Check if this is an inlined function or method.
164
65.9M
  FunctionDecl *Current = S.getCurFunctionDecl();
165
65.9M
  if (!Current)
166
53.8M
    return;
167
12.0M
  if (!Current->isInlined())
168
635k
    return;
169
11.4M
  if (!Current->isExternallyVisible())
170
11.3M
    return;
171
172
  // Check if the decl has internal linkage.
173
56.4k
  if (D->getFormalLinkage() != InternalLinkage)
174
56.3k
    return;
175
176
  // Downgrade from ExtWarn to Extension if
177
  //  (1) the supposedly external inline function is in the main file,
178
  //      and probably won't be included anywhere else.
179
  //  (2) the thing we're referencing is a pure function.
180
  //  (3) the thing we're referencing is another inline function.
181
  // This last can give us false negatives, but it's better than warning on
182
  // wrappers for simple C library functions.
183
21
  const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
184
21
  bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
185
21
  if (!DowngradeWarning && 
UsedFn10
)
186
6
    DowngradeWarning = UsedFn->isInlined() || 
UsedFn->hasAttr<ConstAttr>()4
;
187
188
21
  S.Diag(Loc, DowngradeWarning ? 
diag::ext_internal_in_extern_inline_quiet14
189
21
                               : 
diag::ext_internal_in_extern_inline7
)
190
21
    << /*IsVar=*/!UsedFn << D;
191
192
21
  S.MaybeSuggestAddingStaticToDecl(Current);
193
194
21
  S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
195
21
      << D;
196
21
}
197
198
35
void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
199
35
  const FunctionDecl *First = Cur->getFirstDecl();
200
201
  // Suggest "static" on the function, if possible.
202
35
  if (!hasAnyExplicitStorageClass(First)) {
203
30
    SourceLocation DeclBegin = First->getSourceRange().getBegin();
204
30
    Diag(DeclBegin, diag::note_convert_inline_to_static)
205
30
      << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
206
30
  }
207
35
}
208
209
/// Determine whether the use of this declaration is valid, and
210
/// emit any corresponding diagnostics.
211
///
212
/// This routine diagnoses various problems with referencing
213
/// declarations that can occur when using a declaration. For example,
214
/// it might warn if a deprecated or unavailable declaration is being
215
/// used, or produce an error (and return true) if a C++0x deleted
216
/// function is being used.
217
///
218
/// \returns true if there was an error (this declaration cannot be
219
/// referenced), false otherwise.
220
///
221
bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
222
                             const ObjCInterfaceDecl *UnknownObjCClass,
223
                             bool ObjCPropertyAccess,
224
                             bool AvoidPartialAvailabilityChecks,
225
119M
                             ObjCInterfaceDecl *ClassReceiver) {
226
119M
  SourceLocation Loc = Locs.front();
227
119M
  if (getLangOpts().CPlusPlus && 
isa<FunctionDecl>(D)53.4M
) {
228
    // If there were any diagnostics suppressed by template argument deduction,
229
    // emit them now.
230
2.37M
    auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
231
2.37M
    if (Pos != SuppressedDiagnostics.end()) {
232
3.56k
      for (const PartialDiagnosticAt &Suppressed : Pos->second)
233
3.46k
        Diag(Suppressed.first, Suppressed.second);
234
235
      // Clear out the list of suppressed diagnostics, so that we don't emit
236
      // them again for this specialization. However, we don't obsolete this
237
      // entry from the table, because we want to avoid ever emitting these
238
      // diagnostics again.
239
3.56k
      Pos->second.clear();
240
3.56k
    }
241
242
    // C++ [basic.start.main]p3:
243
    //   The function 'main' shall not be used within a program.
244
2.37M
    if (cast<FunctionDecl>(D)->isMain())
245
104
      Diag(Loc, diag::ext_main_used);
246
247
2.37M
    diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
248
2.37M
  }
249
250
  // See if this is an auto-typed variable whose initializer we are parsing.
251
119M
  if (ParsingInitForAutoVars.count(D)) {
252
27
    if (isa<BindingDecl>(D)) {
253
1
      Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
254
1
        << D->getDeclName();
255
26
    } else {
256
26
      Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
257
26
        << D->getDeclName() << cast<VarDecl>(D)->getType();
258
26
    }
259
27
    return true;
260
27
  }
261
262
119M
  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
263
    // See if this is a deleted function.
264
4.65M
    if (FD->isDeleted()) {
265
169
      auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
266
169
      if (Ctor && 
Ctor->isInheritingConstructor()10
)
267
8
        Diag(Loc, diag::err_deleted_inherited_ctor_use)
268
8
            << Ctor->getParent()
269
8
            << Ctor->getInheritedConstructor().getConstructor()->getParent();
270
161
      else
271
161
        Diag(Loc, diag::err_deleted_function_use);
272
169
      NoteDeletedFunction(FD);
273
169
      return true;
274
169
    }
275
276
    // [expr.prim.id]p4
277
    //   A program that refers explicitly or implicitly to a function with a
278
    //   trailing requires-clause whose constraint-expression is not satisfied,
279
    //   other than to declare it, is ill-formed. [...]
280
    //
281
    // See if this is a function with constraints that need to be satisfied.
282
    // Check this before deducing the return type, as it might instantiate the
283
    // definition.
284
4.65M
    if (FD->getTrailingRequiresClause()) {
285
69
      ConstraintSatisfaction Satisfaction;
286
69
      if (CheckFunctionConstraints(FD, Satisfaction, Loc))
287
        // A diagnostic will have already been generated (non-constant
288
        // constraint expression, for example)
289
1
        return true;
290
68
      if (!Satisfaction.IsSatisfied) {
291
18
        Diag(Loc,
292
18
             diag::err_reference_to_function_with_unsatisfied_constraints)
293
18
            << D;
294
18
        DiagnoseUnsatisfiedConstraint(Satisfaction);
295
18
        return true;
296
18
      }
297
68
    }
298
299
    // If the function has a deduced return type, and we can't deduce it,
300
    // then we can't use it either.
301
4.65M
    if (getLangOpts().CPlusPlus14 && 
FD->getReturnType()->isUndeducedType()595k
&&
302
4.65M
        
DeduceReturnType(FD, Loc)2.35k
)
303
57
      return true;
304
305
4.65M
    if (getLangOpts().CUDA && 
!CheckCUDACall(Loc, FD)4.69k
)
306
34
      return true;
307
308
4.65M
    if (getLangOpts().SYCLIsDevice && 
!checkSYCLDeviceFunction(Loc, FD)504
)
309
0
      return true;
310
4.65M
  }
311
312
119M
  if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
313
    // Lambdas are only default-constructible or assignable in C++2a onwards.
314
1.30M
    if (MD->getParent()->isLambda() &&
315
1.30M
        
(20.7k
(20.7k
isa<CXXConstructorDecl>(MD)20.7k
&&
316
20.7k
          
cast<CXXConstructorDecl>(MD)->isDefaultConstructor()4.44k
) ||
317
20.7k
         
MD->isCopyAssignmentOperator()20.5k
||
MD->isMoveAssignmentOperator()20.5k
)) {
318
142
      Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
319
142
        << !isa<CXXConstructorDecl>(MD);
320
142
    }
321
1.30M
  }
322
323
119M
  auto getReferencedObjCProp = [](const NamedDecl *D) ->
324
119M
                                      const ObjCPropertyDecl * {
325
119M
    if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
326
22.9k
      return MD->findPropertyDecl();
327
119M
    return nullptr;
328
119M
  };
329
119M
  if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
330
1.92k
    if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
331
0
      return true;
332
119M
  } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
333
21
      return true;
334
21
  }
335
336
  // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
337
  // Only the variables omp_in and omp_out are allowed in the combiner.
338
  // Only the variables omp_priv and omp_orig are allowed in the
339
  // initializer-clause.
340
119M
  auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
341
119M
  if (LangOpts.OpenMP && 
DRD1.77M
&&
!CurContext->containsDecl(D)1.94k
&&
342
119M
      
isa<VarDecl>(D)349
) {
343
54
    Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
344
54
        << getCurFunction()->HasOMPDeclareReductionCombiner;
345
54
    Diag(D->getLocation(), diag::note_entity_declared_at) << D;
346
54
    return true;
347
54
  }
348
349
  // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
350
  //  List-items in map clauses on this construct may only refer to the declared
351
  //  variable var and entities that could be referenced by a procedure defined
352
  //  at the same location
353
119M
  if (LangOpts.OpenMP && 
isa<VarDecl>(D)1.77M
&&
354
119M
      
!isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))1.35M
) {
355
8
    Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
356
8
        << getOpenMPDeclareMapperVarName();
357
8
    Diag(D->getLocation(), diag::note_entity_declared_at) << D;
358
8
    return true;
359
8
  }
360
361
119M
  if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) {
362
689
    Diag(Loc, diag::err_use_of_empty_using_if_exists);
363
689
    Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here);
364
689
    return true;
365
689
  }
366
367
119M
  DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
368
119M
                             AvoidPartialAvailabilityChecks, ClassReceiver);
369
370
119M
  DiagnoseUnusedOfDecl(*this, D, Loc);
371
372
119M
  diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
373
374
119M
  if (auto *VD = dyn_cast<ValueDecl>(D))
375
18.9M
    checkTypeSupport(VD->getType(), Loc, VD);
376
377
119M
  if (LangOpts.SYCLIsDevice || 
(119M
LangOpts.OpenMP119M
&&
LangOpts.OpenMPIsDevice1.77M
)) {
378
71.5k
    if (!Context.getTargetInfo().isTLSSupported())
379
23.7k
      if (const auto *VD = dyn_cast<VarDecl>(D))
380
16.0k
        if (VD->getTLSKind() != VarDecl::TLS_None)
381
8
          targetDiag(*Locs.begin(), diag::err_thread_unsupported);
382
71.5k
  }
383
384
119M
  if (isa<ParmVarDecl>(D) && 
isa<RequiresExprBodyDecl>(D->getDeclContext())7.92M
&&
385
119M
      
!isUnevaluatedContext()202
) {
386
    // C++ [expr.prim.req.nested] p3
387
    //   A local parameter shall only appear as an unevaluated operand
388
    //   (Clause 8) within the constraint-expression.
389
2
    Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
390
2
        << D;
391
2
    Diag(D->getLocation(), diag::note_entity_declared_at) << D;
392
2
    return true;
393
2
  }
394
395
119M
  return false;
396
119M
}
397
398
/// DiagnoseSentinelCalls - This routine checks whether a call or
399
/// message-send is to a declaration with the sentinel attribute, and
400
/// if so, it checks that the requirements of the sentinel are
401
/// satisfied.
402
void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
403
3.87M
                                 ArrayRef<Expr *> Args) {
404
3.87M
  const SentinelAttr *attr = D->getAttr<SentinelAttr>();
405
3.87M
  if (!attr)
406
3.87M
    return;
407
408
  // The number of formal parameters of the declaration.
409
272
  unsigned numFormalParams;
410
411
  // The kind of declaration.  This is also an index into a %select in
412
  // the diagnostic.
413
272
  enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
414
415
272
  if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
416
233
    numFormalParams = MD->param_size();
417
233
    calleeType = CT_Method;
418
233
  } else 
if (FunctionDecl *39
FD39
= dyn_cast<FunctionDecl>(D)) {
419
27
    numFormalParams = FD->param_size();
420
27
    calleeType = CT_Function;
421
27
  } else 
if (12
isa<VarDecl>(D)12
) {
422
12
    QualType type = cast<ValueDecl>(D)->getType();
423
12
    const FunctionType *fn = nullptr;
424
12
    if (const PointerType *ptr = type->getAs<PointerType>()) {
425
6
      fn = ptr->getPointeeType()->getAs<FunctionType>();
426
6
      if (!fn) 
return0
;
427
6
      calleeType = CT_Function;
428
6
    } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
429
6
      fn = ptr->getPointeeType()->castAs<FunctionType>();
430
6
      calleeType = CT_Block;
431
6
    } else {
432
0
      return;
433
0
    }
434
435
12
    if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
436
12
      numFormalParams = proto->getNumParams();
437
12
    } else {
438
0
      numFormalParams = 0;
439
0
    }
440
12
  } else {
441
0
    return;
442
0
  }
443
444
  // "nullPos" is the number of formal parameters at the end which
445
  // effectively count as part of the variadic arguments.  This is
446
  // useful if you would prefer to not have *any* formal parameters,
447
  // but the language forces you to have at least one.
448
272
  unsigned nullPos = attr->getNullPos();
449
272
  assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
450
272
  numFormalParams = (nullPos > numFormalParams ? 
00
: numFormalParams - nullPos);
451
452
  // The number of arguments which should follow the sentinel.
453
272
  unsigned numArgsAfterSentinel = attr->getSentinel();
454
455
  // If there aren't enough arguments for all the formal parameters,
456
  // the sentinel, and the args after the sentinel, complain.
457
272
  if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
458
4
    Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
459
4
    Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
460
4
    return;
461
4
  }
462
463
  // Otherwise, find the sentinel expression.
464
268
  Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
465
268
  if (!sentinelExpr) 
return0
;
466
268
  if (sentinelExpr->isValueDependent()) 
return0
;
467
268
  if (Context.isSentinelNullExpr(sentinelExpr)) 
return243
;
468
469
  // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
470
  // or 'NULL' if those are actually defined in the context.  Only use
471
  // 'nil' for ObjC methods, where it's much more likely that the
472
  // variadic arguments form a list of object pointers.
473
25
  SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
474
25
  std::string NullValue;
475
25
  if (calleeType == CT_Method && 
PP.isMacroDefined("nil")5
)
476
2
    NullValue = "nil";
477
23
  else if (getLangOpts().CPlusPlus11)
478
5
    NullValue = "nullptr";
479
18
  else if (PP.isMacroDefined("NULL"))
480
13
    NullValue = "NULL";
481
5
  else
482
5
    NullValue = "(void*) 0";
483
484
25
  if (MissingNilLoc.isInvalid())
485
1
    Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
486
24
  else
487
24
    Diag(MissingNilLoc, diag::warn_missing_sentinel)
488
24
      << int(calleeType)
489
24
      << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
490
25
  Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
491
25
}
492
493
96
SourceRange Sema::getExprRange(Expr *E) const {
494
96
  return E ? E->getSourceRange() : 
SourceRange()0
;
495
96
}
496
497
//===----------------------------------------------------------------------===//
498
//  Standard Promotions and Conversions
499
//===----------------------------------------------------------------------===//
500
501
/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
502
26.0M
ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
503
  // Handle any placeholder expressions which made it here.
504
26.0M
  if (E->hasPlaceholderType()) {
505
27
    ExprResult result = CheckPlaceholderExpr(E);
506
27
    if (result.isInvalid()) 
return ExprError()4
;
507
23
    E = result.get();
508
23
  }
509
510
26.0M
  QualType Ty = E->getType();
511
26.0M
  assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
512
513
26.0M
  if (Ty->isFunctionType()) {
514
2.52k
    if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
515
2.50k
      if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
516
2.50k
        if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
517
11
          return ExprError();
518
519
2.51k
    E = ImpCastExprToType(E, Context.getPointerType(Ty),
520
2.51k
                          CK_FunctionToPointerDecay).get();
521
26.0M
  } else if (Ty->isArrayType()) {
522
    // In C90 mode, arrays only promote to pointers if the array expression is
523
    // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
524
    // type 'array of type' is converted to an expression that has type 'pointer
525
    // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
526
    // that has type 'array of type' ...".  The relevant change is "an lvalue"
527
    // (C90) to "an expression" (C99).
528
    //
529
    // C++ 4.2p1:
530
    // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
531
    // T" can be converted to an rvalue of type "pointer to T".
532
    //
533
135k
    if (getLangOpts().C99 || 
getLangOpts().CPlusPlus77.9k
||
E->isLValue()1.25k
) {
534
135k
      ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
535
135k
                                         CK_ArrayToPointerDecay);
536
135k
      if (Res.isInvalid())
537
9
        return ExprError();
538
135k
      E = Res.get();
539
135k
    }
540
135k
  }
541
26.0M
  return E;
542
26.0M
}
543
544
12.9M
static void CheckForNullPointerDereference(Sema &S, Expr *E) {
545
  // Check to see if we are dereferencing a null pointer.  If so,
546
  // and if not volatile-qualified, this is undefined behavior that the
547
  // optimizer will delete, so warn about it.  People sometimes try to use this
548
  // to get a deterministic trap and are surprised by clang's behavior.  This
549
  // only handles the pattern "*null", which is a very syntactic check.
550
12.9M
  const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
551
12.9M
  if (UO && 
UO->getOpcode() == UO_Deref104k
&&
552
12.9M
      
UO->getSubExpr()->getType()->isPointerType()94.4k
) {
553
94.4k
    const LangAS AS =
554
94.4k
        UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
555
94.4k
    if ((!isTargetAddressSpace(AS) ||
556
94.4k
         
(15
isTargetAddressSpace(AS)15
&&
toTargetAddressSpace(AS) == 015
)) &&
557
94.4k
        UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
558
94.4k
            S.Context, Expr::NPC_ValueDependentIsNotNull) &&
559
94.4k
        
!UO->getType().isVolatileQualified()1.11k
) {
560
36
      S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
561
36
                            S.PDiag(diag::warn_indirection_through_null)
562
36
                                << UO->getSubExpr()->getSourceRange());
563
36
      S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
564
36
                            S.PDiag(diag::note_indirection_through_null));
565
36
    }
566
94.4k
  }
567
12.9M
}
568
569
static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
570
                                    SourceLocation AssignLoc,
571
3.04k
                                    const Expr* RHS) {
572
3.04k
  const ObjCIvarDecl *IV = OIRE->getDecl();
573
3.04k
  if (!IV)
574
0
    return;
575
576
3.04k
  DeclarationName MemberName = IV->getDeclName();
577
3.04k
  IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
578
3.04k
  if (!Member || !Member->isStr("isa"))
579
3.02k
    return;
580
581
19
  const Expr *Base = OIRE->getBase();
582
19
  QualType BaseType = Base->getType();
583
19
  if (OIRE->isArrow())
584
18
    BaseType = BaseType->getPointeeType();
585
19
  if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
586
19
    if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
587
19
      ObjCInterfaceDecl *ClassDeclared = nullptr;
588
19
      ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
589
19
      if (!ClassDeclared->getSuperClass()
590
19
          && 
(*ClassDeclared->ivar_begin()) == IV16
) {
591
11
        if (RHS) {
592
4
          NamedDecl *ObjectSetClass =
593
4
            S.LookupSingleName(S.TUScope,
594
4
                               &S.Context.Idents.get("object_setClass"),
595
4
                               SourceLocation(), S.LookupOrdinaryName);
596
4
          if (ObjectSetClass) {
597
3
            SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
598
3
            S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
599
3
                << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
600
3
                                              "object_setClass(")
601
3
                << FixItHint::CreateReplacement(
602
3
                       SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
603
3
                << FixItHint::CreateInsertion(RHSLocEnd, ")");
604
3
          }
605
1
          else
606
1
            S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
607
7
        } else {
608
7
          NamedDecl *ObjectGetClass =
609
7
            S.LookupSingleName(S.TUScope,
610
7
                               &S.Context.Idents.get("object_getClass"),
611
7
                               SourceLocation(), S.LookupOrdinaryName);
612
7
          if (ObjectGetClass)
613
4
            S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
614
4
                << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
615
4
                                              "object_getClass(")
616
4
                << FixItHint::CreateReplacement(
617
4
                       SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
618
3
          else
619
3
            S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
620
7
        }
621
11
        S.Diag(IV->getLocation(), diag::note_ivar_decl);
622
11
      }
623
19
    }
624
19
}
625
626
38.4M
ExprResult Sema::DefaultLvalueConversion(Expr *E) {
627
  // Handle any placeholder expressions which made it here.
628
38.4M
  if (E->hasPlaceholderType()) {
629
63
    ExprResult result = CheckPlaceholderExpr(E);
630
63
    if (result.isInvalid()) 
return ExprError()20
;
631
43
    E = result.get();
632
43
  }
633
634
  // C++ [conv.lval]p1:
635
  //   A glvalue of a non-function, non-array type T can be
636
  //   converted to a prvalue.
637
38.4M
  if (!E->isGLValue()) 
return E27.2M
;
638
639
11.1M
  QualType T = E->getType();
640
11.1M
  assert(!T.isNull() && "r-value conversion on typeless expression?");
641
642
  // lvalue-to-rvalue conversion cannot be applied to function or array types.
643
11.1M
  if (T->isFunctionType() || 
T->isArrayType()11.1M
)
644
39
    return E;
645
646
  // We don't want to throw lvalue-to-rvalue casts on top of
647
  // expressions of certain types in C++.
648
11.1M
  if (getLangOpts().CPlusPlus &&
649
11.1M
      
(5.61M
E->getType() == Context.OverloadTy5.61M
||
650
5.61M
       T->isDependentType() ||
651
5.61M
       
T->isRecordType()5.61M
))
652
33.1k
    return E;
653
654
  // The C standard is actually really unclear on this point, and
655
  // DR106 tells us what the result should be but not why.  It's
656
  // generally best to say that void types just doesn't undergo
657
  // lvalue-to-rvalue at all.  Note that expressions of unqualified
658
  // 'void' type are never l-values, but qualified void can be.
659
11.1M
  if (T->isVoidType())
660
11
    return E;
661
662
  // OpenCL usually rejects direct accesses to values of 'half' type.
663
11.1M
  if (getLangOpts().OpenCL &&
664
11.1M
      
!getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts())674k
&&
665
11.1M
      
T->isHalfType()5.61k
) {
666
5
    Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
667
5
      << 0 << T;
668
5
    return ExprError();
669
5
  }
670
671
11.1M
  CheckForNullPointerDereference(*this, E);
672
11.1M
  if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
673
45
    NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
674
45
                                     &Context.Idents.get("object_getClass"),
675
45
                                     SourceLocation(), LookupOrdinaryName);
676
45
    if (ObjectGetClass)
677
6
      Diag(E->getExprLoc(), diag::warn_objc_isa_use)
678
6
          << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
679
6
          << FixItHint::CreateReplacement(
680
6
                 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
681
39
    else
682
39
      Diag(E->getExprLoc(), diag::warn_objc_isa_use);
683
45
  }
684
11.1M
  else if (const ObjCIvarRefExpr *OIRE =
685
11.1M
            dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
686
1.61k
    DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
687
688
  // C++ [conv.lval]p1:
689
  //   [...] If T is a non-class type, the type of the prvalue is the
690
  //   cv-unqualified version of T. Otherwise, the type of the
691
  //   rvalue is T.
692
  //
693
  // C99 6.3.2.1p2:
694
  //   If the lvalue has qualified type, the value has the unqualified
695
  //   version of the type of the lvalue; otherwise, the value has the
696
  //   type of the lvalue.
697
11.1M
  if (T.hasQualifiers())
698
1.92M
    T = T.getUnqualifiedType();
699
700
  // Under the MS ABI, lock down the inheritance model now.
701
11.1M
  if (T->isMemberPointerType() &&
702
11.1M
      
Context.getTargetInfo().getCXXABI().isMicrosoft()1.13k
)
703
119
    (void)isCompleteType(E->getExprLoc(), T);
704
705
11.1M
  ExprResult Res = CheckLValueToRValueConversionOperand(E);
706
11.1M
  if (Res.isInvalid())
707
0
    return Res;
708
11.1M
  E = Res.get();
709
710
  // Loading a __weak object implicitly retains the value, so we need a cleanup to
711
  // balance that.
712
11.1M
  if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
713
292
    Cleanup.setExprNeedsCleanups(true);
714
715
11.1M
  if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
716
126
    Cleanup.setExprNeedsCleanups(true);
717
718
  // C++ [conv.lval]p3:
719
  //   If T is cv std::nullptr_t, the result is a null pointer constant.
720
11.1M
  CastKind CK = T->isNullPtrType() ? 
CK_NullToPointer398
:
CK_LValueToRValue11.1M
;
721
11.1M
  Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue,
722
11.1M
                                 CurFPFeatureOverrides());
723
724
  // C11 6.3.2.1p2:
725
  //   ... if the lvalue has atomic type, the value has the non-atomic version
726
  //   of the type of the lvalue ...
727
11.1M
  if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
728
212
    T = Atomic->getValueType().getUnqualifiedType();
729
212
    Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
730
212
                                   nullptr, VK_PRValue, FPOptionsOverride());
731
212
  }
732
733
11.1M
  return Res;
734
11.1M
}
735
736
25.9M
ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
737
25.9M
  ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
738
25.9M
  if (Res.isInvalid())
739
24
    return ExprError();
740
25.9M
  Res = DefaultLvalueConversion(Res.get());
741
25.9M
  if (Res.isInvalid())
742
4
    return ExprError();
743
25.9M
  return Res;
744
25.9M
}
745
746
/// CallExprUnaryConversions - a special case of an unary conversion
747
/// performed on a function designator of a call expression.
748
1.69M
ExprResult Sema::CallExprUnaryConversions(Expr *E) {
749
1.69M
  QualType Ty = E->getType();
750
1.69M
  ExprResult Res = E;
751
  // Only do implicit cast for a function type, but not for a pointer
752
  // to function type.
753
1.69M
  if (Ty->isFunctionType()) {
754
1.68M
    Res = ImpCastExprToType(E, Context.getPointerType(Ty),
755
1.68M
                            CK_FunctionToPointerDecay);
756
1.68M
    if (Res.isInvalid())
757
0
      return ExprError();
758
1.68M
  }
759
1.69M
  Res = DefaultLvalueConversion(Res.get());
760
1.69M
  if (Res.isInvalid())
761
16
    return ExprError();
762
1.69M
  return Res.get();
763
1.69M
}
764
765
/// UsualUnaryConversions - Performs various conversions that are common to most
766
/// operators (C99 6.3). The conversions of array and function types are
767
/// sometimes suppressed. For example, the array->pointer conversion doesn't
768
/// apply if the array is an argument to the sizeof or address (&) operators.
769
/// In these instances, this routine should *not* be called.
770
9.49M
ExprResult Sema::UsualUnaryConversions(Expr *E) {
771
  // First, convert to an r-value.
772
9.49M
  ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
773
9.49M
  if (Res.isInvalid())
774
4
    return ExprError();
775
9.49M
  E = Res.get();
776
777
9.49M
  QualType Ty = E->getType();
778
9.49M
  assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
779
780
0
  LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
781
9.49M
  if (EvalMethod != LangOptions::FEM_Source && 
Ty->isFloatingType()300k
&&
782
9.49M
      
(4.01k
getLangOpts().getFPEvalMethod() !=
783
4.01k
           LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine ||
784
4.01k
       
PP.getLastFPEvalPragmaLocation().isValid()3.87k
)) {
785
249
    switch (EvalMethod) {
786
0
    default:
787
0
      llvm_unreachable("Unrecognized float evaluation method");
788
0
      break;
789
0
    case LangOptions::FEM_UnsetOnCommandLine:
790
0
      llvm_unreachable("Float evaluation method should be set by now");
791
0
      break;
792
145
    case LangOptions::FEM_Double:
793
145
      if (Context.getFloatingTypeOrder(Context.DoubleTy, Ty) > 0)
794
        // Widen the expression to double.
795
111
        return Ty->isComplexType()
796
111
                   ? ImpCastExprToType(E,
797
0
                                       Context.getComplexType(Context.DoubleTy),
798
0
                                       CK_FloatingComplexCast)
799
111
                   : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast);
800
34
      break;
801
104
    case LangOptions::FEM_Extended:
802
104
      if (Context.getFloatingTypeOrder(Context.LongDoubleTy, Ty) > 0)
803
        // Widen the expression to long double.
804
84
        return Ty->isComplexType()
805
84
                   ? ImpCastExprToType(
806
0
                         E, Context.getComplexType(Context.LongDoubleTy),
807
0
                         CK_FloatingComplexCast)
808
84
                   : ImpCastExprToType(E, Context.LongDoubleTy,
809
84
                                       CK_FloatingCast);
810
20
      break;
811
249
    }
812
249
  }
813
814
  // Half FP have to be promoted to float unless it is natively supported
815
9.49M
  if (Ty->isHalfType() && 
!getLangOpts().NativeHalfType1.47k
)
816
999
    return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
817
818
  // Try to perform integral promotions if the object has a theoretically
819
  // promotable type.
820
9.48M
  if (Ty->isIntegralOrUnscopedEnumerationType()) {
821
    // C99 6.3.1.1p2:
822
    //
823
    //   The following may be used in an expression wherever an int or
824
    //   unsigned int may be used:
825
    //     - an object or expression with an integer type whose integer
826
    //       conversion rank is less than or equal to the rank of int
827
    //       and unsigned int.
828
    //     - A bit-field of type _Bool, int, signed int, or unsigned int.
829
    //
830
    //   If an int can represent all values of the original type, the
831
    //   value is converted to an int; otherwise, it is converted to an
832
    //   unsigned int. These are called the integer promotions. All
833
    //   other types are unchanged by the integer promotions.
834
835
9.00M
    QualType PTy = Context.isPromotableBitField(E);
836
9.00M
    if (!PTy.isNull()) {
837
1.43k
      E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
838
1.43k
      return E;
839
1.43k
    }
840
9.00M
    if (Ty->isPromotableIntegerType()) {
841
178k
      QualType PT = Context.getPromotedIntegerType(Ty);
842
178k
      E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
843
178k
      return E;
844
178k
    }
845
9.00M
  }
846
9.30M
  return E;
847
9.48M
}
848
849
/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
850
/// do not have a prototype. Arguments that have type float or __fp16
851
/// are promoted to double. All other argument types are converted by
852
/// UsualUnaryConversions().
853
113k
ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
854
113k
  QualType Ty = E->getType();
855
113k
  assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
856
857
0
  ExprResult Res = UsualUnaryConversions(E);
858
113k
  if (Res.isInvalid())
859
0
    return ExprError();
860
113k
  E = Res.get();
861
862
  // If this is a 'float'  or '__fp16' (CVR qualified or typedef)
863
  // promote to double.
864
  // Note that default argument promotion applies only to float (and
865
  // half/fp16); it does not apply to _Float16.
866
113k
  const BuiltinType *BTy = Ty->getAs<BuiltinType>();
867
113k
  if (BTy && 
(76.6k
BTy->getKind() == BuiltinType::Half76.6k
||
868
76.6k
              
BTy->getKind() == BuiltinType::Float76.6k
)) {
869
802
    if (getLangOpts().OpenCL &&
870
802
        
!getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())6
) {
871
2
      if (BTy->getKind() == BuiltinType::Half) {
872
0
        E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
873
0
      }
874
800
    } else {
875
800
      E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
876
800
    }
877
802
  }
878
113k
  if (BTy &&
879
113k
      getLangOpts().getExtendIntArgs() ==
880
76.6k
          LangOptions::ExtendArgsKind::ExtendTo64 &&
881
113k
      
Context.getTargetInfo().supportsExtendIntArgs()62
&&
Ty->isIntegerType()16
&&
882
113k
      Context.getTypeSizeInChars(BTy) <
883
14
          Context.getTypeSizeInChars(Context.LongLongTy)) {
884
12
    E = (Ty->isUnsignedIntegerType())
885
12
            ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)
886
6
                  .get()
887
12
            : 
ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get()6
;
888
12
    assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() &&
889
12
           "Unexpected typesize for LongLongTy");
890
12
  }
891
892
  // C++ performs lvalue-to-rvalue conversion as a default argument
893
  // promotion, even on class types, but note:
894
  //   C++11 [conv.lval]p2:
895
  //     When an lvalue-to-rvalue conversion occurs in an unevaluated
896
  //     operand or a subexpression thereof the value contained in the
897
  //     referenced object is not accessed. Otherwise, if the glvalue
898
  //     has a class type, the conversion copy-initializes a temporary
899
  //     of type T from the glvalue and the result of the conversion
900
  //     is a prvalue for the temporary.
901
  // FIXME: add some way to gate this entire thing for correctness in
902
  // potentially potentially evaluated contexts.
903
113k
  if (getLangOpts().CPlusPlus && 
E->isGLValue()102k
&&
!isUnevaluatedContext()245
) {
904
231
    ExprResult Temp = PerformCopyInitialization(
905
231
                       InitializedEntity::InitializeTemporary(E->getType()),
906
231
                                                E->getExprLoc(), E);
907
231
    if (Temp.isInvalid())
908
8
      return ExprError();
909
223
    E = Temp.get();
910
223
  }
911
912
113k
  return E;
913
113k
}
914
915
/// Determine the degree of POD-ness for an expression.
916
/// Incomplete types are considered POD, since this check can be performed
917
/// when we're in an unevaluated context.
918
214k
Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
919
214k
  if (Ty->isIncompleteType()) {
920
    // C++11 [expr.call]p7:
921
    //   After these conversions, if the argument does not have arithmetic,
922
    //   enumeration, pointer, pointer to member, or class type, the program
923
    //   is ill-formed.
924
    //
925
    // Since we've already performed array-to-pointer and function-to-pointer
926
    // decay, the only such type in C++ is cv void. This also handles
927
    // initializer lists as variadic arguments.
928
14
    if (Ty->isVoidType())
929
11
      return VAK_Invalid;
930
931
3
    if (Ty->isObjCObjectType())
932
0
      return VAK_Invalid;
933
3
    return VAK_Valid;
934
3
  }
935
936
214k
  if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
937
2
    return VAK_Invalid;
938
939
214k
  if (Ty.isCXX98PODType(Context))
940
213k
    return VAK_Valid;
941
942
  // C++11 [expr.call]p7:
943
  //   Passing a potentially-evaluated argument of class type (Clause 9)
944
  //   having a non-trivial copy constructor, a non-trivial move constructor,
945
  //   or a non-trivial destructor, with no corresponding parameter,
946
  //   is conditionally-supported with implementation-defined semantics.
947
472
  if (getLangOpts().CPlusPlus11 && 
!Ty->isDependentType()333
)
948
333
    if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
949
333
      if (!Record->hasNonTrivialCopyConstructor() &&
950
333
          
!Record->hasNonTrivialMoveConstructor()273
&&
951
333
          
!Record->hasNonTrivialDestructor()273
)
952
256
        return VAK_ValidInCXX11;
953
954
216
  if (getLangOpts().ObjCAutoRefCount && 
Ty->isObjCLifetimeType()0
)
955
0
    return VAK_Valid;
956
957
216
  if (Ty->isObjCObjectType())
958
10
    return VAK_Invalid;
959
960
206
  if (getLangOpts().MSVCCompat)
961
60
    return VAK_MSVCUndefined;
962
963
  // FIXME: In C++11, these cases are conditionally-supported, meaning we're
964
  // permitted to reject them. We should consider doing so.
965
146
  return VAK_Undefined;
966
206
}
967
968
98.7k
void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
969
  // Don't allow one to pass an Objective-C interface to a vararg.
970
98.7k
  const QualType &Ty = E->getType();
971
98.7k
  VarArgKind VAK = isValidVarArgType(Ty);
972
973
  // Complain about passing non-POD types through varargs.
974
98.7k
  switch (VAK) {
975
116
  case VAK_ValidInCXX11:
976
116
    DiagRuntimeBehavior(
977
116
        E->getBeginLoc(), nullptr,
978
116
        PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
979
116
    LLVM_FALLTHROUGH;
980
98.6k
  case VAK_Valid:
981
98.6k
    if (Ty->isRecordType()) {
982
      // This is unlikely to be what the user intended. If the class has a
983
      // 'c_str' member function, the user probably meant to call that.
984
393
      DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
985
393
                          PDiag(diag::warn_pass_class_arg_to_vararg)
986
393
                              << Ty << CT << hasCStrMethod(E) << ".c_str()");
987
393
    }
988
98.6k
    break;
989
990
61
  case VAK_Undefined:
991
91
  case VAK_MSVCUndefined:
992
91
    DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
993
91
                        PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
994
91
                            << getLangOpts().CPlusPlus11 << Ty << CT);
995
91
    break;
996
997
7
  case VAK_Invalid:
998
7
    if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
999
1
      Diag(E->getBeginLoc(),
1000
1
           diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
1001
1
          << Ty << CT;
1002
6
    else if (Ty->isObjCObjectType())
1003
3
      DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1004
3
                          PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
1005
3
                              << Ty << CT);
1006
3
    else
1007
3
      Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
1008
3
          << isa<InitListExpr>(E) << Ty << CT;
1009
7
    break;
1010
98.7k
  }
1011
98.7k
}
1012
1013
/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
1014
/// will create a trap if the resulting type is not a POD type.
1015
ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
1016
111k
                                                  FunctionDecl *FDecl) {
1017
111k
  if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1018
    // Strip the unbridged-cast placeholder expression off, if applicable.
1019
15
    if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1020
15
        
(9
CT == VariadicMethod9
||
1021
9
         
(7
FDecl7
&&
FDecl->hasAttr<CFAuditedTransferAttr>()7
))) {
1022
5
      E = stripARCUnbridgedCast(E);
1023
1024
    // Otherwise, do normal placeholder checking.
1025
10
    } else {
1026
10
      ExprResult ExprRes = CheckPlaceholderExpr(E);
1027
10
      if (ExprRes.isInvalid())
1028
3
        return ExprError();
1029
7
      E = ExprRes.get();
1030
7
    }
1031
15
  }
1032
1033
111k
  ExprResult ExprRes = DefaultArgumentPromotion(E);
1034
111k
  if (ExprRes.isInvalid())
1035
8
    return ExprError();
1036
1037
  // Copy blocks to the heap.
1038
111k
  if (ExprRes.get()->getType()->isBlockPointerType())
1039
21
    maybeExtendBlockObject(ExprRes);
1040
1041
111k
  E = ExprRes.get();
1042
1043
  // Diagnostics regarding non-POD argument types are
1044
  // emitted along with format string checking in Sema::CheckFunctionCall().
1045
111k
  if (isValidVarArgType(E->getType()) == VAK_Undefined) {
1046
    // Turn this into a trap.
1047
76
    CXXScopeSpec SS;
1048
76
    SourceLocation TemplateKWLoc;
1049
76
    UnqualifiedId Name;
1050
76
    Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1051
76
                       E->getBeginLoc());
1052
76
    ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1053
76
                                          /*HasTrailingLParen=*/true,
1054
76
                                          /*IsAddressOfOperand=*/false);
1055
76
    if (TrapFn.isInvalid())
1056
0
      return ExprError();
1057
1058
76
    ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
1059
76
                                    None, E->getEndLoc());
1060
76
    if (Call.isInvalid())
1061
0
      return ExprError();
1062
1063
76
    ExprResult Comma =
1064
76
        ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1065
76
    if (Comma.isInvalid())
1066
0
      return ExprError();
1067
76
    return Comma.get();
1068
76
  }
1069
1070
111k
  if (!getLangOpts().CPlusPlus &&
1071
111k
      RequireCompleteType(E->getExprLoc(), E->getType(),
1072
9.39k
                          diag::err_call_incomplete_argument))
1073
2
    return ExprError();
1074
1075
111k
  return E;
1076
111k
}
1077
1078
/// Converts an integer to complex float type.  Helper function of
1079
/// UsualArithmeticConversions()
1080
///
1081
/// \return false if the integer expression is an integer type and is
1082
/// successfully converted to the complex type.
1083
static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1084
                                                  ExprResult &ComplexExpr,
1085
                                                  QualType IntTy,
1086
                                                  QualType ComplexTy,
1087
1.29k
                                                  bool SkipCast) {
1088
1.29k
  if (IntTy->isComplexType() || 
IntTy->isRealFloatingType()649
)
return true1.22k
;
1089
74
  if (SkipCast) 
return false0
;
1090
74
  if (IntTy->isIntegerType()) {
1091
43
    QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1092
43
    IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1093
43
    IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1094
43
                                  CK_FloatingRealToComplex);
1095
43
  } else {
1096
31
    assert(IntTy->isComplexIntegerType());
1097
0
    IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1098
31
                                  CK_IntegralComplexToFloatingComplex);
1099
31
  }
1100
0
  return false;
1101
74
}
1102
1103
/// Handle arithmetic conversion with complex types.  Helper function of
1104
/// UsualArithmeticConversions()
1105
static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1106
                                             ExprResult &RHS, QualType LHSType,
1107
                                             QualType RHSType,
1108
661
                                             bool IsCompAssign) {
1109
  // if we have an integer operand, the result is the complex type.
1110
661
  if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1111
661
                                             /*skipCast*/false))
1112
28
    return LHSType;
1113
633
  if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1114
633
                                             /*skipCast*/IsCompAssign))
1115
46
    return RHSType;
1116
1117
  // This handles complex/complex, complex/float, or float/complex.
1118
  // When both operands are complex, the shorter operand is converted to the
1119
  // type of the longer, and that is the type of the result. This corresponds
1120
  // to what is done when combining two real floating-point operands.
1121
  // The fun begins when size promotion occur across type domains.
1122
  // From H&S 6.3.4: When one operand is complex and the other is a real
1123
  // floating-point type, the less precise type is converted, within it's
1124
  // real or complex domain, to the precision of the other type. For example,
1125
  // when combining a "long double" with a "double _Complex", the
1126
  // "double _Complex" is promoted to "long double _Complex".
1127
1128
  // Compute the rank of the two types, regardless of whether they are complex.
1129
587
  int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1130
1131
587
  auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1132
587
  auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1133
587
  QualType LHSElementType =
1134
587
      LHSComplexType ? 
LHSComplexType->getElementType()180
:
LHSType407
;
1135
587
  QualType RHSElementType =
1136
587
      RHSComplexType ? 
RHSComplexType->getElementType()419
:
RHSType168
;
1137
1138
587
  QualType ResultType = S.Context.getComplexType(LHSElementType);
1139
587
  if (Order < 0) {
1140
    // Promote the precision of the LHS if not an assignment.
1141
21
    ResultType = S.Context.getComplexType(RHSElementType);
1142
21
    if (!IsCompAssign) {
1143
17
      if (LHSComplexType)
1144
10
        LHS =
1145
10
            S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1146
7
      else
1147
7
        LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1148
17
    }
1149
566
  } else if (Order > 0) {
1150
    // Promote the precision of the RHS.
1151
35
    if (RHSComplexType)
1152
29
      RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1153
6
    else
1154
6
      RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1155
35
  }
1156
587
  return ResultType;
1157
633
}
1158
1159
/// Handle arithmetic conversion from integer to float.  Helper function
1160
/// of UsualArithmeticConversions()
1161
static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1162
                                           ExprResult &IntExpr,
1163
                                           QualType FloatTy, QualType IntTy,
1164
8.93k
                                           bool ConvertFloat, bool ConvertInt) {
1165
8.93k
  if (IntTy->isIntegerType()) {
1166
8.91k
    if (ConvertInt)
1167
      // Convert intExpr to the lhs floating point type.
1168
8.62k
      IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1169
8.62k
                                    CK_IntegralToFloating);
1170
8.91k
    return FloatTy;
1171
8.91k
  }
1172
1173
  // Convert both sides to the appropriate complex float.
1174
27
  assert(IntTy->isComplexIntegerType());
1175
0
  QualType result = S.Context.getComplexType(FloatTy);
1176
1177
  // _Complex int -> _Complex float
1178
27
  if (ConvertInt)
1179
27
    IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1180
27
                                  CK_IntegralComplexToFloatingComplex);
1181
1182
  // float -> _Complex float
1183
27
  if (ConvertFloat)
1184
27
    FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1185
27
                                    CK_FloatingRealToComplex);
1186
1187
27
  return result;
1188
8.93k
}
1189
1190
/// Handle arithmethic conversion with floating point types.  Helper
1191
/// function of UsualArithmeticConversions()
1192
static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1193
                                      ExprResult &RHS, QualType LHSType,
1194
10.6k
                                      QualType RHSType, bool IsCompAssign) {
1195
10.6k
  bool LHSFloat = LHSType->isRealFloatingType();
1196
10.6k
  bool RHSFloat = RHSType->isRealFloatingType();
1197
1198
  // N1169 4.1.4: If one of the operands has a floating type and the other
1199
  //              operand has a fixed-point type, the fixed-point operand
1200
  //              is converted to the floating type [...]
1201
10.6k
  if (LHSType->isFixedPointType() || 
RHSType->isFixedPointType()10.6k
) {
1202
14
    if (LHSFloat)
1203
4
      RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1204
10
    else if (!IsCompAssign)
1205
0
      LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1206
14
    return LHSFloat ? 
LHSType4
:
RHSType10
;
1207
14
  }
1208
1209
  // If we have two real floating types, convert the smaller operand
1210
  // to the bigger result.
1211
10.6k
  if (LHSFloat && 
RHSFloat6.25k
) {
1212
1.69k
    int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1213
1.69k
    if (order > 0) {
1214
151
      RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1215
151
      return LHSType;
1216
151
    }
1217
1218
1.54k
    assert(order < 0 && "illegal float comparison");
1219
1.54k
    if (!IsCompAssign)
1220
598
      LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1221
1.54k
    return RHSType;
1222
1.69k
  }
1223
1224
8.93k
  if (LHSFloat) {
1225
    // Half FP has to be promoted to float unless it is natively supported
1226
4.56k
    if (LHSType->isHalfType() && 
!S.getLangOpts().NativeHalfType110
)
1227
40
      LHSType = S.Context.FloatTy;
1228
1229
4.56k
    return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1230
4.56k
                                      /*ConvertFloat=*/!IsCompAssign,
1231
4.56k
                                      /*ConvertInt=*/ true);
1232
4.56k
  }
1233
4.37k
  assert(RHSFloat);
1234
0
  return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1235
4.37k
                                    /*ConvertFloat=*/ true,
1236
4.37k
                                    /*ConvertInt=*/!IsCompAssign);
1237
8.93k
}
1238
1239
/// Diagnose attempts to convert between __float128, __ibm128 and
1240
/// long double if there is no support for such conversion.
1241
/// Helper function of UsualArithmeticConversions().
1242
static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1243
872k
                                      QualType RHSType) {
1244
  // No issue if either is not a floating point type.
1245
872k
  if (!LHSType->isFloatingType() || 
!RHSType->isFloatingType()33.0k
)
1246
860k
    return false;
1247
1248
  // No issue if both have the same 128-bit float semantics.
1249
11.8k
  auto *LHSComplex = LHSType->getAs<ComplexType>();
1250
11.8k
  auto *RHSComplex = RHSType->getAs<ComplexType>();
1251
1252
11.8k
  QualType LHSElem = LHSComplex ? 
LHSComplex->getElementType()795
:
LHSType11.0k
;
1253
11.8k
  QualType RHSElem = RHSComplex ? 
RHSComplex->getElementType()554
:
RHSType11.2k
;
1254
1255
11.8k
  const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem);
1256
11.8k
  const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem);
1257
1258
11.8k
  if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1259
11.8k
       
&RHSSem != &llvm::APFloat::IEEEquad()49
) &&
1260
11.8k
      
(11.7k
&LHSSem != &llvm::APFloat::IEEEquad()11.7k
||
1261
11.7k
       
&RHSSem != &llvm::APFloat::PPCDoubleDouble()357
))
1262
11.7k
    return false;
1263
1264
45
  return true;
1265
11.8k
}
1266
1267
typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1268
1269
namespace {
1270
/// These helper callbacks are placed in an anonymous namespace to
1271
/// permit their use as function template parameters.
1272
456k
ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1273
456k
  return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1274
456k
}
1275
1276
106
ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1277
106
  return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1278
106
                             CK_IntegralComplexCast);
1279
106
}
1280
}
1281
1282
/// Handle integer arithmetic conversions.  Helper function of
1283
/// UsualArithmeticConversions()
1284
template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1285
static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1286
                                        ExprResult &RHS, QualType LHSType,
1287
457k
                                        QualType RHSType, bool IsCompAssign) {
1288
  // The rules for this case are in C99 6.3.1.8
1289
457k
  int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1290
457k
  bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1291
457k
  bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1292
457k
  if (LHSSigned == RHSSigned) {
1293
    // Same signedness; use the higher-ranked type
1294
96.9k
    if (order >= 0) {
1295
74.5k
      RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1296
74.5k
      return LHSType;
1297
74.5k
    } else 
if (22.3k
!IsCompAssign22.3k
)
1298
22.2k
      LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1299
22.3k
    return RHSType;
1300
360k
  } else if (order != (LHSSigned ? 
180.0k
:
-1280k
)) {
1301
    // The unsigned type has greater than or equal rank to the
1302
    // signed type, so use the unsigned type
1303
355k
    if (RHSSigned) {
1304
277k
      RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1305
277k
      return LHSType;
1306
277k
    } else 
if (78.1k
!IsCompAssign78.1k
)
1307
77.8k
      LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1308
78.1k
    return RHSType;
1309
355k
  } else 
if (4.35k
S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)4.35k
) {
1310
    // The two types are different widths; if we are here, that
1311
    // means the signed type is larger than the unsigned type, so
1312
    // use the signed type.
1313
4.12k
    if (LHSSigned) {
1314
1.68k
      RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1315
1.68k
      return LHSType;
1316
2.43k
    } else if (!IsCompAssign)
1317
2.43k
      LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1318
2.43k
    return RHSType;
1319
4.12k
  } else {
1320
    // The signed type is higher-ranked than the unsigned type,
1321
    // but isn't actually any bigger (like unsigned int and long
1322
    // on most 32-bit systems).  Use the unsigned type corresponding
1323
    // to the signed type.
1324
229
    QualType result =
1325
229
      S.Context.getCorrespondingUnsignedType(LHSSigned ? 
LHSType177
:
RHSType52
);
1326
229
    RHS = (*doRHSCast)(S, RHS.get(), result);
1327
229
    if (!IsCompAssign)
1328
229
      LHS = (*doLHSCast)(S, LHS.get(), result);
1329
229
    return result;
1330
229
  }
1331
457k
}
SemaExpr.cpp:clang::QualType handleIntegerConversion<&((anonymous namespace)::doComplexIntegralCast(clang::Sema&, clang::Expr*, clang::QualType)), &((anonymous namespace)::doComplexIntegralCast(clang::Sema&, clang::Expr*, clang::QualType))>(clang::Sema&, clang::ActionResult<clang::Expr*, true>&, clang::ActionResult<clang::Expr*, true>&, clang::QualType, clang::QualType, bool)
Line
Count
Source
1287
25
                                        QualType RHSType, bool IsCompAssign) {
1288
  // The rules for this case are in C99 6.3.1.8
1289
25
  int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1290
25
  bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1291
25
  bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1292
25
  if (LHSSigned == RHSSigned) {
1293
    // Same signedness; use the higher-ranked type
1294
24
    if (order >= 0) {
1295
14
      RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1296
14
      return LHSType;
1297
14
    } else 
if (10
!IsCompAssign10
)
1298
9
      LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1299
10
    return RHSType;
1300
24
  } else 
if (1
order != (1
LHSSigned1
?
10
:
-11
)) {
1301
    // The unsigned type has greater than or equal rank to the
1302
    // signed type, so use the unsigned type
1303
1
    if (RHSSigned) {
1304
1
      RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1305
1
      return LHSType;
1306
1
    } else 
if (0
!IsCompAssign0
)
1307
0
      LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1308
0
    return RHSType;
1309
1
  } else 
if (0
S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)0
) {
1310
    // The two types are different widths; if we are here, that
1311
    // means the signed type is larger than the unsigned type, so
1312
    // use the signed type.
1313
0
    if (LHSSigned) {
1314
0
      RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1315
0
      return LHSType;
1316
0
    } else if (!IsCompAssign)
1317
0
      LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1318
0
    return RHSType;
1319
0
  } else {
1320
    // The signed type is higher-ranked than the unsigned type,
1321
    // but isn't actually any bigger (like unsigned int and long
1322
    // on most 32-bit systems).  Use the unsigned type corresponding
1323
    // to the signed type.
1324
0
    QualType result =
1325
0
      S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1326
0
    RHS = (*doRHSCast)(S, RHS.get(), result);
1327
0
    if (!IsCompAssign)
1328
0
      LHS = (*doLHSCast)(S, LHS.get(), result);
1329
0
    return result;
1330
0
  }
1331
25
}
SemaExpr.cpp:clang::QualType handleIntegerConversion<&((anonymous namespace)::doComplexIntegralCast(clang::Sema&, clang::Expr*, clang::QualType)), &((anonymous namespace)::doIntegralCast(clang::Sema&, clang::Expr*, clang::QualType))>(clang::Sema&, clang::ActionResult<clang::Expr*, true>&, clang::ActionResult<clang::Expr*, true>&, clang::QualType, clang::QualType, bool)
Line
Count
Source
1287
61
                                        QualType RHSType, bool IsCompAssign) {
1288
  // The rules for this case are in C99 6.3.1.8
1289
61
  int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1290
61
  bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1291
61
  bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1292
61
  if (LHSSigned == RHSSigned) {
1293
    // Same signedness; use the higher-ranked type
1294
53
    if (order >= 0) {
1295
46
      RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1296
46
      return LHSType;
1297
46
    } else 
if (7
!IsCompAssign7
)
1298
6
      LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1299
7
    return RHSType;
1300
53
  } else 
if (8
order != (8
LHSSigned8
?
12
:
-16
)) {
1301
    // The unsigned type has greater than or equal rank to the
1302
    // signed type, so use the unsigned type
1303
5
    if (RHSSigned) {
1304
3
      RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1305
3
      return LHSType;
1306
3
    } else 
if (2
!IsCompAssign2
)
1307
2
      LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1308
2
    return RHSType;
1309
5
  } else 
if (3
S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)3
) {
1310
    // The two types are different widths; if we are here, that
1311
    // means the signed type is larger than the unsigned type, so
1312
    // use the signed type.
1313
3
    if (LHSSigned) {
1314
0
      RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1315
0
      return LHSType;
1316
3
    } else if (!IsCompAssign)
1317
3
      LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1318
3
    return RHSType;
1319
3
  } else {
1320
    // The signed type is higher-ranked than the unsigned type,
1321
    // but isn't actually any bigger (like unsigned int and long
1322
    // on most 32-bit systems).  Use the unsigned type corresponding
1323
    // to the signed type.
1324
0
    QualType result =
1325
0
      S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1326
0
    RHS = (*doRHSCast)(S, RHS.get(), result);
1327
0
    if (!IsCompAssign)
1328
0
      LHS = (*doLHSCast)(S, LHS.get(), result);
1329
0
    return result;
1330
0
  }
1331
61
}
SemaExpr.cpp:clang::QualType handleIntegerConversion<&((anonymous namespace)::doIntegralCast(clang::Sema&, clang::Expr*, clang::QualType)), &((anonymous namespace)::doComplexIntegralCast(clang::Sema&, clang::Expr*, clang::QualType))>(clang::Sema&, clang::ActionResult<clang::Expr*, true>&, clang::ActionResult<clang::Expr*, true>&, clang::QualType, clang::QualType, bool)
Line
Count
Source
1287
78
                                        QualType RHSType, bool IsCompAssign) {
1288
  // The rules for this case are in C99 6.3.1.8
1289
78
  int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1290
78
  bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1291
78
  bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1292
78
  if (LHSSigned == RHSSigned) {
1293
    // Same signedness; use the higher-ranked type
1294
68
    if (order >= 0) {
1295
66
      RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1296
66
      return LHSType;
1297
66
    } else 
if (2
!IsCompAssign2
)
1298
2
      LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1299
2
    return RHSType;
1300
68
  } else 
if (10
order != (10
LHSSigned10
?
18
:
-12
)) {
1301
    // The unsigned type has greater than or equal rank to the
1302
    // signed type, so use the unsigned type
1303
7
    if (RHSSigned) {
1304
2
      RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1305
2
      return LHSType;
1306
5
    } else if (!IsCompAssign)
1307
5
      LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1308
5
    return RHSType;
1309
7
  } else 
if (3
S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)3
) {
1310
    // The two types are different widths; if we are here, that
1311
    // means the signed type is larger than the unsigned type, so
1312
    // use the signed type.
1313
3
    if (LHSSigned) {
1314
3
      RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1315
3
      return LHSType;
1316
3
    } else 
if (0
!IsCompAssign0
)
1317
0
      LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1318
0
    return RHSType;
1319
3
  } else {
1320
    // The signed type is higher-ranked than the unsigned type,
1321
    // but isn't actually any bigger (like unsigned int and long
1322
    // on most 32-bit systems).  Use the unsigned type corresponding
1323
    // to the signed type.
1324
0
    QualType result =
1325
0
      S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1326
0
    RHS = (*doRHSCast)(S, RHS.get(), result);
1327
0
    if (!IsCompAssign)
1328
0
      LHS = (*doLHSCast)(S, LHS.get(), result);
1329
0
    return result;
1330
0
  }
1331
78
}
SemaExpr.cpp:clang::QualType handleIntegerConversion<&((anonymous namespace)::doIntegralCast(clang::Sema&, clang::Expr*, clang::QualType)), &((anonymous namespace)::doIntegralCast(clang::Sema&, clang::Expr*, clang::QualType))>(clang::Sema&, clang::ActionResult<clang::Expr*, true>&, clang::ActionResult<clang::Expr*, true>&, clang::QualType, clang::QualType, bool)
Line
Count
Source
1287
457k
                                        QualType RHSType, bool IsCompAssign) {
1288
  // The rules for this case are in C99 6.3.1.8
1289
457k
  int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1290
457k
  bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1291
457k
  bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1292
457k
  if (LHSSigned == RHSSigned) {
1293
    // Same signedness; use the higher-ranked type
1294
96.8k
    if (order >= 0) {
1295
74.4k
      RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1296
74.4k
      return LHSType;
1297
74.4k
    } else 
if (22.3k
!IsCompAssign22.3k
)
1298
22.2k
      LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1299
22.3k
    return RHSType;
1300
360k
  } else if (order != (LHSSigned ? 
180.0k
:
-1280k
)) {
1301
    // The unsigned type has greater than or equal rank to the
1302
    // signed type, so use the unsigned type
1303
355k
    if (RHSSigned) {
1304
277k
      RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1305
277k
      return LHSType;
1306
277k
    } else 
if (78.1k
!IsCompAssign78.1k
)
1307
77.8k
      LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1308
78.1k
    return RHSType;
1309
355k
  } else 
if (4.34k
S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)4.34k
) {
1310
    // The two types are different widths; if we are here, that
1311
    // means the signed type is larger than the unsigned type, so
1312
    // use the signed type.
1313
4.11k
    if (LHSSigned) {
1314
1.68k
      RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1315
1.68k
      return LHSType;
1316
2.43k
    } else if (!IsCompAssign)
1317
2.43k
      LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1318
2.43k
    return RHSType;
1319
4.11k
  } else {
1320
    // The signed type is higher-ranked than the unsigned type,
1321
    // but isn't actually any bigger (like unsigned int and long
1322
    // on most 32-bit systems).  Use the unsigned type corresponding
1323
    // to the signed type.
1324
229
    QualType result =
1325
229
      S.Context.getCorrespondingUnsignedType(LHSSigned ? 
LHSType177
:
RHSType52
);
1326
229
    RHS = (*doRHSCast)(S, RHS.get(), result);
1327
229
    if (!IsCompAssign)
1328
229
      LHS = (*doLHSCast)(S, LHS.get(), result);
1329
229
    return result;
1330
229
  }
1331
457k
}
1332
1333
/// Handle conversions with GCC complex int extension.  Helper function
1334
/// of UsualArithmeticConversions()
1335
static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1336
                                           ExprResult &RHS, QualType LHSType,
1337
                                           QualType RHSType,
1338
164
                                           bool IsCompAssign) {
1339
164
  const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1340
164
  const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1341
1342
164
  if (LHSComplexInt && 
RHSComplexInt86
) {
1343
25
    QualType LHSEltType = LHSComplexInt->getElementType();
1344
25
    QualType RHSEltType = RHSComplexInt->getElementType();
1345
25
    QualType ScalarType =
1346
25
      handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1347
25
        (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1348
1349
25
    return S.Context.getComplexType(ScalarType);
1350
25
  }
1351
1352
139
  if (LHSComplexInt) {
1353
61
    QualType LHSEltType = LHSComplexInt->getElementType();
1354
61
    QualType ScalarType =
1355
61
      handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1356
61
        (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1357
61
    QualType ComplexType = S.Context.getComplexType(ScalarType);
1358
61
    RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1359
61
                              CK_IntegralRealToComplex);
1360
1361
61
    return ComplexType;
1362
61
  }
1363
1364
78
  assert(RHSComplexInt);
1365
1366
0
  QualType RHSEltType = RHSComplexInt->getElementType();
1367
78
  QualType ScalarType =
1368
78
    handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1369
78
      (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1370
78
  QualType ComplexType = S.Context.getComplexType(ScalarType);
1371
1372
78
  if (!IsCompAssign)
1373
76
    LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1374
76
                              CK_IntegralRealToComplex);
1375
78
  return ComplexType;
1376
139
}
1377
1378
/// Return the rank of a given fixed point or integer type. The value itself
1379
/// doesn't matter, but the values must be increasing with proper increasing
1380
/// rank as described in N1169 4.1.1.
1381
1.05k
static unsigned GetFixedPointRank(QualType Ty) {
1382
1.05k
  const auto *BTy = Ty->getAs<BuiltinType>();
1383
1.05k
  assert(BTy && "Expected a builtin type.");
1384
1385
0
  switch (BTy->getKind()) {
1386
53
  case BuiltinType::ShortFract:
1387
61
  case BuiltinType::UShortFract:
1388
65
  case BuiltinType::SatShortFract:
1389
65
  case BuiltinType::SatUShortFract:
1390
65
    return 1;
1391
26
  case BuiltinType::Fract:
1392
36
  case BuiltinType::UFract:
1393
38
  case BuiltinType::SatFract:
1394
38
  case BuiltinType::SatUFract:
1395
38
    return 2;
1396
45
  case BuiltinType::LongFract:
1397
45
  case BuiltinType::ULongFract:
1398
45
  case BuiltinType::SatLongFract:
1399
45
  case BuiltinType::SatULongFract:
1400
45
    return 3;
1401
321
  case BuiltinType::ShortAccum:
1402
411
  case BuiltinType::UShortAccum:
1403
475
  case BuiltinType::SatShortAccum:
1404
523
  case BuiltinType::SatUShortAccum:
1405
523
    return 4;
1406
93
  case BuiltinType::Accum:
1407
117
  case BuiltinType::UAccum:
1408
129
  case BuiltinType::SatAccum:
1409
129
  case BuiltinType::SatUAccum:
1410
129
    return 5;
1411
14
  case BuiltinType::LongAccum:
1412
20
  case BuiltinType::ULongAccum:
1413
20
  case BuiltinType::SatLongAccum:
1414
22
  case BuiltinType::SatULongAccum:
1415
22
    return 6;
1416
236
  default:
1417
236
    if (BTy->isInteger())
1418
236
      return 0;
1419
1.05k
    
llvm_unreachable0
("Unexpected fixed point or integer type");
1420
1.05k
  }
1421
1.05k
}
1422
1423
/// handleFixedPointConversion - Fixed point operations between fixed
1424
/// point types and integers or other fixed point types do not fall under
1425
/// usual arithmetic conversion since these conversions could result in loss
1426
/// of precsision (N1169 4.1.4). These operations should be calculated with
1427
/// the full precision of their result type (N1169 4.1.6.2.1).
1428
static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1429
529
                                           QualType RHSTy) {
1430
529
  assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1431
529
         "Expected at least one of the operands to be a fixed point type");
1432
0
  assert((LHSTy->isFixedPointOrIntegerType() ||
1433
529
          RHSTy->isFixedPointOrIntegerType()) &&
1434
529
         "Special fixed point arithmetic operation conversions are only "
1435
529
         "applied to ints or other fixed point types");
1436
1437
  // If one operand has signed fixed-point type and the other operand has
1438
  // unsigned fixed-point type, then the unsigned fixed-point operand is
1439
  // converted to its corresponding signed fixed-point type and the resulting
1440
  // type is the type of the converted operand.
1441
529
  if (RHSTy->isSignedFixedPointType() && 
LHSTy->isUnsignedFixedPointType()194
)
1442
12
    LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1443
517
  else if (RHSTy->isUnsignedFixedPointType() && 
LHSTy->isSignedFixedPointType()148
)
1444
76
    RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1445
1446
  // The result type is the type with the highest rank, whereby a fixed-point
1447
  // conversion rank is always greater than an integer conversion rank; if the
1448
  // type of either of the operands is a saturating fixedpoint type, the result
1449
  // type shall be the saturating fixed-point type corresponding to the type
1450
  // with the highest rank; the resulting value is converted (taking into
1451
  // account rounding and overflow) to the precision of the resulting type.
1452
  // Same ranks between signed and unsigned types are resolved earlier, so both
1453
  // types are either signed or both unsigned at this point.
1454
529
  unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1455
529
  unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1456
1457
529
  QualType ResultTy = LHSTyRank > RHSTyRank ? 
LHSTy280
:
RHSTy249
;
1458
1459
529
  if (LHSTy->isSaturatedFixedPointType() || 
RHSTy->isSaturatedFixedPointType()435
)
1460
126
    ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1461
1462
529
  return ResultTy;
1463
529
}
1464
1465
/// Check that the usual arithmetic conversions can be performed on this pair of
1466
/// expressions that might be of enumeration type.
1467
static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1468
                                           SourceLocation Loc,
1469
3.85M
                                           Sema::ArithConvKind ACK) {
1470
  // C++2a [expr.arith.conv]p1:
1471
  //   If one operand is of enumeration type and the other operand is of a
1472
  //   different enumeration type or a floating-point type, this behavior is
1473
  //   deprecated ([depr.arith.conv.enum]).
1474
  //
1475
  // Warn on this in all language modes. Produce a deprecation warning in C++20.
1476
  // Eventually we will presumably reject these cases (in C++23 onwards?).
1477
3.85M
  QualType L = LHS->getType(), R = RHS->getType();
1478
3.85M
  bool LEnum = L->isUnscopedEnumerationType(),
1479
3.85M
       REnum = R->isUnscopedEnumerationType();
1480
3.85M
  bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1481
3.85M
  if ((!IsCompAssign && 
LEnum3.78M
&&
R->isFloatingType()31.5k
) ||
1482
3.85M
      
(3.85M
REnum3.85M
&&
L->isFloatingType()34.0k
)) {
1483
40
    S.Diag(Loc, S.getLangOpts().CPlusPlus20
1484
40
                    ? 
diag::warn_arith_conv_enum_float_cxx2014
1485
40
                    : 
diag::warn_arith_conv_enum_float26
)
1486
40
        << LHS->getSourceRange() << RHS->getSourceRange()
1487
40
        << (int)ACK << LEnum << L << R;
1488
3.85M
  } else if (!IsCompAssign && 
LEnum3.78M
&&
REnum31.5k
&&
1489
3.85M
             
!S.Context.hasSameUnqualifiedType(L, R)27.7k
) {
1490
1.92k
    unsigned DiagID;
1491
1.92k
    if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1492
1.92k
        
!R->castAs<EnumType>()->getDecl()->hasNameForLinkage()307
) {
1493
      // If either enumeration type is unnamed, it's less likely that the
1494
      // user cares about this, but this situation is still deprecated in
1495
      // C++2a. Use a different warning group.
1496
1.62k
      DiagID = S.getLangOpts().CPlusPlus20
1497
1.62k
                    ? 
diag::warn_arith_conv_mixed_anon_enum_types_cxx200
1498
1.62k
                    : diag::warn_arith_conv_mixed_anon_enum_types;
1499
1.62k
    } else 
if (301
ACK == Sema::ACK_Conditional301
) {
1500
      // Conditional expressions are separated out because they have
1501
      // historically had a different warning flag.
1502
13
      DiagID = S.getLangOpts().CPlusPlus20
1503
13
                   ? 
diag::warn_conditional_mixed_enum_types_cxx202
1504
13
                   : 
diag::warn_conditional_mixed_enum_types11
;
1505
288
    } else if (ACK == Sema::ACK_Comparison) {
1506
      // Comparison expressions are separated out because they have
1507
      // historically had a different warning flag.
1508
284
      DiagID = S.getLangOpts().CPlusPlus20
1509
284
                   ? 
diag::warn_comparison_mixed_enum_types_cxx203
1510
284
                   : 
diag::warn_comparison_mixed_enum_types281
;
1511
284
    } else {
1512
4
      DiagID = S.getLangOpts().CPlusPlus20
1513
4
                   ? 
diag::warn_arith_conv_mixed_enum_types_cxx202
1514
4
                   : 
diag::warn_arith_conv_mixed_enum_types2
;
1515
4
    }
1516
1.92k
    S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1517
1.92k
                        << (int)ACK << L << R;
1518
1.92k
  }
1519
3.85M
}
1520
1521
/// UsualArithmeticConversions - Performs various conversions that are common to
1522
/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1523
/// routine returns the first non-arithmetic type found. The client is
1524
/// responsible for emitting appropriate error diagnostics.
1525
QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1526
                                          SourceLocation Loc,
1527
3.85M
                                          ArithConvKind ACK) {
1528
3.85M
  checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1529
1530
3.85M
  if (ACK != ACK_CompAssign) {
1531
3.78M
    LHS = UsualUnaryConversions(LHS.get());
1532
3.78M
    if (LHS.isInvalid())
1533
2
      return QualType();
1534
3.78M
  }
1535
1536
3.85M
  RHS = UsualUnaryConversions(RHS.get());
1537
3.85M
  if (RHS.isInvalid())
1538
2
    return QualType();
1539
1540
  // For conversion purposes, we ignore any qualifiers.
1541
  // For example, "const float" and "float" are equivalent.
1542
3.85M
  QualType LHSType =
1543
3.85M
    Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1544
3.85M
  QualType RHSType =
1545
3.85M
    Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1546
1547
  // For conversion purposes, we ignore any atomic qualifier on the LHS.
1548
3.85M
  if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1549
58
    LHSType = AtomicLHS->getValueType();
1550
1551
  // If both types are identical, no conversion is needed.
1552
3.85M
  if (LHSType == RHSType)
1553
3.30M
    return LHSType;
1554
1555
  // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1556
  // The caller can deal with this (e.g. pointer + int).
1557
540k
  if (!LHSType->isArithmeticType() || 
!RHSType->isArithmeticType()473k
)
1558
67.5k
    return QualType();
1559
1560
  // Apply unary and bitfield promotions to the LHS's type.
1561
473k
  QualType LHSUnpromotedType = LHSType;
1562
473k
  if (LHSType->isPromotableIntegerType())
1563
4.13k
    LHSType = Context.getPromotedIntegerType(LHSType);
1564
473k
  QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1565
473k
  if (!LHSBitfieldPromoteTy.isNull())
1566
151
    LHSType = LHSBitfieldPromoteTy;
1567
473k
  if (LHSType != LHSUnpromotedType && 
ACK != ACK_CompAssign4.18k
)
1568
0
    LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1569
1570
  // If both types are identical, no conversion is needed.
1571
473k
  if (LHSType == RHSType)
1572
3.93k
    return LHSType;
1573
1574
  // At this point, we have two different arithmetic types.
1575
1576
  // Diagnose attempts to convert between __ibm128, __float128 and long double
1577
  // where such conversions currently can't be handled.
1578
469k
  if (unsupportedTypeConversion(*this, LHSType, RHSType))
1579
28
    return QualType();
1580
1581
  // Handle complex types first (C99 6.3.1.8p1).
1582
469k
  if (LHSType->isComplexType() || 
RHSType->isComplexType()468k
)
1583
661
    return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1584
661
                                        ACK == ACK_CompAssign);
1585
1586
  // Now handle "real" floating types (i.e. float, double, long double).
1587
468k
  if (LHSType->isRealFloatingType() || 
RHSType->isRealFloatingType()462k
)
1588
10.6k
    return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1589
10.6k
                                 ACK == ACK_CompAssign);
1590
1591
  // Handle GCC complex int extension.
1592
457k
  if (LHSType->isComplexIntegerType() || 
RHSType->isComplexIntegerType()457k
)
1593
164
    return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1594
164
                                      ACK == ACK_CompAssign);
1595
1596
457k
  if (LHSType->isFixedPointType() || 
RHSType->isFixedPointType()457k
)
1597
529
    return handleFixedPointConversion(*this, LHSType, RHSType);
1598
1599
  // Finally, we have two differing integer types.
1600
457k
  return handleIntegerConversion<doIntegralCast, doIntegralCast>
1601
457k
           (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1602
457k
}
1603
1604
//===----------------------------------------------------------------------===//
1605
//  Semantic Analysis for various Expression Types
1606
//===----------------------------------------------------------------------===//
1607
1608
1609
ExprResult
1610
Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1611
                                SourceLocation DefaultLoc,
1612
                                SourceLocation RParenLoc,
1613
                                Expr *ControllingExpr,
1614
                                ArrayRef<ParsedType> ArgTypes,
1615
210
                                ArrayRef<Expr *> ArgExprs) {
1616
210
  unsigned NumAssocs = ArgTypes.size();
1617
210
  assert(NumAssocs == ArgExprs.size());
1618
1619
0
  TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1620
665
  for (unsigned i = 0; i < NumAssocs; 
++i455
) {
1621
455
    if (ArgTypes[i])
1622
355
      (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1623
100
    else
1624
100
      Types[i] = nullptr;
1625
455
  }
1626
1627
210
  ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1628
210
                                             ControllingExpr,
1629
210
                                             llvm::makeArrayRef(Types, NumAssocs),
1630
210
                                             ArgExprs);
1631
210
  delete [] Types;
1632
210
  return ER;
1633
210
}
1634
1635
ExprResult
1636
Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1637
                                 SourceLocation DefaultLoc,
1638
                                 SourceLocation RParenLoc,
1639
                                 Expr *ControllingExpr,
1640
                                 ArrayRef<TypeSourceInfo *> Types,
1641
227
                                 ArrayRef<Expr *> Exprs) {
1642
227
  unsigned NumAssocs = Types.size();
1643
227
  assert(NumAssocs == Exprs.size());
1644
1645
  // Decay and strip qualifiers for the controlling expression type, and handle
1646
  // placeholder type replacement. See committee discussion from WG14 DR423.
1647
0
  {
1648
227
    EnterExpressionEvaluationContext Unevaluated(
1649
227
        *this, Sema::ExpressionEvaluationContext::Unevaluated);
1650
227
    ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1651
227
    if (R.isInvalid())
1652
0
      return ExprError();
1653
227
    ControllingExpr = R.get();
1654
227
  }
1655
1656
0
  bool TypeErrorFound = false,
1657
227
       IsResultDependent = ControllingExpr->isTypeDependent(),
1658
227
       ContainsUnexpandedParameterPack
1659
227
         = ControllingExpr->containsUnexpandedParameterPack();
1660
1661
  // The controlling expression is an unevaluated operand, so side effects are
1662
  // likely unintended.
1663
227
  if (!inTemplateInstantiation() && 
!IsResultDependent210
&&
1664
227
      
ControllingExpr->HasSideEffects(Context, false)196
)
1665
5
    Diag(ControllingExpr->getExprLoc(),
1666
5
         diag::warn_side_effects_unevaluated_context);
1667
1668
737
  for (unsigned i = 0; i < NumAssocs; 
++i510
) {
1669
510
    if (Exprs[i]->containsUnexpandedParameterPack())
1670
0
      ContainsUnexpandedParameterPack = true;
1671
1672
510
    if (Types[i]) {
1673
410
      if (Types[i]->getType()->containsUnexpandedParameterPack())
1674
0
        ContainsUnexpandedParameterPack = true;
1675
1676
410
      if (Types[i]->getType()->isDependentType()) {
1677
2
        IsResultDependent = true;
1678
408
      } else {
1679
        // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1680
        // complete object type other than a variably modified type."
1681
408
        unsigned D = 0;
1682
408
        if (Types[i]->getType()->isIncompleteType())
1683
2
          D = diag::err_assoc_type_incomplete;
1684
406
        else if (!Types[i]->getType()->isObjectType())
1685
2
          D = diag::err_assoc_type_nonobject;
1686
404
        else if (Types[i]->getType()->isVariablyModifiedType())
1687
2
          D = diag::err_assoc_type_variably_modified;
1688
402
        else {
1689
          // Because the controlling expression undergoes lvalue conversion,
1690
          // array conversion, and function conversion, an association which is
1691
          // of array type, function type, or is qualified can never be
1692
          // reached. We will warn about this so users are less surprised by
1693
          // the unreachable association. However, we don't have to handle
1694
          // function types; that's not an object type, so it's handled above.
1695
402
          unsigned Reason = 0;
1696
402
          QualType QT = Types[i]->getType();
1697
402
          if (QT->isArrayType())
1698
2
            Reason = 1;
1699
400
          else if (QT.hasQualifiers())
1700
4
            Reason = 2;
1701
1702
402
          if (Reason)
1703
6
            Diag(Types[i]->getTypeLoc().getBeginLoc(),
1704
6
                 diag::warn_unreachable_association)
1705
6
                << QT << (Reason - 1);
1706
402
        }
1707
1708
408
        if (D != 0) {
1709
6
          Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1710
6
            << Types[i]->getTypeLoc().getSourceRange()
1711
6
            << Types[i]->getType();
1712
6
          TypeErrorFound = true;
1713
6
        }
1714
1715
        // C11 6.5.1.1p2 "No two generic associations in the same generic
1716
        // selection shall specify compatible types."
1717
799
        for (unsigned j = i+1; j < NumAssocs; 
++j391
)
1718
391
          if (Types[j] && 
!Types[j]->getType()->isDependentType()300
&&
1719
391
              Context.typesAreCompatible(Types[i]->getType(),
1720
296
                                         Types[j]->getType())) {
1721
8
            Diag(Types[j]->getTypeLoc().getBeginLoc(),
1722
8
                 diag::err_assoc_compatible_types)
1723
8
              << Types[j]->getTypeLoc().getSourceRange()
1724
8
              << Types[j]->getType()
1725
8
              << Types[i]->getType();
1726
8
            Diag(Types[i]->getTypeLoc().getBeginLoc(),
1727
8
                 diag::note_compat_assoc)
1728
8
              << Types[i]->getTypeLoc().getSourceRange()
1729
8
              << Types[i]->getType();
1730
8
            TypeErrorFound = true;
1731
8
          }
1732
408
      }
1733
410
    }
1734
510
  }
1735
227
  if (TypeErrorFound)
1736
10
    return ExprError();
1737
1738
  // If we determined that the generic selection is result-dependent, don't
1739
  // try to compute the result expression.
1740
217
  if (IsResultDependent)
1741
13
    return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1742
13
                                        Exprs, DefaultLoc, RParenLoc,
1743
13
                                        ContainsUnexpandedParameterPack);
1744
1745
204
  SmallVector<unsigned, 1> CompatIndices;
1746
204
  unsigned DefaultIndex = -1U;
1747
663
  for (unsigned i = 0; i < NumAssocs; 
++i459
) {
1748
459
    if (!Types[i])
1749
95
      DefaultIndex = i;
1750
364
    else if (Context.typesAreCompatible(ControllingExpr->getType(),
1751
364
                                        Types[i]->getType()))
1752
181
      CompatIndices.push_back(i);
1753
459
  }
1754
1755
  // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1756
  // type compatible with at most one of the types named in its generic
1757
  // association list."
1758
204
  if (CompatIndices.size() > 1) {
1759
    // We strip parens here because the controlling expression is typically
1760
    // parenthesized in macro definitions.
1761
2
    ControllingExpr = ControllingExpr->IgnoreParens();
1762
2
    Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1763
2
        << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1764
2
        << (unsigned)CompatIndices.size();
1765
4
    for (unsigned I : CompatIndices) {
1766
4
      Diag(Types[I]->getTypeLoc().getBeginLoc(),
1767
4
           diag::note_compat_assoc)
1768
4
        << Types[I]->getTypeLoc().getSourceRange()
1769
4
        << Types[I]->getType();
1770
4
    }
1771
2
    return ExprError();
1772
2
  }
1773
1774
  // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1775
  // its controlling expression shall have type compatible with exactly one of
1776
  // the types named in its generic association list."
1777
202
  if (DefaultIndex == -1U && 
CompatIndices.size() == 0107
) {
1778
    // We strip parens here because the controlling expression is typically
1779
    // parenthesized in macro definitions.
1780
3
    ControllingExpr = ControllingExpr->IgnoreParens();
1781
3
    Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1782
3
        << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1783
3
    return ExprError();
1784
3
  }
1785
1786
  // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1787
  // type name that is compatible with the type of the controlling expression,
1788
  // then the result expression of the generic selection is the expression
1789
  // in that generic association. Otherwise, the result expression of the
1790
  // generic selection is the expression in the default generic association."
1791
199
  unsigned ResultIndex =
1792
199
    CompatIndices.size() ? 
CompatIndices[0]177
:
DefaultIndex22
;
1793
1794
199
  return GenericSelectionExpr::Create(
1795
199
      Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1796
199
      ContainsUnexpandedParameterPack, ResultIndex);
1797
202
}
1798
1799
/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1800
/// location of the token and the offset of the ud-suffix within it.
1801
static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1802
376
                                     unsigned Offset) {
1803
376
  return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1804
376
                                        S.getLangOpts());
1805
376
}
1806
1807
/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1808
/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1809
static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1810
                                                 IdentifierInfo *UDSuffix,
1811
                                                 SourceLocation UDSuffixLoc,
1812
                                                 ArrayRef<Expr*> Args,
1813
57
                                                 SourceLocation LitEndLoc) {
1814
57
  assert(Args.size() <= 2 && "too many arguments for literal operator");
1815
1816
0
  QualType ArgTy[2];
1817
114
  for (unsigned ArgIdx = 0; ArgIdx != Args.size(); 
++ArgIdx57
) {
1818
57
    ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1819
57
    if (ArgTy[ArgIdx]->isArrayType())
1820
0
      ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1821
57
  }
1822
1823
57
  DeclarationName OpName =
1824
57
    S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1825
57
  DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1826
57
  OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1827
1828
57
  LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1829
57
  if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1830
57
                              /*AllowRaw*/ false, /*AllowTemplate*/ false,
1831
57
                              /*AllowStringTemplatePack*/ false,
1832
57
                              /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1833
10
    return ExprError();
1834
1835
47
  return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1836
57
}
1837
1838
/// ActOnStringLiteral - The specified tokens were lexed as pasted string
1839
/// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1840
/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1841
/// multiple tokens.  However, the common case is that StringToks points to one
1842
/// string.
1843
///
1844
ExprResult
1845
3.97M
Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1846
3.97M
  assert(!StringToks.empty() && "Must have at least one string!");
1847
1848
0
  StringLiteralParser Literal(StringToks, PP);
1849
3.97M
  if (Literal.hadError)
1850
104
    return ExprError();
1851
1852
3.97M
  SmallVector<SourceLocation, 4> StringTokLocs;
1853
3.97M
  for (const Token &Tok : StringToks)
1854
4.14M
    StringTokLocs.push_back(Tok.getLocation());
1855
1856
3.97M
  QualType CharTy = Context.CharTy;
1857
3.97M
  StringLiteral::StringKind Kind = StringLiteral::Ascii;
1858
3.97M
  if (Literal.isWide()) {
1859
1.11k
    CharTy = Context.getWideCharType();
1860
1.11k
    Kind = StringLiteral::Wide;
1861
3.97M
  } else if (Literal.isUTF8()) {
1862
297
    if (getLangOpts().Char8)
1863
213
      CharTy = Context.Char8Ty;
1864
297
    Kind = StringLiteral::UTF8;
1865
3.97M
  } else if (Literal.isUTF16()) {
1866
144
    CharTy = Context.Char16Ty;
1867
144
    Kind = StringLiteral::UTF16;
1868
3.97M
  } else if (Literal.isUTF32()) {
1869
140
    CharTy = Context.Char32Ty;
1870
140
    Kind = StringLiteral::UTF32;
1871
3.97M
  } else if (Literal.isPascal()) {
1872
11
    CharTy = Context.UnsignedCharTy;
1873
11
  }
1874
1875
  // Warn on initializing an array of char from a u8 string literal; this
1876
  // becomes ill-formed in C++2a.
1877
3.97M
  if (getLangOpts().CPlusPlus && 
!getLangOpts().CPlusPlus201.85M
&&
1878
3.97M
      
!getLangOpts().Char81.84M
&&
Kind == StringLiteral::UTF81.84M
) {
1879
63
    Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string);
1880
1881
    // Create removals for all 'u8' prefixes in the string literal(s). This
1882
    // ensures C++2a compatibility (but may change the program behavior when
1883
    // built by non-Clang compilers for which the execution character set is
1884
    // not always UTF-8).
1885
63
    auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8);
1886
63
    SourceLocation RemovalDiagLoc;
1887
66
    for (const Token &Tok : StringToks) {
1888
66
      if (Tok.getKind() == tok::utf8_string_literal) {
1889
65
        if (RemovalDiagLoc.isInvalid())
1890
63
          RemovalDiagLoc = Tok.getLocation();
1891
65
        RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1892
65
            Tok.getLocation(),
1893
65
            Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1894
65
                                           getSourceManager(), getLangOpts())));
1895
65
      }
1896
66
    }
1897
63
    Diag(RemovalDiagLoc, RemovalDiag);
1898
63
  }
1899
1900
3.97M
  QualType StrTy =
1901
3.97M
      Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1902
1903
  // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1904
3.97M
  StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1905
3.97M
                                             Kind, Literal.Pascal, StrTy,
1906
3.97M
                                             &StringTokLocs[0],
1907
3.97M
                                             StringTokLocs.size());
1908
3.97M
  if (Literal.getUDSuffix().empty())
1909
3.97M
    return Lit;
1910
1911
  // We're building a user-defined literal.
1912
106
  IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1913
106
  SourceLocation UDSuffixLoc =
1914
106
    getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1915
106
                   Literal.getUDSuffixOffset());
1916
1917
  // Make sure we're allowed user-defined literals here.
1918
106
  if (!UDLScope)
1919
6
    return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1920
1921
  // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1922
  //   operator "" X (str, len)
1923
100
  QualType SizeType = Context.getSizeType();
1924
1925
100
  DeclarationName OpName =
1926
100
    Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1927
100
  DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1928
100
  OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1929
1930
100
  QualType ArgTy[] = {
1931
100
    Context.getArrayDecayedType(StrTy), SizeType
1932
100
  };
1933
1934
100
  LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1935
100
  switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1936
100
                                /*AllowRaw*/ false, /*AllowTemplate*/ true,
1937
100
                                /*AllowStringTemplatePack*/ true,
1938
100
                                /*DiagnoseMissing*/ true, Lit)) {
1939
1940
60
  case LOLR_Cooked: {
1941
60
    llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1942
60
    IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1943
60
                                                    StringTokLocs[0]);
1944
60
    Expr *Args[] = { Lit, LenArg };
1945
1946
60
    return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1947
0
  }
1948
1949
9
  case LOLR_Template: {
1950
9
    TemplateArgumentListInfo ExplicitArgs;
1951
9
    TemplateArgument Arg(Lit);
1952
9
    TemplateArgumentLocInfo ArgInfo(Lit);
1953
9
    ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1954
9
    return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1955
9
                                    &ExplicitArgs);
1956
0
  }
1957
1958
13
  case LOLR_StringTemplatePack: {
1959
13
    TemplateArgumentListInfo ExplicitArgs;
1960
1961
13
    unsigned CharBits = Context.getIntWidth(CharTy);
1962
13
    bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1963
13
    llvm::APSInt Value(CharBits, CharIsUnsigned);
1964
1965
13
    TemplateArgument TypeArg(CharTy);
1966
13
    TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1967
13
    ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1968
1969
129
    for (unsigned I = 0, N = Lit->getLength(); I != N; 
++I116
) {
1970
116
      Value = Lit->getCodeUnit(I);
1971
116
      TemplateArgument Arg(Context, Value, CharTy);
1972
116
      TemplateArgumentLocInfo ArgInfo;
1973
116
      ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1974
116
    }
1975
13
    return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1976
13
                                    &ExplicitArgs);
1977
0
  }
1978
0
  case LOLR_Raw:
1979
0
  case LOLR_ErrorNoDiagnostic:
1980
0
    llvm_unreachable("unexpected literal operator lookup result");
1981
18
  case LOLR_Error:
1982
18
    return ExprError();
1983
100
  }
1984
0
  llvm_unreachable("unexpected literal operator lookup result");
1985
0
}
1986
1987
DeclRefExpr *
1988
Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1989
                       SourceLocation Loc,
1990
38.9k
                       const CXXScopeSpec *SS) {
1991
38.9k
  DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1992
38.9k
  return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1993
38.9k
}
1994
1995
DeclRefExpr *
1996
Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1997
                       const DeclarationNameInfo &NameInfo,
1998
                       const CXXScopeSpec *SS, NamedDecl *FoundD,
1999
                       SourceLocation TemplateKWLoc,
2000
16.2M
                       const TemplateArgumentListInfo *TemplateArgs) {
2001
16.2M
  NestedNameSpecifierLoc NNS =
2002
16.2M
      SS ? 
SS->getWithLocInContext(Context)16.1M
:
NestedNameSpecifierLoc()39.3k
;
2003
16.2M
  return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
2004
16.2M
                          TemplateArgs);
2005
16.2M
}
2006
2007
// CUDA/HIP: Check whether a captured reference variable is referencing a
2008
// host variable in a device or host device lambda.
2009
static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S,
2010
862k
                                                            VarDecl *VD) {
2011
862k
  if (!S.getLangOpts().CUDA || 
!VD->hasInit()148
)
2012
861k
    return false;
2013
112
  assert(VD->getType()->isReferenceType());
2014
2015
  // Check whether the reference variable is referencing a host variable.
2016
0
  auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
2017
112
  if (!DRE)
2018
0
    return false;
2019
112
  auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
2020
112
  if (!Referee || !Referee->hasGlobalStorage() ||
2021
112
      Referee->hasAttr<CUDADeviceAttr>())
2022
26
    return false;
2023
2024
  // Check whether the current function is a device or host device lambda.
2025
  // Check whether the reference variable is a capture by getDeclContext()
2026
  // since refersToEnclosingVariableOrCapture() is not ready at this point.
2027
86
  auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
2028
86
  if (MD && 
MD->getParent()->isLambda()32
&&
2029
86
      
MD->getOverloadedOperator() == OO_Call32
&&
MD->hasAttr<CUDADeviceAttr>()32
&&
2030
86
      
VD->getDeclContext() != MD32
)
2031
12
    return true;
2032
2033
74
  return false;
2034
86
}
2035
2036
18.1M
NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
2037
  // A declaration named in an unevaluated operand never constitutes an odr-use.
2038
18.1M
  if (isUnevaluatedContext())
2039
148k
    return NOUR_Unevaluated;
2040
2041
  // C++2a [basic.def.odr]p4:
2042
  //   A variable x whose name appears as a potentially-evaluated expression e
2043
  //   is odr-used by e unless [...] x is a reference that is usable in
2044
  //   constant expressions.
2045
  // CUDA/HIP:
2046
  //   If a reference variable referencing a host variable is captured in a
2047
  //   device or host device lambda, the value of the referee must be copied
2048
  //   to the capture and the reference variable must be treated as odr-use
2049
  //   since the value of the referee is not known at compile time and must
2050
  //   be loaded from the captured.
2051
17.9M
  if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2052
12.6M
    if (VD->getType()->isReferenceType() &&
2053
12.6M
        
!(881k
getLangOpts().OpenMP881k
&&
isOpenMPCapturedDecl(D)51.2k
) &&
2054
12.6M
        
!isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD)862k
&&
2055
12.6M
        
VD->isUsableInConstantExpressions(Context)861k
)
2056
3.18k
      return NOUR_Constant;
2057
12.6M
  }
2058
2059
  // All remaining non-variable cases constitute an odr-use. For variables, we
2060
  // need to wait and see how the expression is used.
2061
17.9M
  return NOUR_None;
2062
17.9M
}
2063
2064
/// BuildDeclRefExpr - Build an expression that references a
2065
/// declaration that does not require a closure capture.
2066
DeclRefExpr *
2067
Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2068
                       const DeclarationNameInfo &NameInfo,
2069
                       NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2070
                       SourceLocation TemplateKWLoc,
2071
16.9M
                       const TemplateArgumentListInfo *TemplateArgs) {
2072
16.9M
  bool RefersToCapturedVariable =
2073
16.9M
      isa<VarDecl>(D) &&
2074
16.9M
      
NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc())12.6M
;
2075
2076
16.9M
  DeclRefExpr *E = DeclRefExpr::Create(
2077
16.9M
      Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2078
16.9M
      VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2079
16.9M
  MarkDeclRefReferenced(E);
2080
2081
  // C++ [except.spec]p17:
2082
  //   An exception-specification is considered to be needed when:
2083
  //   - in an expression, the function is the unique lookup result or
2084
  //     the selected member of a set of overloaded functions.
2085
  //
2086
  // We delay doing this until after we've built the function reference and
2087
  // marked it as used so that:
2088
  //  a) if the function is defaulted, we get errors from defining it before /
2089
  //     instead of errors from computing its exception specification, and
2090
  //  b) if the function is a defaulted comparison, we can use the body we
2091
  //     build when defining it as input to the exception specification
2092
  //     computation rather than computing a new body.
2093
16.9M
  if (auto *FPT = Ty->getAs<FunctionProtoType>()) {
2094
1.66M
    if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2095
1.58k
      if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2096
1.58k
        E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
2097
1.58k
    }
2098
1.66M
  }
2099
2100
16.9M
  if (getLangOpts().ObjCWeak && 
isa<VarDecl>(D)33.7k
&&
2101
16.9M
      
Ty.getObjCLifetime() == Qualifiers::OCL_Weak19.4k
&&
!isUnevaluatedContext()290
&&
2102
16.9M
      
!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())283
)
2103
26
    getCurFunction()->recordUseOfWeak(E);
2104
2105
16.9M
  FieldDecl *FD = dyn_cast<FieldDecl>(D);
2106
16.9M
  if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
2107
40
    FD = IFD->getAnonField();
2108
16.9M
  if (FD) {
2109
995
    UnusedPrivateFields.remove(FD);
2110
    // Just in case we're building an illegal pointer-to-member.
2111
995
    if (FD->isBitField())
2112
2
      E->setObjectKind(OK_BitField);
2113
995
  }
2114
2115
  // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2116
  // designates a bit-field.
2117
16.9M
  if (auto *BD = dyn_cast<BindingDecl>(D))
2118
563
    if (auto *BE = BD->getBinding())
2119
529
      E->setObjectKind(BE->getObjectKind());
2120
2121
16.9M
  return E;
2122
16.9M
}
2123
2124
/// Decomposes the given name into a DeclarationNameInfo, its location, and
2125
/// possibly a list of template arguments.
2126
///
2127
/// If this produces template arguments, it is permitted to call
2128
/// DecomposeTemplateName.
2129
///
2130
/// This actually loses a lot of source location information for
2131
/// non-standard name kinds; we should consider preserving that in
2132
/// some way.
2133
void
2134
Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
2135
                             TemplateArgumentListInfo &Buffer,
2136
                             DeclarationNameInfo &NameInfo,
2137
15.2M
                             const TemplateArgumentListInfo *&TemplateArgs) {
2138
15.2M
  if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2139
176k
    Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2140
176k
    Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2141
2142
176k
    ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2143
176k
                                       Id.TemplateId->NumArgs);
2144
176k
    translateTemplateArguments(TemplateArgsPtr, Buffer);
2145
2146
176k
    TemplateName TName = Id.TemplateId->Template.get();
2147
176k
    SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2148
176k
    NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2149
176k
    TemplateArgs = &Buffer;
2150
15.0M
  } else {
2151
15.0M
    NameInfo = GetNameFromUnqualifiedId(Id);
2152
15.0M
    TemplateArgs = nullptr;
2153
15.0M
  }
2154
15.2M
}
2155
2156
static void emitEmptyLookupTypoDiagnostic(
2157
    const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2158
    DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2159
3.16k
    unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2160
3.16k
  DeclContext *Ctx =
2161
3.16k
      SS.isEmpty() ? 
nullptr3.03k
:
SemaRef.computeDeclContext(SS, false)130
;
2162
3.16k
  if (!TC) {
2163
    // Emit a special diagnostic for failed member lookups.
2164
    // FIXME: computing the declaration context might fail here (?)
2165
2.87k
    if (Ctx)
2166
48
      SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2167
48
                                                 << SS.getRange();
2168
2.82k
    else
2169
2.82k
      SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2170
2.87k
    return;
2171
2.87k
  }
2172
2173
298
  std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2174
298
  bool DroppedSpecifier =
2175
298
      TC.WillReplaceSpecifier() && 
Typo.getAsString() == CorrectedStr97
;
2176
298
  unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2177
298
                        ? 
diag::note_implicit_param_decl1
2178
298
                        : 
diag::note_previous_decl297
;
2179
298
  if (!Ctx)
2180
216
    SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2181
216
                         SemaRef.PDiag(NoteID));
2182
82
  else
2183
82
    SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2184
82
                                 << Typo << Ctx << DroppedSpecifier
2185
82
                                 << SS.getRange(),
2186
82
                         SemaRef.PDiag(NoteID));
2187
298
}
2188
2189
/// Diagnose a lookup that found results in an enclosing class during error
2190
/// recovery. This usually indicates that the results were found in a dependent
2191
/// base class that could not be searched as part of a template definition.
2192
/// Always issues a diagnostic (though this may be only a warning in MS
2193
/// compatibility mode).
2194
///
2195
/// Return \c true if the error is unrecoverable, or \c false if the caller
2196
/// should attempt to recover using these lookup results.
2197
37
bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) {
2198
  // During a default argument instantiation the CurContext points
2199
  // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2200
  // function parameter list, hence add an explicit check.
2201
37
  bool isDefaultArgument =
2202
37
      !CodeSynthesisContexts.empty() &&
2203
37
      CodeSynthesisContexts.back().Kind ==
2204
37
          CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2205
37
  CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2206
37
  bool isInstance = CurMethod && 
CurMethod->isInstance()35
&&
2207
37
                    
R.getNamingClass() == CurMethod->getParent()31
&&
2208
37
                    
!isDefaultArgument4
;
2209
2210
  // There are two ways we can find a class-scope declaration during template
2211
  // instantiation that we did not find in the template definition: if it is a
2212
  // member of a dependent base class, or if it is declared after the point of
2213
  // use in the same class. Distinguish these by comparing the class in which
2214
  // the member was found to the naming class of the lookup.
2215
37
  unsigned DiagID = diag::err_found_in_dependent_base;
2216
37
  unsigned NoteID = diag::note_member_declared_at;
2217
37
  if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) {
2218
4
    DiagID = getLangOpts().MSVCCompat ? 
diag::ext_found_later_in_class0
2219
4
                                      : diag::err_found_later_in_class;
2220
33
  } else if (getLangOpts().MSVCCompat) {
2221
23
    DiagID = diag::ext_found_in_dependent_base;
2222
23
    NoteID = diag::note_dependent_member_use;
2223
23
  }
2224
2225
37
  if (isInstance) {
2226
    // Give a code modification hint to insert 'this->'.
2227
4
    Diag(R.getNameLoc(), DiagID)
2228
4
        << R.getLookupName()
2229
4
        << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2230
4
    CheckCXXThisCapture(R.getNameLoc());
2231
33
  } else {
2232
    // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2233
    // they're not shadowed).
2234
33
    Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2235
33
  }
2236
2237
37
  for (NamedDecl *D : R)
2238
37
    Diag(D->getLocation(), NoteID);
2239
2240
  // Return true if we are inside a default argument instantiation
2241
  // and the found name refers to an instance member function, otherwise
2242
  // the caller will try to create an implicit member call and this is wrong
2243
  // for default arguments.
2244
  //
2245
  // FIXME: Is this special case necessary? We could allow the caller to
2246
  // diagnose this.
2247
37
  if (isDefaultArgument && 
((*R.begin())->isCXXInstanceMember())4
) {
2248
2
    Diag(R.getNameLoc(), diag::err_member_call_without_object);
2249
2
    return true;
2250
2
  }
2251
2252
  // Tell the callee to try to recover.
2253
35
  return false;
2254
37
}
2255
2256
/// Diagnose an empty lookup.
2257
///
2258
/// \return false if new lookup candidates were found
2259
bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2260
                               CorrectionCandidateCallback &CCC,
2261
                               TemplateArgumentListInfo *ExplicitTemplateArgs,
2262
8.11k
                               ArrayRef<Expr *> Args, TypoExpr **Out) {
2263
8.11k
  DeclarationName Name = R.getLookupName();
2264
2265
8.11k
  unsigned diagnostic = diag::err_undeclared_var_use;
2266
8.11k
  unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2267
8.11k
  if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2268
8.11k
      
Name.getNameKind() == DeclarationName::CXXLiteralOperatorName8.10k
||
2269
8.11k
      
Name.getNameKind() == DeclarationName::CXXConversionFunctionName8.10k
) {
2270
10
    diagnostic = diag::err_undeclared_use;
2271
10
    diagnostic_suggest = diag::err_undeclared_use_suggest;
2272
10
  }
2273
2274
  // If the original lookup was an unqualified lookup, fake an
2275
  // unqualified lookup.  This is useful when (for example) the
2276
  // original lookup would not have found something because it was a
2277
  // dependent name.
2278
8.11k
  DeclContext *DC = SS.isEmpty() ? 
CurContext7.83k
:
nullptr278
;
2279
26.0k
  while (DC) {
2280
17.9k
    if (isa<CXXRecordDecl>(DC)) {
2281
387
      LookupQualifiedName(R, DC);
2282
2283
387
      if (!R.empty()) {
2284
        // Don't give errors about ambiguities in this lookup.
2285
35
        R.suppressDiagnostics();
2286
2287
        // If there's a best viable function among the results, only mention
2288
        // that one in the notes.
2289
35
        OverloadCandidateSet Candidates(R.getNameLoc(),
2290
35
                                        OverloadCandidateSet::CSK_Normal);
2291
35
        AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2292
35
        OverloadCandidateSet::iterator Best;
2293
35
        if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2294
35
            OR_Success) {
2295
31
          R.clear();
2296
31
          R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2297
31
          R.resolveKind();
2298
31
        }
2299
2300
35
        return DiagnoseDependentMemberLookup(R);
2301
35
      }
2302
2303
352
      R.clear();
2304
352
    }
2305
2306
17.9k
    DC = DC->getLookupParent();
2307
17.9k
  }
2308
2309
  // We didn't find anything, so try to correct for a typo.
2310
8.07k
  TypoCorrection Corrected;
2311
8.07k
  if (S && 
Out8.05k
) {
2312
4.23k
    SourceLocation TypoLoc = R.getNameLoc();
2313
4.23k
    assert(!ExplicitTemplateArgs &&
2314
4.23k
           "Diagnosing an empty lookup with explicit template args!");
2315
0
    *Out = CorrectTypoDelayed(
2316
4.23k
        R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2317
4.23k
        [=](const TypoCorrection &TC) {
2318
3.16k
          emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2319
3.16k
                                        diagnostic, diagnostic_suggest);
2320
3.16k
        },
2321
4.23k
        nullptr, CTK_ErrorRecovery);
2322
4.23k
    if (*Out)
2323
3.16k
      return true;
2324
4.23k
  } else 
if (3.83k
S3.83k
&&
2325
3.83k
             (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2326
3.81k
                                      S, &SS, CCC, CTK_ErrorRecovery))) {
2327
239
    std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2328
239
    bool DroppedSpecifier =
2329
239
        Corrected.WillReplaceSpecifier() && 
Name.getAsString() == CorrectedStr43
;
2330
239
    R.setLookupName(Corrected.getCorrection());
2331
2332
239
    bool AcceptableWithRecovery = false;
2333
239
    bool AcceptableWithoutRecovery = false;
2334
239
    NamedDecl *ND = Corrected.getFoundDecl();
2335
239
    if (ND) {
2336
227
      if (Corrected.isOverloaded()) {
2337
64
        OverloadCandidateSet OCS(R.getNameLoc(),
2338
64
                                 OverloadCandidateSet::CSK_Normal);
2339
64
        OverloadCandidateSet::iterator Best;
2340
816
        for (NamedDecl *CD : Corrected) {
2341
816
          if (FunctionTemplateDecl *FTD =
2342
816
                   dyn_cast<FunctionTemplateDecl>(CD))
2343
20
            AddTemplateOverloadCandidate(
2344
20
                FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2345
20
                Args, OCS);
2346
796
          else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2347
788
            if (!ExplicitTemplateArgs || 
ExplicitTemplateArgs->size() == 00
)
2348
788
              AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2349
788
                                   Args, OCS);
2350
816
        }
2351
64
        switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2352
42
        case OR_Success:
2353
42
          ND = Best->FoundDecl;
2354
42
          Corrected.setCorrectionDecl(ND);
2355
42
          break;
2356
22
        default:
2357
          // FIXME: Arbitrarily pick the first declaration for the note.
2358
22
          Corrected.setCorrectionDecl(ND);
2359
22
          break;
2360
64
        }
2361
64
      }
2362
227
      R.addDecl(ND);
2363
227
      if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2364
8
        CXXRecordDecl *Record = nullptr;
2365
8
        if (Corrected.getCorrectionSpecifier()) {
2366
3
          const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2367
3
          Record = Ty->getAsCXXRecordDecl();
2368
3
        }
2369
8
        if (!Record)
2370
5
          Record = cast<CXXRecordDecl>(
2371
5
              ND->getDeclContext()->getRedeclContext());
2372
8
        R.setNamingClass(Record);
2373
8
      }
2374
2375
227
      auto *UnderlyingND = ND->getUnderlyingDecl();
2376
227
      AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2377
227
                               
isa<FunctionTemplateDecl>(UnderlyingND)34
;
2378
      // FIXME: If we ended up with a typo for a type name or
2379
      // Objective-C class name, we're in trouble because the parser
2380
      // is in the wrong place to recover. Suggest the typo
2381
      // correction, but don't make it a fix-it since we're not going
2382
      // to recover well anyway.
2383
227
      AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2384
227
                                  
getAsTypeTemplateDecl(UnderlyingND)225
||
2385
227
                                  
isa<ObjCInterfaceDecl>(UnderlyingND)212
;
2386
227
    } else {
2387
      // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2388
      // because we aren't able to recover.
2389
12
      AcceptableWithoutRecovery = true;
2390
12
    }
2391
2392
239
    if (AcceptableWithRecovery || 
AcceptableWithoutRecovery27
) {
2393
239
      unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2394
239
                            ? 
diag::note_implicit_param_decl0
2395
239
                            : diag::note_previous_decl;
2396
239
      if (SS.isEmpty())
2397
239
        diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2398
239
                     PDiag(NoteID), AcceptableWithRecovery);
2399
0
      else
2400
0
        diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2401
0
                                  << Name << computeDeclContext(SS, false)
2402
0
                                  << DroppedSpecifier << SS.getRange(),
2403
0
                     PDiag(NoteID), AcceptableWithRecovery);
2404
2405
      // Tell the callee whether to try to recover.
2406
239
      return !AcceptableWithRecovery;
2407
239
    }
2408
239
  }
2409
4.66k
  R.clear();
2410
2411
  // Emit a special diagnostic for failed member lookups.
2412
  // FIXME: computing the declaration context might fail here (?)
2413
4.66k
  if (!SS.isEmpty()) {
2414
148
    Diag(R.getNameLoc(), diag::err_no_member)
2415
148
      << Name << computeDeclContext(SS, false)
2416
148
      << SS.getRange();
2417
148
    return true;
2418
148
  }
2419
2420
  // Give up, we can't recover.
2421
4.52k
  Diag(R.getNameLoc(), diagnostic) << Name;
2422
4.52k
  return true;
2423
4.66k
}
2424
2425
/// In Microsoft mode, if we are inside a template class whose parent class has
2426
/// dependent base classes, and we can't resolve an unqualified identifier, then
2427
/// assume the identifier is a member of a dependent base class.  We can only
2428
/// recover successfully in static methods, instance methods, and other contexts
2429
/// where 'this' is available.  This doesn't precisely match MSVC's
2430
/// instantiation model, but it's close enough.
2431
static Expr *
2432
recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2433
                               DeclarationNameInfo &NameInfo,
2434
                               SourceLocation TemplateKWLoc,
2435
66
                               const TemplateArgumentListInfo *TemplateArgs) {
2436
  // Only try to recover from lookup into dependent bases in static methods or
2437
  // contexts where 'this' is available.
2438
66
  QualType ThisType = S.getCurrentThisType();
2439
66
  const CXXRecordDecl *RD = nullptr;
2440
66
  if (!ThisType.isNull())
2441
30
    RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2442
36
  else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2443
5
    RD = MD->getParent();
2444
66
  if (!RD || 
!RD->hasAnyDependentBases()35
)
2445
40
    return nullptr;
2446
2447
  // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2448
  // is available, suggest inserting 'this->' as a fixit.
2449
26
  SourceLocation Loc = NameInfo.getLoc();
2450
26
  auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2451
26
  DB << NameInfo.getName() << RD;
2452
2453
26
  if (!ThisType.isNull()) {
2454
22
    DB << FixItHint::CreateInsertion(Loc, "this->");
2455
22
    return CXXDependentScopeMemberExpr::Create(
2456
22
        Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2457
22
        /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2458
22
        /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2459
22
  }
2460
2461
  // Synthesize a fake NNS that points to the derived class.  This will
2462
  // perform name lookup during template instantiation.
2463
4
  CXXScopeSpec SS;
2464
4
  auto *NNS =
2465
4
      NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2466
4
  SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2467
4
  return DependentScopeDeclRefExpr::Create(
2468
4
      Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2469
4
      TemplateArgs);
2470
26
}
2471
2472
ExprResult
2473
Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2474
                        SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2475
                        bool HasTrailingLParen, bool IsAddressOfOperand,
2476
                        CorrectionCandidateCallback *CCC,
2477
14.0M
                        bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2478
14.0M
  assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2479
14.0M
         "cannot be direct & operand and have a trailing lparen");
2480
14.0M
  if (SS.isInvalid())
2481
202
    return ExprError();
2482
2483
14.0M
  TemplateArgumentListInfo TemplateArgsBuffer;
2484
2485
  // Decompose the UnqualifiedId into the following data.
2486
14.0M
  DeclarationNameInfo NameInfo;
2487
14.0M
  const TemplateArgumentListInfo *TemplateArgs;
2488
14.0M
  DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2489
2490
14.0M
  DeclarationName Name = NameInfo.getName();
2491
14.0M
  IdentifierInfo *II = Name.getAsIdentifierInfo();
2492
14.0M
  SourceLocation NameLoc = NameInfo.getLoc();
2493
2494
14.0M
  if (II && 
II->isEditorPlaceholder()14.0M
) {
2495
    // FIXME: When typed placeholders are supported we can create a typed
2496
    // placeholder expression node.
2497
16
    return ExprError();
2498
16
  }
2499
2500
  // C++ [temp.dep.expr]p3:
2501
  //   An id-expression is type-dependent if it contains:
2502
  //     -- an identifier that was declared with a dependent type,
2503
  //        (note: handled after lookup)
2504
  //     -- a template-id that is dependent,
2505
  //        (note: handled in BuildTemplateIdExpr)
2506
  //     -- a conversion-function-id that specifies a dependent type,
2507
  //     -- a nested-name-specifier that contains a class-name that
2508
  //        names a dependent type.
2509
  // Determine whether this is a member of an unknown specialization;
2510
  // we need to handle these differently.
2511
14.0M
  bool DependentID = false;
2512
14.0M
  if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2513
14.0M
      
Name.getCXXNameType()->isDependentType()30
) {
2514
6
    DependentID = true;
2515
14.0M
  } else if (SS.isSet()) {
2516
1.04M
    if (DeclContext *DC = computeDeclContext(SS, false)) {
2517
385k
      if (RequireCompleteDeclContext(SS, DC))
2518
2
        return ExprError();
2519
656k
    } else {
2520
656k
      DependentID = true;
2521
656k
    }
2522
1.04M
  }
2523
2524
14.0M
  if (DependentID)
2525
656k
    return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2526
656k
                                      IsAddressOfOperand, TemplateArgs);
2527
2528
  // Perform the required lookup.
2529
13.3M
  LookupResult R(*this, NameInfo,
2530
13.3M
                 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2531
13.3M
                     ? 
LookupObjCImplicitSelfParam2.17k
2532
13.3M
                     : 
LookupOrdinaryName13.3M
);
2533
13.3M
  if (TemplateKWLoc.isValid() || 
TemplateArgs13.3M
) {
2534
    // Lookup the template name again to correctly establish the context in
2535
    // which it was found. This is really unfortunate as we already did the
2536
    // lookup to determine that it was a template name in the first place. If
2537
    // this becomes a performance hit, we can work harder to preserve those
2538
    // results until we get here but it's likely not worth it.
2539
166k
    bool MemberOfUnknownSpecialization;
2540
166k
    AssumedTemplateKind AssumedTemplate;
2541
166k
    if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2542
166k
                           MemberOfUnknownSpecialization, TemplateKWLoc,
2543
166k
                           &AssumedTemplate))
2544
0
      return ExprError();
2545
2546
166k
    if (MemberOfUnknownSpecialization ||
2547
166k
        (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2548
0
      return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2549
0
                                        IsAddressOfOperand, TemplateArgs);
2550
13.2M
  } else {
2551
13.2M
    bool IvarLookupFollowUp = II && 
!SS.isSet()13.2M
&&
getCurMethodDecl()12.9M
;
2552
13.2M
    LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2553
2554
    // If the result might be in a dependent base class, this is a dependent
2555
    // id-expression.
2556
13.2M
    if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2557
12
      return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2558
12
                                        IsAddressOfOperand, TemplateArgs);
2559
2560
    // If this reference is in an Objective-C method, then we need to do
2561
    // some special Objective-C lookup, too.
2562
13.2M
    if (IvarLookupFollowUp) {
2563
10.4k
      ExprResult E(LookupInObjCMethod(R, S, II, true));
2564
10.4k
      if (E.isInvalid())
2565
5
        return ExprError();
2566
2567
10.4k
      if (Expr *Ex = E.getAs<Expr>())
2568
1.24k
        return Ex;
2569
10.4k
    }
2570
13.2M
  }
2571
2572
13.3M
  if (R.isAmbiguous())
2573
56
    return ExprError();
2574
2575
  // This could be an implicitly declared function reference if the language
2576
  // mode allows it as a feature.
2577
13.3M
  if (R.empty() && 
HasTrailingLParen8.55k
&&
II4.57k
&&
2578
13.3M
      
getLangOpts().implicitFunctionsAllowed()4.54k
) {
2579
309
    NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2580
309
    if (D) R.addDecl(D);
2581
309
  }
2582
2583
  // Determine whether this name might be a candidate for
2584
  // argument-dependent lookup.
2585
13.3M
  bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2586
2587
13.3M
  if (R.empty() && 
!ADL8.24k
) {
2588
4.28k
    if (SS.isEmpty() && 
getLangOpts().MSVCCompat4.00k
) {
2589
66
      if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2590
66
                                                   TemplateKWLoc, TemplateArgs))
2591
26
        return E;
2592
66
    }
2593
2594
    // Don't diagnose an empty lookup for inline assembly.
2595
4.25k
    if (IsInlineAsmIdentifier)
2596
20
      return ExprError();
2597
2598
    // If this name wasn't predeclared and if this is not a function
2599
    // call, diagnose the problem.
2600
4.23k
    TypoExpr *TE = nullptr;
2601
4.23k
    DefaultFilterCCC DefaultValidator(II, SS.isValid() ? 
SS.getScopeRep()278
2602
4.23k
                                                       : 
nullptr3.96k
);
2603
4.23k
    DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2604
4.23k
    assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2605
4.23k
           "Typo correction callback misconfigured");
2606
4.23k
    if (CCC) {
2607
      // Make sure the callback knows what the typo being diagnosed is.
2608
3.95k
      CCC->setTypoName(II);
2609
3.95k
      if (SS.isValid())
2610
0
        CCC->setTypoNNS(SS.getScopeRep());
2611
3.95k
    }
2612
    // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2613
    // a template name, but we happen to have always already looked up the name
2614
    // before we get here if it must be a template name.
2615
4.23k
    if (DiagnoseEmptyLookup(S, SS, R, CCC ? 
*CCC3.95k
:
DefaultValidator283
, nullptr,
2616
4.23k
                            None, &TE)) {
2617
4.23k
      if (TE && 
KeywordReplacement3.16k
) {
2618
2.21k
        auto &State = getTypoExprState(TE);
2619
2.21k
        auto BestTC = State.Consumer->getNextCorrection();
2620
2.21k
        if (BestTC.isKeyword()) {
2621
6
          auto *II = BestTC.getCorrectionAsIdentifierInfo();
2622
6
          if (State.DiagHandler)
2623
6
            State.DiagHandler(BestTC);
2624
6
          KeywordReplacement->startToken();
2625
6
          KeywordReplacement->setKind(II->getTokenID());
2626
6
          KeywordReplacement->setIdentifierInfo(II);
2627
6
          KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2628
          // Clean up the state associated with the TypoExpr, since it has
2629
          // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2630
6
          clearDelayedTypo(TE);
2631
          // Signal that a correction to a keyword was performed by returning a
2632
          // valid-but-null ExprResult.
2633
6
          return (Expr*)nullptr;
2634
6
        }
2635
2.21k
        State.Consumer->resetCorrectionStream();
2636
2.21k
      }
2637
4.23k
      return TE ? 
TE3.16k
:
ExprError()1.07k
;
2638
4.23k
    }
2639
2640
0
    assert(!R.empty() &&
2641
0
           "DiagnoseEmptyLookup returned false but added no results");
2642
2643
    // If we found an Objective-C instance variable, let
2644
    // LookupInObjCMethod build the appropriate expression to
2645
    // reference the ivar.
2646
0
    if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2647
0
      R.clear();
2648
0
      ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2649
      // In a hopelessly buggy code, Objective-C instance variable
2650
      // lookup fails and no expression will be built to reference it.
2651
0
      if (!E.isInvalid() && !E.get())
2652
0
        return ExprError();
2653
0
      return E;
2654
0
    }
2655
0
  }
2656
2657
  // This is guaranteed from this point on.
2658
13.3M
  assert(!R.empty() || ADL);
2659
2660
  // Check whether this might be a C++ implicit instance member access.
2661
  // C++ [class.mfct.non-static]p3:
2662
  //   When an id-expression that is not part of a class member access
2663
  //   syntax and not used to form a pointer to member is used in the
2664
  //   body of a non-static member function of class X, if name lookup
2665
  //   resolves the name in the id-expression to a non-static non-type
2666
  //   member of some class C, the id-expression is transformed into a
2667
  //   class member access expression using (*this) as the
2668
  //   postfix-expression to the left of the . operator.
2669
  //
2670
  // But we don't actually need to do this for '&' operands if R
2671
  // resolved to a function or overloaded function set, because the
2672
  // expression is ill-formed if it actually works out to be a
2673
  // non-static member function:
2674
  //
2675
  // C++ [expr.ref]p4:
2676
  //   Otherwise, if E1.E2 refers to a non-static member function. . .
2677
  //   [t]he expression can be used only as the left-hand operand of a
2678
  //   member function call.
2679
  //
2680
  // There are other safeguards against such uses, but it's important
2681
  // to get this right here so that we don't end up making a
2682
  // spuriously dependent expression if we're inside a dependent
2683
  // instance method.
2684
13.3M
  if (!R.empty() && 
(*R.begin())->isCXXClassMember()13.3M
) {
2685
680k
    bool MightBeImplicitMember;
2686
680k
    if (!IsAddressOfOperand)
2687
657k
      MightBeImplicitMember = true;
2688
22.1k
    else if (!SS.isEmpty())
2689
2.84k
      MightBeImplicitMember = false;
2690
19.3k
    else if (R.isOverloadedResult())
2691
152
      MightBeImplicitMember = false;
2692
19.1k
    else if (R.isUnresolvableResult())
2693
7
      MightBeImplicitMember = true;
2694
19.1k
    else
2695
19.1k
      MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2696
19.1k
                              
isa<IndirectFieldDecl>(R.getFoundDecl())118
||
2697
19.1k
                              
isa<MSPropertyDecl>(R.getFoundDecl())114
;
2698
2699
680k
    if (MightBeImplicitMember)
2700
676k
      return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2701
676k
                                             R, TemplateArgs, S);
2702
680k
  }
2703
2704
12.6M
  if (TemplateArgs || 
TemplateKWLoc.isValid()12.5M
) {
2705
2706
    // In C++1y, if this is a variable template id, then check it
2707
    // in BuildTemplateIdExpr().
2708
    // The single lookup result must be a variable template declaration.
2709
156k
    if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && 
Id.TemplateId156k
&&
2710
156k
        
Id.TemplateId->Kind == TNK_Var_template156k
) {
2711
2.56k
      assert(R.getAsSingle<VarTemplateDecl>() &&
2712
2.56k
             "There should only be one declaration found.");
2713
2.56k
    }
2714
2715
0
    return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2716
156k
  }
2717
2718
12.5M
  return BuildDeclarationNameExpr(SS, R, ADL);
2719
12.6M
}
2720
2721
/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2722
/// declaration name, generally during template instantiation.
2723
/// There's a large number of things which don't need to be done along
2724
/// this path.
2725
ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2726
    CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2727
1.13M
    bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2728
1.13M
  DeclContext *DC = computeDeclContext(SS, false);
2729
1.13M
  if (!DC)
2730
395k
    return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2731
395k
                                     NameInfo, /*TemplateArgs=*/nullptr);
2732
2733
735k
  if (RequireCompleteDeclContext(SS, DC))
2734
14
    return ExprError();
2735
2736
735k
  LookupResult R(*this, NameInfo, LookupOrdinaryName);
2737
735k
  LookupQualifiedName(R, DC);
2738
2739
735k
  if (R.isAmbiguous())
2740
0
    return ExprError();
2741
2742
735k
  if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2743
0
    return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2744
0
                                     NameInfo, /*TemplateArgs=*/nullptr);
2745
2746
735k
  if (R.empty()) {
2747
    // Don't diagnose problems with invalid record decl, the secondary no_member
2748
    // diagnostic during template instantiation is likely bogus, e.g. if a class
2749
    // is invalid because it's derived from an invalid base class, then missing
2750
    // members were likely supposed to be inherited.
2751
201
    if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
2752
200
      if (CD->isInvalidDecl())
2753
2
        return ExprError();
2754
199
    Diag(NameInfo.getLoc(), diag::err_no_member)
2755
199
      << NameInfo.getName() << DC << SS.getRange();
2756
199
    return ExprError();
2757
201
  }
2758
2759
735k
  if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2760
    // Diagnose a missing typename if this resolved unambiguously to a type in
2761
    // a dependent context.  If we can recover with a type, downgrade this to
2762
    // a warning in Microsoft compatibility mode.
2763
38
    unsigned DiagID = diag::err_typename_missing;
2764
38
    if (RecoveryTSI && 
getLangOpts().MSVCCompat3
)
2765
3
      DiagID = diag::ext_typename_missing;
2766
38
    SourceLocation Loc = SS.getBeginLoc();
2767
38
    auto D = Diag(Loc, DiagID);
2768
38
    D << SS.getScopeRep() << NameInfo.getName().getAsString()
2769
38
      << SourceRange(Loc, NameInfo.getEndLoc());
2770
2771
    // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2772
    // context.
2773
38
    if (!RecoveryTSI)
2774
35
      return ExprError();
2775
2776
    // Only issue the fixit if we're prepared to recover.
2777
3
    D << FixItHint::CreateInsertion(Loc, "typename ");
2778
2779
    // Recover by pretending this was an elaborated type.
2780
3
    QualType Ty = Context.getTypeDeclType(TD);
2781
3
    TypeLocBuilder TLB;
2782
3
    TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2783
2784
3
    QualType ET = getElaboratedType(ETK_None, SS, Ty);
2785
3
    ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2786
3
    QTL.setElaboratedKeywordLoc(SourceLocation());
2787
3
    QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2788
2789
3
    *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2790
2791
3
    return ExprEmpty();
2792
38
  }
2793
2794
  // Defend against this resolving to an implicit member access. We usually
2795
  // won't get here if this might be a legitimate a class member (we end up in
2796
  // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2797
  // a pointer-to-member or in an unevaluated context in C++11.
2798
735k
  if (!R.empty() && (*R.begin())->isCXXClassMember() && 
!IsAddressOfOperand735k
)
2799
735k
    return BuildPossibleImplicitMemberExpr(SS,
2800
735k
                                           /*TemplateKWLoc=*/SourceLocation(),
2801
735k
                                           R, /*TemplateArgs=*/nullptr, S);
2802
2803
86
  return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2804
735k
}
2805
2806
/// The parser has read a name in, and Sema has detected that we're currently
2807
/// inside an ObjC method. Perform some additional checks and determine if we
2808
/// should form a reference to an ivar.
2809
///
2810
/// Ideally, most of this would be done by lookup, but there's
2811
/// actually quite a lot of extra work involved.
2812
DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
2813
14.4k
                                        IdentifierInfo *II) {
2814
14.4k
  SourceLocation Loc = Lookup.getNameLoc();
2815
14.4k
  ObjCMethodDecl *CurMethod = getCurMethodDecl();
2816
2817
  // Check for error condition which is already reported.
2818
14.4k
  if (!CurMethod)
2819
0
    return DeclResult(true);
2820
2821
  // There are two cases to handle here.  1) scoped lookup could have failed,
2822
  // in which case we should look for an ivar.  2) scoped lookup could have
2823
  // found a decl, but that decl is outside the current instance method (i.e.
2824
  // a global variable).  In these two cases, we do a lookup for an ivar with
2825
  // this name, if the lookup sucedes, we replace it our current decl.
2826
2827
  // If we're in a class method, we don't normally want to look for
2828
  // ivars.  But if we don't find anything else, and there's an
2829
  // ivar, that's an error.
2830
14.4k
  bool IsClassMethod = CurMethod->isClassMethod();
2831
2832
14.4k
  bool LookForIvars;
2833
14.4k
  if (Lookup.empty())
2834
2.16k
    LookForIvars = true;
2835
12.2k
  else if (IsClassMethod)
2836
929
    LookForIvars = false;
2837
11.3k
  else
2838
11.3k
    LookForIvars = (Lookup.isSingleResult() &&
2839
11.3k
                    
Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()11.3k
);
2840
14.4k
  ObjCInterfaceDecl *IFace = nullptr;
2841
14.4k
  if (LookForIvars) {
2842
3.90k
    IFace = CurMethod->getClassInterface();
2843
3.90k
    ObjCInterfaceDecl *ClassDeclared;
2844
3.90k
    ObjCIvarDecl *IV = nullptr;
2845
3.90k
    if (IFace && 
(IV = IFace->lookupInstanceVariable(II, ClassDeclared))3.89k
) {
2846
      // Diagnose using an ivar in a class method.
2847
2.18k
      if (IsClassMethod) {
2848
8
        Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2849
8
        return DeclResult(true);
2850
8
      }
2851
2852
      // Diagnose the use of an ivar outside of the declaring class.
2853
2.17k
      if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2854
2.17k
          
!declaresSameEntity(ClassDeclared, IFace)675
&&
2855
2.17k
          
!getLangOpts().DebuggerSupport9
)
2856
3
        Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2857
2858
      // Success.
2859
2.17k
      return IV;
2860
2.18k
    }
2861
10.5k
  } else if (CurMethod->isInstanceMethod()) {
2862
    // We should warn if a local variable hides an ivar.
2863
9.57k
    if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2864
9.56k
      ObjCInterfaceDecl *ClassDeclared;
2865
9.56k
      if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2866
2
        if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2867
2
            
declaresSameEntity(IFace, ClassDeclared)0
)
2868
2
          Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2869
2
      }
2870
9.56k
    }
2871
9.57k
  } else 
if (929
Lookup.isSingleResult()929
&&
2872
929
             Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2873
    // If accessing a stand-alone ivar in a class method, this is an error.
2874
191
    if (const ObjCIvarDecl *IV =
2875
191
            dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
2876
1
      Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2877
1
      return DeclResult(true);
2878
1
    }
2879
191
  }
2880
2881
  // Didn't encounter an error, didn't find an ivar.
2882
12.2k
  return DeclResult(false);
2883
14.4k
}
2884
2885
ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
2886
2.17k
                                  ObjCIvarDecl *IV) {
2887
2.17k
  ObjCMethodDecl *CurMethod = getCurMethodDecl();
2888
2.17k
  assert(CurMethod && CurMethod->isInstanceMethod() &&
2889
2.17k
         "should not reference ivar from this context");
2890
2891
0
  ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
2892
2.17k
  assert(IFace && "should not reference ivar from this context");
2893
2894
  // If we're referencing an invalid decl, just return this as a silent
2895
  // error node.  The error diagnostic was already emitted on the decl.
2896
2.17k
  if (IV->isInvalidDecl())
2897
2
    return ExprError();
2898
2899
  // Check if referencing a field with __attribute__((deprecated)).
2900
2.17k
  if (DiagnoseUseOfDecl(IV, Loc))
2901
0
    return ExprError();
2902
2903
  // FIXME: This should use a new expr for a direct reference, don't
2904
  // turn this into Self->ivar, just return a BareIVarExpr or something.
2905
2.17k
  IdentifierInfo &II = Context.Idents.get("self");
2906
2.17k
  UnqualifiedId SelfName;
2907
2.17k
  SelfName.setImplicitSelfParam(&II);
2908
2.17k
  CXXScopeSpec SelfScopeSpec;
2909
2.17k
  SourceLocation TemplateKWLoc;
2910
2.17k
  ExprResult SelfExpr =
2911
2.17k
      ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2912
2.17k
                        /*HasTrailingLParen=*/false,
2913
2.17k
                        /*IsAddressOfOperand=*/false);
2914
2.17k
  if (SelfExpr.isInvalid())
2915
0
    return ExprError();
2916
2917
2.17k
  SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2918
2.17k
  if (SelfExpr.isInvalid())
2919
0
    return ExprError();
2920
2921
2.17k
  MarkAnyDeclReferenced(Loc, IV, true);
2922
2923
2.17k
  ObjCMethodFamily MF = CurMethod->getMethodFamily();
2924
2.17k
  if (MF != OMF_init && 
MF != OMF_dealloc1.79k
&&
MF != OMF_finalize1.59k
&&
2925
2.17k
      
!IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)1.59k
)
2926
1.56k
    Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2927
2928
2.17k
  ObjCIvarRefExpr *Result = new (Context)
2929
2.17k
      ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2930
2.17k
                      IV->getLocation(), SelfExpr.get(), true, true);
2931
2932
2.17k
  if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2933
15
    if (!isUnevaluatedContext() &&
2934
15
        !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2935
4
      getCurFunction()->recordUseOfWeak(Result);
2936
15
  }
2937
2.17k
  if (getLangOpts().ObjCAutoRefCount)
2938
260
    if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2939
24
      ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2940
2941
2.17k
  return Result;
2942
2.17k
}
2943
2944
/// The parser has read a name in, and Sema has detected that we're currently
2945
/// inside an ObjC method. Perform some additional checks and determine if we
2946
/// should form a reference to an ivar. If so, build an expression referencing
2947
/// that ivar.
2948
ExprResult
2949
Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2950
10.4k
                         IdentifierInfo *II, bool AllowBuiltinCreation) {
2951
  // FIXME: Integrate this lookup step into LookupParsedName.
2952
10.4k
  DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
2953
10.4k
  if (Ivar.isInvalid())
2954
3
    return ExprError();
2955
10.4k
  if (Ivar.isUsable())
2956
1.26k
    return BuildIvarRefExpr(S, Lookup.getNameLoc(),
2957
1.26k
                            cast<ObjCIvarDecl>(Ivar.get()));
2958
2959
9.21k
  if (Lookup.empty() && 
II173
&&
AllowBuiltinCreation173
)
2960
173
    LookupBuiltin(Lookup);
2961
2962
  // Sentinel value saying that we didn't do anything special.
2963
9.21k
  return ExprResult(false);
2964
10.4k
}
2965
2966
/// Cast a base object to a member's actual type.
2967
///
2968
/// There are two relevant checks:
2969
///
2970
/// C++ [class.access.base]p7:
2971
///
2972
///   If a class member access operator [...] is used to access a non-static
2973
///   data member or non-static member function, the reference is ill-formed if
2974
///   the left operand [...] cannot be implicitly converted to a pointer to the
2975
///   naming class of the right operand.
2976
///
2977
/// C++ [expr.ref]p7:
2978
///
2979
///   If E2 is a non-static data member or a non-static member function, the
2980
///   program is ill-formed if the class of which E2 is directly a member is an
2981
///   ambiguous base (11.8) of the naming class (11.9.3) of E2.
2982
///
2983
/// Note that the latter check does not consider access; the access of the
2984
/// "real" base class is checked as appropriate when checking the access of the
2985
/// member name.
2986
ExprResult
2987
Sema::PerformObjectMemberConversion(Expr *From,
2988
                                    NestedNameSpecifier *Qualifier,
2989
                                    NamedDecl *FoundDecl,
2990
839k
                                    NamedDecl *Member) {
2991
839k
  CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2992
839k
  if (!RD)
2993
121k
    return From;
2994
2995
717k
  QualType DestRecordType;
2996
717k
  QualType DestType;
2997
717k
  QualType FromRecordType;
2998
717k
  QualType FromType = From->getType();
2999
717k
  bool PointerConversions = false;
3000
717k
  if (isa<FieldDecl>(Member)) {
3001
710k
    DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
3002
710k
    auto FromPtrType = FromType->getAs<PointerType>();
3003
710k
    DestRecordType = Context.getAddrSpaceQualType(
3004
710k
        DestRecordType, FromPtrType
3005
710k
                            ? 
FromType->getPointeeType().getAddressSpace()516k
3006
710k
                            : 
FromType.getAddressSpace()193k
);
3007
3008
710k
    if (FromPtrType) {
3009
516k
      DestType = Context.getPointerType(DestRecordType);
3010
516k
      FromRecordType = FromPtrType->getPointeeType();
3011
516k
      PointerConversions = true;
3012
516k
    } else {
3013
193k
      DestType = DestRecordType;
3014
193k
      FromRecordType = FromType;
3015
193k
    }
3016
710k
  } else 
if (CXXMethodDecl *7.43k
Method7.43k
= dyn_cast<CXXMethodDecl>(Member)) {
3017
7.43k
    if (Method->isStatic())
3018
0
      return From;
3019
3020
7.43k
    DestType = Method->getThisType();
3021
7.43k
    DestRecordType = DestType->getPointeeType();
3022
3023
7.43k
    if (FromType->getAs<PointerType>()) {
3024
5.62k
      FromRecordType = FromType->getPointeeType();
3025
5.62k
      PointerConversions = true;
3026
5.62k
    } else {
3027
1.80k
      FromRecordType = FromType;
3028
1.80k
      DestType = DestRecordType;
3029
1.80k
    }
3030
3031
7.43k
    LangAS FromAS = FromRecordType.getAddressSpace();
3032
7.43k
    LangAS DestAS = DestRecordType.getAddressSpace();
3033
7.43k
    if (FromAS != DestAS) {
3034
4
      QualType FromRecordTypeWithoutAS =
3035
4
          Context.removeAddrSpaceQualType(FromRecordType);
3036
4
      QualType FromTypeWithDestAS =
3037
4
          Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
3038
4
      if (PointerConversions)
3039
1
        FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
3040
4
      From = ImpCastExprToType(From, FromTypeWithDestAS,
3041
4
                               CK_AddressSpaceConversion, From->getValueKind())
3042
4
                 .get();
3043
4
    }
3044
7.43k
  } else {
3045
    // No conversion necessary.
3046
0
    return From;
3047
0
  }
3048
3049
717k
  if (DestType->isDependentType() || 
FromType->isDependentType()411k
)
3050
306k
    return From;
3051
3052
  // If the unqualified types are the same, no conversion is necessary.
3053
411k
  if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3054
395k
    return From;
3055
3056
15.8k
  SourceRange FromRange = From->getSourceRange();
3057
15.8k
  SourceLocation FromLoc = FromRange.getBegin();
3058
3059
15.8k
  ExprValueKind VK = From->getValueKind();
3060
3061
  // C++ [class.member.lookup]p8:
3062
  //   [...] Ambiguities can often be resolved by qualifying a name with its
3063
  //   class name.
3064
  //
3065
  // If the member was a qualified name and the qualified referred to a
3066
  // specific base subobject type, we'll cast to that intermediate type
3067
  // first and then to the object in which the member is declared. That allows
3068
  // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3069
  //
3070
  //   class Base { public: int x; };
3071
  //   class Derived1 : public Base { };
3072
  //   class Derived2 : public Base { };
3073
  //   class VeryDerived : public Derived1, public Derived2 { void f(); };
3074
  //
3075
  //   void VeryDerived::f() {
3076
  //     x = 17; // error: ambiguous base subobjects
3077
  //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
3078
  //   }
3079
15.8k
  if (Qualifier && 
Qualifier->getAsType()6.16k
) {
3080
6.15k
    QualType QType = QualType(Qualifier->getAsType(), 0);
3081
6.15k
    assert(QType->isRecordType() && "lookup done with non-record type");
3082
3083
0
    QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3084
3085
    // In C++98, the qualifier type doesn't actually have to be a base
3086
    // type of the object type, in which case we just ignore it.
3087
    // Otherwise build the appropriate casts.
3088
6.15k
    if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3089
6.12k
      CXXCastPath BasePath;
3090
6.12k
      if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3091
6.12k
                                       FromLoc, FromRange, &BasePath))
3092
18
        return ExprError();
3093
3094
6.10k
      if (PointerConversions)
3095
5.93k
        QType = Context.getPointerType(QType);
3096
6.10k
      From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3097
6.10k
                               VK, &BasePath).get();
3098
3099
6.10k
      FromType = QType;
3100
6.10k
      FromRecordType = QRecordType;
3101
3102
      // If the qualifier type was the same as the destination type,
3103
      // we're done.
3104
6.10k
      if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3105
5.95k
        return From;
3106
6.10k
    }
3107
6.15k
  }
3108
3109
9.91k
  CXXCastPath BasePath;
3110
9.91k
  if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3111
9.91k
                                   FromLoc, FromRange, &BasePath,
3112
9.91k
                                   /*IgnoreAccess=*/true))
3113
7
    return ExprError();
3114
3115
9.90k
  return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
3116
9.90k
                           VK, &BasePath);
3117
9.91k
}
3118
3119
bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
3120
                                      const LookupResult &R,
3121
17.5M
                                      bool HasTrailingLParen) {
3122
  // Only when used directly as the postfix-expression of a call.
3123
17.5M
  if (!HasTrailingLParen)
3124
13.3M
    return false;
3125
3126
  // Never if a scope specifier was provided.
3127
4.22M
  if (SS.isSet())
3128
413k
    return false;
3129
3130
  // Only in C++ or ObjC++.
3131
3.81M
  if (!getLangOpts().CPlusPlus)
3132
2.38M
    return false;
3133
3134
  // Turn off ADL when we find certain kinds of declarations during
3135
  // normal lookup:
3136
1.74M
  
for (NamedDecl *D : R)1.43M
{
3137
    // C++0x [basic.lookup.argdep]p3:
3138
    //     -- a declaration of a class member
3139
    // Since using decls preserve this property, we check this on the
3140
    // original decl.
3141
1.74M
    if (D->isCXXClassMember())
3142
428k
      return false;
3143
3144
    // C++0x [basic.lookup.argdep]p3:
3145
    //     -- a block-scope function declaration that is not a
3146
    //        using-declaration
3147
    // NOTE: we also trigger this for function templates (in fact, we
3148
    // don't check the decl type at all, since all other decl types
3149
    // turn off ADL anyway).
3150
1.31M
    if (isa<UsingShadowDecl>(D))
3151
41.7k
      D = cast<UsingShadowDecl>(D)->getTargetDecl();
3152
1.27M
    else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3153
30.5k
      return false;
3154
3155
    // C++0x [basic.lookup.argdep]p3:
3156
    //     -- a declaration that is neither a function or a function
3157
    //        template
3158
    // And also for builtin functions.
3159
1.28M
    if (isa<FunctionDecl>(D)) {
3160
1.02M
      FunctionDecl *FDecl = cast<FunctionDecl>(D);
3161
3162
      // But also builtin functions.
3163
1.02M
      if (FDecl->getBuiltinID() && 
FDecl->isImplicit()497k
)
3164
412k
        return false;
3165
1.02M
    } else 
if (263k
!isa<FunctionTemplateDecl>(D)263k
)
3166
5.39k
      return false;
3167
1.28M
  }
3168
3169
556k
  return true;
3170
1.43M
}
3171
3172
3173
/// Diagnoses obvious problems with the use of the given declaration
3174
/// as an expression.  This is only actually called for lookups that
3175
/// were not overloaded, and it doesn't promise that the declaration
3176
/// will in fact be used.
3177
16.3M
static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
3178
16.3M
  if (D->isInvalidDecl())
3179
928
    return true;
3180
3181
16.3M
  if (isa<TypedefNameDecl>(D)) {
3182
3
    S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3183
3
    return true;
3184
3
  }
3185
3186
16.3M
  if (isa<ObjCInterfaceDecl>(D)) {
3187
2
    S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3188
2
    return true;
3189
2
  }
3190
3191
16.3M
  if (isa<NamespaceDecl>(D)) {
3192
5
    S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3193
5
    return true;
3194
5
  }
3195
3196
16.3M
  return false;
3197
16.3M
}
3198
3199
// Certain multiversion types should be treated as overloaded even when there is
3200
// only one result.
3201
15.0M
static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3202
15.0M
  assert(R.isSingleResult() && "Expected only a single result");
3203
0
  const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3204
15.0M
  return FD &&
3205
15.0M
         
(2.91M
FD->isCPUDispatchMultiVersion()2.91M
||
FD->isCPUSpecificMultiVersion()2.91M
);
3206
15.0M
}
3207
3208
ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3209
                                          LookupResult &R, bool NeedsADL,
3210
15.4M
                                          bool AcceptInvalidDecl) {
3211
  // If this is a single, fully-resolved result and we don't need ADL,
3212
  // just build an ordinary singleton decl ref.
3213
15.4M
  if (!NeedsADL && 
R.isSingleResult()15.1M
&&
3214
15.4M
      
!R.getAsSingle<FunctionTemplateDecl>()14.8M
&&
3215
15.4M
      
!ShouldLookupResultBeMultiVersionOverload(R)14.8M
)
3216
14.8M
    return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3217
14.8M
                                    R.getRepresentativeDecl(), nullptr,
3218
14.8M
                                    AcceptInvalidDecl);
3219
3220
  // We only need to check the declaration if there's exactly one
3221
  // result, because in the overloaded case the results can only be
3222
  // functions and function templates.
3223
588k
  if (R.isSingleResult() && 
!ShouldLookupResultBeMultiVersionOverload(R)163k
&&
3224
588k
      
CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())163k
)
3225
18
    return ExprError();
3226
3227
  // Otherwise, just build an unresolved lookup expression.  Suppress
3228
  // any lookup-related diagnostics; we'll hash these out later, when
3229
  // we've picked a target.
3230
588k
  R.suppressDiagnostics();
3231
3232
588k
  UnresolvedLookupExpr *ULE
3233
588k
    = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3234
588k
                                   SS.getWithLocInContext(Context),
3235
588k
                                   R.getLookupNameInfo(),
3236
588k
                                   NeedsADL, R.isOverloadedResult(),
3237
588k
                                   R.begin(), R.end());
3238
3239
588k
  return ULE;
3240
588k
}
3241
3242
static void diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
3243
                                               ValueDecl *var);
3244
3245
/// Complete semantic analysis for a reference to the given declaration.
3246
ExprResult Sema::BuildDeclarationNameExpr(
3247
    const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3248
    NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3249
16.1M
    bool AcceptInvalidDecl) {
3250
16.1M
  assert(D && "Cannot refer to a NULL declaration");
3251
0
  assert(!isa<FunctionTemplateDecl>(D) &&
3252
16.1M
         "Cannot refer unambiguously to a function template");
3253
3254
0
  SourceLocation Loc = NameInfo.getLoc();
3255
16.1M
  if (CheckDeclInExpr(*this, Loc, D)) {
3256
    // Recovery from invalid cases (e.g. D is an invalid Decl).
3257
    // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3258
    // diagnostics, as invalid decls use int as a fallback type.
3259
920
    return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
3260
920
  }
3261
3262
16.1M
  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3263
    // Specifically diagnose references to class templates that are missing
3264
    // a template argument list.
3265
12
    diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
3266
12
    return ExprError();
3267
12
  }
3268
3269
  // Make sure that we're referring to a value.
3270
16.1M
  if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) {
3271
3.24k
    Diag(Loc, diag::err_ref_non_value) << D << SS.getRange();
3272
3.24k
    Diag(D->getLocation(), diag::note_declared_at);
3273
3.24k
    return ExprError();
3274
3.24k
  }
3275
3276
  // Check whether this declaration can be used. Note that we suppress
3277
  // this check when we're going to perform argument-dependent lookup
3278
  // on this function name, because this might not be the function
3279
  // that overload resolution actually selects.
3280
16.1M
  if (DiagnoseUseOfDecl(D, Loc))
3281
132
    return ExprError();
3282
3283
16.1M
  auto *VD = cast<ValueDecl>(D);
3284
3285
  // Only create DeclRefExpr's for valid Decl's.
3286
16.1M
  if (VD->isInvalidDecl() && 
!AcceptInvalidDecl18
)
3287
18
    return ExprError();
3288
3289
  // Handle members of anonymous structs and unions.  If we got here,
3290
  // and the reference is to a class member indirect field, then this
3291
  // must be the subject of a pointer-to-member expression.
3292
16.1M
  if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
3293
112
    if (!indirectField->isCXXClassMember())
3294
72
      return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3295
72
                                                      indirectField);
3296
3297
16.1M
  QualType type = VD->getType();
3298
16.1M
  if (type.isNull())
3299
1
    return ExprError();
3300
16.1M
  ExprValueKind valueKind = VK_PRValue;
3301
3302
  // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3303
  // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3304
  // is expanded by some outer '...' in the context of the use.
3305
16.1M
  type = type.getNonPackExpansionType();
3306
3307
16.1M
  switch (D->getKind()) {
3308
    // Ignore all the non-ValueDecl kinds.
3309
0
#define ABSTRACT_DECL(kind)
3310
0
#define VALUE(type, base)
3311
0
#define DECL(type, base) case Decl::type:
3312
0
#include "clang/AST/DeclNodes.inc"
3313
0
    llvm_unreachable("invalid value decl kind");
3314
3315
  // These shouldn't make it here.
3316
0
  case Decl::ObjCAtDefsField:
3317
0
    llvm_unreachable("forming non-member reference to ivar?");
3318
3319
  // Enum constants are always r-values and never references.
3320
  // Unresolved using declarations are dependent.
3321
415k
  case Decl::EnumConstant:
3322
415k
  case Decl::UnresolvedUsingValue:
3323
415k
  case Decl::OMPDeclareReduction:
3324
415k
  case Decl::OMPDeclareMapper:
3325
415k
    valueKind = VK_PRValue;
3326
415k
    break;
3327
3328
  // Fields and indirect fields that got here must be for
3329
  // pointer-to-member expressions; we just call them l-values for
3330
  // internal consistency, because this subexpression doesn't really
3331
  // exist in the high-level semantics.
3332
948
  case Decl::Field:
3333
988
  case Decl::IndirectField:
3334
995
  case Decl::ObjCIvar:
3335
995
    assert(getLangOpts().CPlusPlus && "building reference to field in C?");
3336
3337
    // These can't have reference type in well-formed programs, but
3338
    // for internal consistency we do this anyway.
3339
0
    type = type.getNonReferenceType();
3340
995
    valueKind = VK_LValue;
3341
995
    break;
3342
3343
  // Non-type template parameters are either l-values or r-values
3344
  // depending on the type.
3345
337k
  case Decl::NonTypeTemplateParm: {
3346
337k
    if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3347
48
      type = reftype->getPointeeType();
3348
48
      valueKind = VK_LValue; // even if the parameter is an r-value reference
3349
48
      break;
3350
48
    }
3351
3352
    // [expr.prim.id.unqual]p2:
3353
    //   If the entity is a template parameter object for a template
3354
    //   parameter of type T, the type of the expression is const T.
3355
    //   [...] The expression is an lvalue if the entity is a [...] template
3356
    //   parameter object.
3357
337k
    if (type->isRecordType()) {
3358
32
      type = type.getUnqualifiedType().withConst();
3359
32
      valueKind = VK_LValue;
3360
32
      break;
3361
32
    }
3362
3363
    // For non-references, we need to strip qualifiers just in case
3364
    // the template parameter was declared as 'const int' or whatever.
3365
337k
    valueKind = VK_PRValue;
3366
337k
    type = type.getUnqualifiedType();
3367
337k
    break;
3368
337k
  }
3369
3370
4.69M
  case Decl::Var:
3371
4.69M
  case Decl::VarTemplateSpecialization:
3372
4.69M
  case Decl::VarTemplatePartialSpecialization:
3373
4.69M
  case Decl::Decomposition:
3374
4.71M
  case Decl::OMPCapturedExpr:
3375
    // In C, "extern void blah;" is valid and is an r-value.
3376
4.71M
    if (!getLangOpts().CPlusPlus && 
!type.hasQualifiers()1.02M
&&
3377
4.71M
        
type->isVoidType()1.00M
) {
3378
9
      valueKind = VK_PRValue;
3379
9
      break;
3380
9
    }
3381
4.71M
    
LLVM_FALLTHROUGH4.71M
;4.71M
3382
3383
4.71M
  case Decl::ImplicitParam:
3384
12.6M
  case Decl::ParmVar: {
3385
    // These are always l-values.
3386
12.6M
    valueKind = VK_LValue;
3387
12.6M
    type = type.getNonReferenceType();
3388
3389
    // FIXME: Does the addition of const really only apply in
3390
    // potentially-evaluated contexts? Since the variable isn't actually
3391
    // captured in an unevaluated context, it seems that the answer is no.
3392
12.6M
    if (!isUnevaluatedContext()) {
3393
12.5M
      QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3394
12.5M
      if (!CapturedType.isNull())
3395
569k
        type = CapturedType;
3396
12.5M
    }
3397
3398
12.6M
    break;
3399
4.71M
  }
3400
3401
563
  case Decl::Binding: {
3402
    // These are always lvalues.
3403
563
    valueKind = VK_LValue;
3404
563
    type = type.getNonReferenceType();
3405
    // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3406
    // decides how that's supposed to work.
3407
563
    auto *BD = cast<BindingDecl>(VD);
3408
563
    if (BD->getDeclContext() != CurContext) {
3409
17
      auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
3410
17
      if (DD && DD->hasLocalStorage())
3411
2
        diagnoseUncapturableValueReference(*this, Loc, BD);
3412
17
    }
3413
563
    break;
3414
4.71M
  }
3415
3416
2.68M
  case Decl::Function: {
3417
2.68M
    if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3418
1.78M
      if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
3419
1.77M
        type = Context.BuiltinFnTy;
3420
1.77M
        valueKind = VK_PRValue;
3421
1.77M
        break;
3422
1.77M
      }
3423
1.78M
    }
3424
3425
909k
    const FunctionType *fty = type->castAs<FunctionType>();
3426
3427
    // If we're referring to a function with an __unknown_anytype
3428
    // result type, make the entire expression __unknown_anytype.
3429
909k
    if (fty->getReturnType() == Context.UnknownAnyTy) {
3430
6
      type = Context.UnknownAnyTy;
3431
6
      valueKind = VK_PRValue;
3432
6
      break;
3433
6
    }
3434
3435
    // Functions are l-values in C++.
3436
909k
    if (getLangOpts().CPlusPlus) {
3437
70.5k
      valueKind = VK_LValue;
3438
70.5k
      break;
3439
70.5k
    }
3440
3441
    // C99 DR 316 says that, if a function type comes from a
3442
    // function definition (without a prototype), that type is only
3443
    // used for checking compatibility. Therefore, when referencing
3444
    // the function, we pretend that we don't have the full function
3445
    // type.
3446
838k
    if (!cast<FunctionDecl>(VD)->hasPrototype() && 
isa<FunctionProtoType>(fty)1.16k
)
3447
52
      type = Context.getFunctionNoProtoType(fty->getReturnType(),
3448
52
                                            fty->getExtInfo());
3449
3450
    // Functions are r-values in C.
3451
838k
    valueKind = VK_PRValue;
3452
838k
    break;
3453
909k
  }
3454
3455
0
  case Decl::CXXDeductionGuide:
3456
0
    llvm_unreachable("building reference to deduction guide");
3457
3458
3
  case Decl::MSProperty:
3459
15
  case Decl::MSGuid:
3460
127
  case Decl::TemplateParamObject:
3461
    // FIXME: Should MSGuidDecl and template parameter objects be subject to
3462
    // capture in OpenMP, or duplicated between host and device?
3463
127
    valueKind = VK_LValue;
3464
127
    break;
3465
3466
0
  case Decl::UnnamedGlobalConstant:
3467
0
    valueKind = VK_LValue;
3468
0
    break;
3469
3470
85.7k
  case Decl::CXXMethod:
3471
    // If we're referring to a method with an __unknown_anytype
3472
    // result type, make the entire expression __unknown_anytype.
3473
    // This should only be possible with a type written directly.
3474
85.7k
    if (const FunctionProtoType *proto =
3475
85.7k
            dyn_cast<FunctionProtoType>(VD->getType()))
3476
85.6k
      if (proto->getReturnType() == Context.UnknownAnyTy) {
3477
0
        type = Context.UnknownAnyTy;
3478
0
        valueKind = VK_PRValue;
3479
0
        break;
3480
0
      }
3481
3482
    // C++ methods are l-values if static, r-values if non-static.
3483
85.7k
    if (cast<CXXMethodDecl>(VD)->isStatic()) {
3484
84.0k
      valueKind = VK_LValue;
3485
84.0k
      break;
3486
84.0k
    }
3487
85.7k
    
LLVM_FALLTHROUGH1.65k
;1.65k
3488
3489
1.67k
  case Decl::CXXConversion:
3490
1.67k
  case Decl::CXXDestructor:
3491
1.67k
  case Decl::CXXConstructor:
3492
1.67k
    valueKind = VK_PRValue;
3493
1.67k
    break;
3494
16.1M
  }
3495
3496
16.1M
  return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3497
16.1M
                          /*FIXME: TemplateKWLoc*/ SourceLocation(),
3498
16.1M
                          TemplateArgs);
3499
16.1M
}
3500
3501
static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3502
14
                                    SmallString<32> &Target) {
3503
14
  Target.resize(CharByteWidth * (Source.size() + 1));
3504
14
  char *ResultPtr = &Target[0];
3505
14
  const llvm::UTF8 *ErrorPtr;
3506
14
  bool success =
3507
14
      llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3508
14
  (void)success;
3509
14
  assert(success);
3510
0
  Target.resize(ResultPtr - &Target[0]);
3511
14
}
3512
3513
ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3514
897
                                     PredefinedExpr::IdentKind IK) {
3515
  // Pick the current block, lambda, captured statement or function.
3516
897
  Decl *currentDecl = nullptr;
3517
897
  if (const BlockScopeInfo *BSI = getCurBlock())
3518
41
    currentDecl = BSI->TheDecl;
3519
856
  else if (const LambdaScopeInfo *LSI = getCurLambda())
3520
24
    currentDecl = LSI->CallOperator;
3521
832
  else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3522
23
    currentDecl = CSI->TheCapturedDecl;
3523
809
  else
3524
809
    currentDecl = getCurFunctionOrMethodDecl();
3525
3526
897
  if (!currentDecl) {
3527
5
    Diag(Loc, diag::ext_predef_outside_function);
3528
5
    currentDecl = Context.getTranslationUnitDecl();
3529
5
  }
3530
3531
897
  QualType ResTy;
3532
897
  StringLiteral *SL = nullptr;
3533
897
  if (cast<DeclContext>(currentDecl)->isDependentContext())
3534
83
    ResTy = Context.DependentTy;
3535
814
  else {
3536
    // Pre-defined identifiers are of type char[x], where x is the length of
3537
    // the string.
3538
814
    auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3539
814
    unsigned Length = Str.length();
3540
3541
814
    llvm::APInt LengthI(32, Length + 1);
3542
814
    if (IK == PredefinedExpr::LFunction || 
IK == PredefinedExpr::LFuncSig806
) {
3543
14
      ResTy =
3544
14
          Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3545
14
      SmallString<32> RawChars;
3546
14
      ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3547
14
                              Str, RawChars);
3548
14
      ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3549
14
                                           ArrayType::Normal,
3550
14
                                           /*IndexTypeQuals*/ 0);
3551
14
      SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3552
14
                                 /*Pascal*/ false, ResTy, Loc);
3553
800
    } else {
3554
800
      ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3555
800
      ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3556
800
                                           ArrayType::Normal,
3557
800
                                           /*IndexTypeQuals*/ 0);
3558
800
      SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3559
800
                                 /*Pascal*/ false, ResTy, Loc);
3560
800
    }
3561
814
  }
3562
3563
897
  return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3564
897
}
3565
3566
ExprResult Sema::BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc,
3567
                                               SourceLocation LParen,
3568
                                               SourceLocation RParen,
3569
84
                                               TypeSourceInfo *TSI) {
3570
84
  return SYCLUniqueStableNameExpr::Create(Context, OpLoc, LParen, RParen, TSI);
3571
84
}
3572
3573
ExprResult Sema::ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc,
3574
                                               SourceLocation LParen,
3575
                                               SourceLocation RParen,
3576
62
                                               ParsedType ParsedTy) {
3577
62
  TypeSourceInfo *TSI = nullptr;
3578
62
  QualType Ty = GetTypeFromParser(ParsedTy, &TSI);
3579
3580
62
  if (Ty.isNull())
3581
0
    return ExprError();
3582
62
  if (!TSI)
3583
0
    TSI = Context.getTrivialTypeSourceInfo(Ty, LParen);
3584
3585
62
  return BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI);
3586
62
}
3587
3588
822
ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3589
822
  PredefinedExpr::IdentKind IK;
3590
3591
822
  switch (Kind) {
3592
0
  default: llvm_unreachable("Unknown simple primary expr!");
3593
370
  case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3594
197
  case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3595
9
  case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3596
13
  case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3597
8
  case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3598
6
  case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3599
219
  case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3600
822
  }
3601
3602
822
  return BuildPredefinedExpr(Loc, IK);
3603
822
}
3604
3605
567k
ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3606
567k
  SmallString<16> CharBuffer;
3607
567k
  bool Invalid = false;
3608
567k
  StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3609
567k
  if (Invalid)
3610
0
    return ExprError();
3611
3612
567k
  CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3613
567k
                            PP, Tok.getKind());
3614
567k
  if (Literal.hadError())
3615
125
    return ExprError();
3616
3617
567k
  QualType Ty;
3618
567k
  if (Literal.isWide())
3619
1.09k
    Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3620
565k
  else if (Literal.isUTF8() && 
getLangOpts().C2x151
)
3621
2
    Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C2x
3622
565k
  else if (Literal.isUTF8() && 
getLangOpts().Char8149
)
3623
139
    Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3624
565k
  else if (Literal.isUTF16())
3625
104
    Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3626
565k
  else if (Literal.isUTF32())
3627
94
    Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3628
565k
  else if (!getLangOpts().CPlusPlus || 
Literal.isMultiChar()98.8k
)
3629
530k
    Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3630
35.0k
  else
3631
35.0k
    Ty = Context.CharTy; // 'x' -> char in C++;
3632
                         // u8'x' -> char in C11-C17 and in C++ without char8_t.
3633
3634
567k
  CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3635
567k
  if (Literal.isWide())
3636
1.09k
    Kind = CharacterLiteral::Wide;
3637
565k
  else if (Literal.isUTF16())
3638
104
    Kind = CharacterLiteral::UTF16;
3639
565k
  else if (Literal.isUTF32())
3640
94
    Kind = CharacterLiteral::UTF32;
3641
565k
  else if (Literal.isUTF8())
3642
151
    Kind = CharacterLiteral::UTF8;
3643
3644
567k
  Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3645
567k
                                             Tok.getLocation());
3646
3647
567k
  if (Literal.getUDSuffix().empty())
3648
566k
    return Lit;
3649
3650
  // We're building a user-defined literal.
3651
57
  IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3652
57
  SourceLocation UDSuffixLoc =
3653
57
    getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3654
3655
  // Make sure we're allowed user-defined literals here.
3656
57
  if (!UDLScope)
3657
0
    return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3658
3659
  // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3660
  //   operator "" X (ch)
3661
57
  return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3662
57
                                        Lit, Tok.getLocation());
3663
57
}
3664
3665
4.69M
ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3666
4.69M
  unsigned IntSize = Context.getTargetInfo().getIntWidth();
3667
4.69M
  return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3668
4.69M
                                Context.IntTy, Loc);
3669
4.69M
}
3670
3671
static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3672
39.8k
                                  QualType Ty, SourceLocation Loc) {
3673
39.8k
  const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3674
3675
39.8k
  using llvm::APFloat;
3676
39.8k
  APFloat Val(Format);
3677
3678
39.8k
  APFloat::opStatus result = Literal.GetFloatValue(Val);
3679
3680
  // Overflow is always an error, but underflow is only an error if
3681
  // we underflowed to zero (APFloat reports denormals as underflow).
3682
39.8k
  if ((result & APFloat::opOverflow) ||
3683
39.8k
      
(39.8k
(result & APFloat::opUnderflow)39.8k
&&
Val.isZero()1.42k
)) {
3684
26
    unsigned diagnostic;
3685
26
    SmallString<20> buffer;
3686
26
    if (result & APFloat::opOverflow) {
3687
14
      diagnostic = diag::warn_float_overflow;
3688
14
      APFloat::getLargest(Format).toString(buffer);
3689
14
    } else {
3690
12
      diagnostic = diag::warn_float_underflow;
3691
12
      APFloat::getSmallest(Format).toString(buffer);
3692
12
    }
3693
3694
26
    S.Diag(Loc, diagnostic)
3695
26
      << Ty
3696
26
      << StringRef(buffer.data(), buffer.size());
3697
26
  }
3698
3699
39.8k
  bool isExact = (result == APFloat::opOK);
3700
39.8k
  return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3701
39.8k
}
3702
3703
305
bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3704
305
  assert(E && "Invalid expression");
3705
3706
305
  if (E->isValueDependent())
3707
66
    return false;
3708
3709
239
  QualType QT = E->getType();
3710
239
  if (!QT->isIntegerType() || 
QT->isBooleanType()238
||
QT->isCharType()237
) {
3711
3
    Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3712
3
    return true;
3713
3
  }
3714
3715
236
  llvm::APSInt ValueAPS;
3716
236
  ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3717
3718
236
  if (R.isInvalid())
3719
1
    return true;
3720
3721
235
  bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3722
235
  if (!ValueIsPositive || 
ValueAPS.getActiveBits() > 31221
) {
3723
19
    Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3724
19
        << toString(ValueAPS, 10) << ValueIsPositive;
3725
19
    return true;
3726
19
  }
3727
3728
216
  return false;
3729
235
}
3730
3731
8.05M
ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3732
  // Fast path for a single digit (which is quite common).  A single digit
3733
  // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3734
8.05M
  if (Tok.getLength() == 1) {
3735
3.66M
    const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3736
3.66M
    return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3737
3.66M
  }
3738
3739
4.38M
  SmallString<128> SpellingBuffer;
3740
  // NumericLiteralParser wants to overread by one character.  Add padding to
3741
  // the buffer in case the token is copied to the buffer.  If getSpelling()
3742
  // returns a StringRef to the memory buffer, it should have a null char at
3743
  // the EOF, so it is also safe.
3744
4.38M
  SpellingBuffer.resize(Tok.getLength() + 1);
3745
3746
  // Get the spelling of the token, which eliminates trigraphs, etc.
3747
4.38M
  bool Invalid = false;
3748
4.38M
  StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3749
4.38M
  if (Invalid)
3750
0
    return ExprError();
3751
3752
4.38M
  NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3753
4.38M
                               PP.getSourceManager(), PP.getLangOpts(),
3754
4.38M
                               PP.getTargetInfo(), PP.getDiagnostics());
3755
4.38M
  if (Literal.hadError)
3756
252
    return ExprError();
3757
3758
4.38M
  if (Literal.hasUDSuffix()) {
3759
    // We're building a user-defined literal.
3760
213
    IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3761
213
    SourceLocation UDSuffixLoc =
3762
213
      getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3763
3764
    // Make sure we're allowed user-defined literals here.
3765
213
    if (!UDLScope)
3766
0
      return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3767
3768
213
    QualType CookedTy;
3769
213
    if (Literal.isFloatingLiteral()) {
3770
      // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3771
      // long double, the literal is treated as a call of the form
3772
      //   operator "" X (f L)
3773
74
      CookedTy = Context.LongDoubleTy;
3774
139
    } else {
3775
      // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3776
      // unsigned long long, the literal is treated as a call of the form
3777
      //   operator "" X (n ULL)
3778
139
      CookedTy = Context.UnsignedLongLongTy;
3779
139
    }
3780
3781
213
    DeclarationName OpName =
3782
213
      Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3783
213
    DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3784
213
    OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3785
3786
213
    SourceLocation TokLoc = Tok.getLocation();
3787
3788
    // Perform literal operator lookup to determine if we're building a raw
3789
    // literal or a cooked one.
3790
213
    LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3791
213
    switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3792
213
                                  /*AllowRaw*/ true, /*AllowTemplate*/ true,
3793
213
                                  /*AllowStringTemplatePack*/ false,
3794
213
                                  /*DiagnoseMissing*/ !Literal.isImaginary)) {
3795
30
    case LOLR_ErrorNoDiagnostic:
3796
      // Lookup failure for imaginary constants isn't fatal, there's still the
3797
      // GNU extension producing _Complex types.
3798
30
      break;
3799
18
    case LOLR_Error:
3800
18
      return ExprError();
3801
103
    case LOLR_Cooked: {
3802
103
      Expr *Lit;
3803
103
      if (Literal.isFloatingLiteral()) {
3804
33
        Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3805
70
      } else {
3806
70
        llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3807
70
        if (Literal.GetIntegerValue(ResultVal))
3808
1
          Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3809
1
              << /* Unsigned */ 1;
3810
70
        Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3811
70
                                     Tok.getLocation());
3812
70
      }
3813
103
      return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3814
0
    }
3815
3816
33
    case LOLR_Raw: {
3817
      // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3818
      // literal is treated as a call of the form
3819
      //   operator "" X ("n")
3820
33
      unsigned Length = Literal.getUDSuffixOffset();
3821
33
      QualType StrTy = Context.getConstantArrayType(
3822
33
          Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3823
33
          llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3824
33
      Expr *Lit = StringLiteral::Create(
3825
33
          Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3826
33
          /*Pascal*/false, StrTy, &TokLoc, 1);
3827
33
      return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3828
0
    }
3829
3830
29
    case LOLR_Template: {
3831
      // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3832
      // template), L is treated as a call fo the form
3833
      //   operator "" X <'c1', 'c2', ... 'ck'>()
3834
      // where n is the source character sequence c1 c2 ... ck.
3835
29
      TemplateArgumentListInfo ExplicitArgs;
3836
29
      unsigned CharBits = Context.getIntWidth(Context.CharTy);
3837
29
      bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3838
29
      llvm::APSInt Value(CharBits, CharIsUnsigned);
3839
184
      for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; 
++I155
) {
3840
155
        Value = TokSpelling[I];
3841
155
        TemplateArgument Arg(Context, Value, Context.CharTy);
3842
155
        TemplateArgumentLocInfo ArgInfo;
3843
155
        ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3844
155
      }
3845
29
      return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3846
29
                                      &ExplicitArgs);
3847
0
    }
3848
0
    case LOLR_StringTemplatePack:
3849
0
      llvm_unreachable("unexpected literal operator lookup result");
3850
213
    }
3851
213
  }
3852
3853
4.38M
  Expr *Res;
3854
3855
4.38M
  if (Literal.isFixedPointLiteral()) {
3856
808
    QualType Ty;
3857
3858
808
    if (Literal.isAccum) {
3859
607
      if (Literal.isHalf) {
3860
416
        Ty = Context.ShortAccumTy;
3861
416
      } else 
if (191
Literal.isLong191
) {
3862
51
        Ty = Context.LongAccumTy;
3863
140
      } else {
3864
140
        Ty = Context.AccumTy;
3865
140
      }
3866
607
    } else 
if (201
Literal.isFract201
) {
3867
201
      if (Literal.isHalf) {
3868
63
        Ty = Context.ShortFractTy;
3869
138
      } else if (Literal.isLong) {
3870
59
        Ty = Context.LongFractTy;
3871
79
      } else {
3872
79
        Ty = Context.FractTy;
3873
79
      }
3874
201
    }
3875
3876
808
    if (Literal.isUnsigned) 
Ty = Context.getCorrespondingUnsignedType(Ty)229
;
3877
3878
808
    bool isSigned = !Literal.isUnsigned;
3879
808
    unsigned scale = Context.getFixedPointScale(Ty);
3880
808
    unsigned bit_width = Context.getTypeInfo(Ty).Width;
3881
3882
808
    llvm::APInt Val(bit_width, 0, isSigned);
3883
808
    bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3884
808
    bool ValIsZero = Val.isZero() && 
!Overflowed55
;
3885
3886
808
    auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3887
808
    if (Literal.isFract && 
Val == MaxVal + 1201
&&
!ValIsZero36
)
3888
      // Clause 6.4.4 - The value of a constant shall be in the range of
3889
      // representable values for its type, with exception for constants of a
3890
      // fract type with a value of exactly 1; such a constant shall denote
3891
      // the maximal value for the type.
3892
32
      --Val;
3893
776
    else if (Val.ugt(MaxVal) || 
Overflowed761
)
3894
31
      Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3895
3896
808
    Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3897
808
                                              Tok.getLocation(), scale);
3898
4.38M
  } else if (Literal.isFloatingLiteral()) {
3899
39.8k
    QualType Ty;
3900
39.8k
    if (Literal.isHalf){
3901
16
      if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
3902
10
        Ty = Context.HalfTy;
3903
6
      else {
3904
6
        Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3905
6
        return ExprError();
3906
6
      }
3907
39.7k
    } else if (Literal.isFloat)
3908
7.76k
      Ty = Context.FloatTy;
3909
32.0k
    else if (Literal.isLong)
3910
3.88k
      Ty = Context.LongDoubleTy;
3911
28.1k
    else if (Literal.isFloat16)
3912
109
      Ty = Context.Float16Ty;
3913
28.0k
    else if (Literal.isFloat128)
3914
170
      Ty = Context.Float128Ty;
3915
27.8k
    else
3916
27.8k
      Ty = Context.DoubleTy;
3917
3918
39.8k
    Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3919
3920
39.8k
    if (Ty == Context.DoubleTy) {
3921
27.8k
      if (getLangOpts().SinglePrecisionConstants) {
3922
2
        if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
3923
2
          Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3924
2
        }
3925
27.8k
      } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
3926
127
                                             "cl_khr_fp64", getLangOpts())) {
3927
        // Impose single-precision float type when cl_khr_fp64 is not enabled.
3928
26
        Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
3929
26
            << (getLangOpts().getOpenCLCompatibleVersion() >= 300);
3930
26
        Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3931
26
      }
3932
27.8k
    }
3933
4.34M
  } else if (!Literal.isIntegerLiteral()) {
3934
0
    return ExprError();
3935
4.34M
  } else {
3936
4.34M
    QualType Ty;
3937
3938
    // 'long long' is a C99 or C++11 feature.
3939
4.34M
    if (!getLangOpts().C99 && 
Literal.isLongLong846k
) {
3940
24.8k
      if (getLangOpts().CPlusPlus)
3941
24.8k
        Diag(Tok.getLocation(),
3942
24.8k
             getLangOpts().CPlusPlus11 ?
3943
24.8k
             diag::warn_cxx98_compat_longlong : 
diag::ext_cxx11_longlong37
);
3944
9
      else
3945
9
        Diag(Tok.getLocation(), diag::ext_c99_longlong);
3946
24.8k
    }
3947
3948
    // 'z/uz' literals are a C++2b feature.
3949
4.34M
    if (Literal.isSizeT)
3950
94
      Diag(Tok.getLocation(), getLangOpts().CPlusPlus
3951
94
                                  ? 
getLangOpts().CPlusPlus2b84
3952
84
                                        ? 
diag::warn_cxx20_compat_size_t_suffix74
3953
84
                                        : 
diag::ext_cxx2b_size_t_suffix10
3954
94
                                  : 
diag::err_cxx2b_size_t_suffix10
);
3955
3956
    // 'wb/uwb' literals are a C2x feature. We support _BitInt as a type in C++,
3957
    // but we do not currently support the suffix in C++ mode because it's not
3958
    // entirely clear whether WG21 will prefer this suffix to return a library
3959
    // type such as std::bit_int instead of returning a _BitInt.
3960
4.34M
    if (Literal.isBitInt && 
!getLangOpts().CPlusPlus64
)
3961
64
      PP.Diag(Tok.getLocation(), getLangOpts().C2x
3962
64
                                     ? 
diag::warn_c2x_compat_bitint_suffix63
3963
64
                                     : 
diag::ext_c2x_bitint_suffix1
);
3964
3965
    // Get the value in the widest-possible width. What is "widest" depends on
3966
    // whether the literal is a bit-precise integer or not. For a bit-precise
3967
    // integer type, try to scan the source to determine how many bits are
3968
    // needed to represent the value. This may seem a bit expensive, but trying
3969
    // to get the integer value from an overly-wide APInt is *extremely*
3970
    // expensive, so the naive approach of assuming
3971
    // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
3972
4.34M
    unsigned BitsNeeded =
3973
4.34M
        Literal.isBitInt ? llvm::APInt::getSufficientBitsNeeded(
3974
64
                               Literal.getLiteralDigits(), Literal.getRadix())
3975
4.34M
                         : 
Context.getTargetInfo().getIntMaxTWidth()4.34M
;
3976
4.34M
    llvm::APInt ResultVal(BitsNeeded, 0);
3977
3978
4.34M
    if (Literal.GetIntegerValue(ResultVal)) {
3979
      // If this value didn't fit into uintmax_t, error and force to ull.
3980
5
      Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3981
5
          << /* Unsigned */ 1;
3982
5
      Ty = Context.UnsignedLongLongTy;
3983
5
      assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3984
5
             "long long is not intmax_t?");
3985
4.34M
    } else {
3986
      // If this value fits into a ULL, try to figure out what else it fits into
3987
      // according to the rules of C99 6.4.4.1p5.
3988
3989
      // Octal, Hexadecimal, and integers with a U suffix are allowed to
3990
      // be an unsigned int.
3991
4.34M
      bool AllowUnsigned = Literal.isUnsigned || 
Literal.getRadix() != 104.24M
;
3992
3993
      // Check from smallest to largest, picking the smallest type we can.
3994
4.34M
      unsigned Width = 0;
3995
3996
      // Microsoft specific integer suffixes are explicitly sized.
3997
4.34M
      if (Literal.MicrosoftInteger) {
3998
50
        if (Literal.MicrosoftInteger == 8 && 
!Literal.isUnsigned9
) {
3999
5
          Width = 8;
4000
5
          Ty = Context.CharTy;
4001
45
        } else {
4002
45
          Width = Literal.MicrosoftInteger;
4003
45
          Ty = Context.getIntTypeForBitwidth(Width,
4004
45
                                             /*Signed=*/!Literal.isUnsigned);
4005
45
        }
4006
50
      }
4007
4008
      // Bit-precise integer literals are automagically-sized based on the
4009
      // width required by the literal.
4010
4.34M
      if (Literal.isBitInt) {
4011
        // The signed version has one more bit for the sign value. There are no
4012
        // zero-width bit-precise integers, even if the literal value is 0.
4013
64
        Width = std::max(ResultVal.getActiveBits(), 1u) +
4014
64
                (Literal.isUnsigned ? 
0u30
:
1u34
);
4015
4016
        // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
4017
        // and reset the type to the largest supported width.
4018
64
        unsigned int MaxBitIntWidth =
4019
64
            Context.getTargetInfo().getMaxBitIntWidth();
4020
64
        if (Width > MaxBitIntWidth) {
4021
2
          Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4022
2
              << Literal.isUnsigned;
4023
2
          Width = MaxBitIntWidth;
4024
2
        }
4025
4026
        // Reset the result value to the smaller APInt and select the correct
4027
        // type to be used. Note, we zext even for signed values because the
4028
        // literal itself is always an unsigned value (a preceeding - is a
4029
        // unary operator, not part of the literal).
4030
64
        ResultVal = ResultVal.zextOrTrunc(Width);
4031
64
        Ty = Context.getBitIntType(Literal.isUnsigned, Width);
4032
64
      }
4033
4034
      // Check C++2b size_t literals.
4035
4.34M
      if (Literal.isSizeT) {
4036
94
        assert(!Literal.MicrosoftInteger &&
4037
94
               "size_t literals can't be Microsoft literals");
4038
0
        unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
4039
94
            Context.getTargetInfo().getSizeType());
4040
4041
        // Does it fit in size_t?
4042
94
        if (ResultVal.isIntN(SizeTSize)) {
4043
          // Does it fit in ssize_t?
4044
92
          if (!Literal.isUnsigned && 
ResultVal[SizeTSize - 1] == 026
)
4045
24
            Ty = Context.getSignedSizeType();
4046
68
          else if (AllowUnsigned)
4047
67
            Ty = Context.getSizeType();
4048
92
          Width = SizeTSize;
4049
92
        }
4050
94
      }
4051
4052
4.34M
      if (Ty.isNull() && 
!Literal.isLong4.34M
&&
!Literal.isLongLong4.20M
&&
4053
4.34M
          
!Literal.isSizeT4.16M
) {
4054
        // Are int/unsigned possibilities?
4055
4.16M
        unsigned IntSize = Context.getTargetInfo().getIntWidth();
4056
4057
        // Does it fit in a unsigned int?
4058
4.16M
        if (ResultVal.isIntN(IntSize)) {
4059
          // Does it fit in a signed int?
4060
4.16M
          if (!Literal.isUnsigned && 
ResultVal[IntSize-1] == 04.14M
)
4061
4.11M
            Ty = Context.IntTy;
4062
49.8k
          else if (AllowUnsigned)
4063
49.6k
            Ty = Context.UnsignedIntTy;
4064
4.16M
          Width = IntSize;
4065
4.16M
        }
4066
4.16M
      }
4067
4068
      // Are long/unsigned long possibilities?
4069
4.34M
      if (Ty.isNull() && 
!Literal.isLongLong180k
&&
!Literal.isSizeT136k
) {
4070
136k
        unsigned LongSize = Context.getTargetInfo().getLongWidth();
4071
4072
        // Does it fit in a unsigned long?
4073
136k
        if (ResultVal.isIntN(LongSize)) {
4074
          // Does it fit in a signed long?
4075
136k
          if (!Literal.isUnsigned && 
ResultVal[LongSize-1] == 078.9k
)
4076
78.7k
            Ty = Context.LongTy;
4077
57.7k
          else if (AllowUnsigned)
4078
57.5k
            Ty = Context.UnsignedLongTy;
4079
          // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4080
          // is compatible.
4081
132
          else if (!getLangOpts().C99 && 
!getLangOpts().CPlusPlus1146
) {
4082
18
            const unsigned LongLongSize =
4083
18
                Context.getTargetInfo().getLongLongWidth();
4084
18
            Diag(Tok.getLocation(),
4085
18
                 getLangOpts().CPlusPlus
4086
18
                     ? 
Literal.isLong6
4087
6
                           ? 
diag::warn_old_implicitly_unsigned_long_cxx4
4088
6
                           : /*C++98 UB*/ diag::
4089
2
                                 ext_old_implicitly_unsigned_long_cxx
4090
18
                     : 
diag::warn_old_implicitly_unsigned_long12
)
4091
18
                << (LongLongSize > LongSize ? /*will have type 'long long'*/ 
09
4092
18
                                            : /*will be ill-formed*/ 
19
);
4093
18
            Ty = Context.UnsignedLongTy;
4094
18
          }
4095
136k
          Width = LongSize;
4096
136k
        }
4097
136k
      }
4098
4099
      // Check long long if needed.
4100
4.34M
      if (Ty.isNull() && 
!Literal.isSizeT44.0k
) {
4101
44.0k
        unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4102
4103
        // Does it fit in a unsigned long long?
4104
44.0k
        if (ResultVal.isIntN(LongLongSize)) {
4105
          // Does it fit in a signed long long?
4106
          // To be compatible with MSVC, hex integer literals ending with the
4107
          // LL or i64 suffix are always signed in Microsoft mode.
4108
44.0k
          if (!Literal.isUnsigned && 
(22.4k
ResultVal[LongLongSize-1] == 022.4k
||
4109
22.4k
              
(44
getLangOpts().MSVCCompat44
&&
Literal.isLongLong5
)))
4110
22.4k
            Ty = Context.LongLongTy;
4111
21.6k
          else if (AllowUnsigned)
4112
21.5k
            Ty = Context.UnsignedLongLongTy;
4113
44.0k
          Width = LongLongSize;
4114
44.0k
        }
4115
44.0k
      }
4116
4117
      // If we still couldn't decide a type, we either have 'size_t' literal
4118
      // that is out of range, or a decimal literal that does not fit in a
4119
      // signed long long and has no U suffix.
4120
4.34M
      if (Ty.isNull()) {
4121
20
        if (Literal.isSizeT)
4122
3
          Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4123
3
              << Literal.isUnsigned;
4124
17
        else
4125
17
          Diag(Tok.getLocation(),
4126
17
               diag::ext_integer_literal_too_large_for_signed);
4127
20
        Ty = Context.UnsignedLongLongTy;
4128
20
        Width = Context.getTargetInfo().getLongLongWidth();
4129
20
      }
4130
4131
4.34M
      if (ResultVal.getBitWidth() != Width)
4132
4.16M
        ResultVal = ResultVal.trunc(Width);
4133
4.34M
    }
4134
0
    Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4135
4.34M
  }
4136
4137
  // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4138
4.38M
  if (Literal.isImaginary) {
4139
364
    Res = new (Context) ImaginaryLiteral(Res,
4140
364
                                        Context.getComplexType(Res->getType()));
4141
4142
364
    Diag(Tok.getLocation(), diag::ext_imaginary_constant);
4143
364
  }
4144
4.38M
  return Res;
4145
4.38M
}
4146
4147
2.32M
ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
4148
2.32M
  assert(E && "ActOnParenExpr() missing expr");
4149
0
  QualType ExprTy = E->getType();
4150
2.32M
  if (getLangOpts().ProtectParens && 
CurFPFeatures.getAllowFPReassociate()15
&&
4151
2.32M
      
!E->isLValue()8
&&
ExprTy->hasFloatingRepresentation()6
)
4152
5
    return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
4153
2.32M
  return new (Context) ParenExpr(L, R, E);
4154
2.32M
}
4155
4156
static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
4157
                                         SourceLocation Loc,
4158
45
                                         SourceRange ArgRange) {
4159
  // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4160
  // scalar or vector data type argument..."
4161
  // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4162
  // type (C99 6.2.5p18) or void.
4163
45
  if (!(T->isArithmeticType() || 
T->isVoidType()43
||
T->isVectorType()42
)) {
4164
3
    S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4165
3
      << T << ArgRange;
4166
3
    return true;
4167
3
  }
4168
4169
42
  assert((T->isVoidType() || !T->isIncompleteType()) &&
4170
42
         "Scalar types should always be complete");
4171
0
  return false;
4172
45
}
4173
4174
static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
4175
                                           SourceLocation Loc,
4176
                                           SourceRange ArgRange,
4177
71.6k
                                           UnaryExprOrTypeTrait TraitKind) {
4178
  // Invalid types must be hard errors for SFINAE in C++.
4179
71.6k
  if (S.LangOpts.CPlusPlus)
4180
58.4k
    return true;
4181
4182
  // C99 6.5.3.4p1:
4183
13.2k
  if (T->isFunctionType() &&
4184
13.2k
      
(11
TraitKind == UETT_SizeOf11
||
TraitKind == UETT_AlignOf1
||
4185
11
       
TraitKind == UETT_PreferredAlignOf1
)) {
4186
    // sizeof(function)/alignof(function) is allowed as an extension.
4187
11
    S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4188
11
        << getTraitSpelling(TraitKind) << ArgRange;
4189
11
    return false;
4190
11
  }
4191
4192
  // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4193
  // this is an error (OpenCL v1.1 s6.3.k)
4194
13.1k
  if (T->isVoidType()) {
4195
11
    unsigned DiagID = S.LangOpts.OpenCL ? 
diag::err_opencl_sizeof_alignof_type1
4196
11
                                        : 
diag::ext_sizeof_alignof_void_type10
;
4197
11
    S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4198
11
    return false;
4199
11
  }
4200
4201
13.1k
  return true;
4202
13.1k
}
4203
4204
static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4205
                                             SourceLocation Loc,
4206
                                             SourceRange ArgRange,
4207
71.4k
                                             UnaryExprOrTypeTrait TraitKind) {
4208
  // Reject sizeof(interface) and sizeof(interface<proto>) if the
4209
  // runtime doesn't allow it.
4210
71.4k
  if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && 
T->isObjCObjectType()71.3k
) {
4211
3
    S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4212
3
      << T << (TraitKind == UETT_SizeOf)
4213
3
      << ArgRange;
4214
3
    return true;
4215
3
  }
4216
4217
71.4k
  return false;
4218
71.4k
}
4219
4220
/// Check whether E is a pointer from a decayed array type (the decayed
4221
/// pointer type is equal to T) and emit a warning if it is.
4222
static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4223
180
                                     Expr *E) {
4224
  // Don't warn if the operation changed the type.
4225
180
  if (T != E->getType())
4226
63
    return;
4227
4228
  // Now look for array decays.
4229
117
  ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
4230
117
  if (!ICE || 
ICE->getCastKind() != CK_ArrayToPointerDecay45
)
4231
108
    return;
4232
4233
9
  S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4234
9
                                             << ICE->getType()
4235
9
                                             << ICE->getSubExpr()->getType();
4236
9
}
4237
4238
/// Check the constraints on expression operands to unary type expression
4239
/// and type traits.
4240
///
4241
/// Completes any types necessary and validates the constraints on the operand
4242
/// expression. The logic mostly mirrors the type-based overload, but may modify
4243
/// the expression as it completes the type for that expression through template
4244
/// instantiation, etc.
4245
bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4246
10.3k
                                            UnaryExprOrTypeTrait ExprKind) {
4247
10.3k
  QualType ExprTy = E->getType();
4248
10.3k
  assert(!ExprTy->isReferenceType());
4249
4250
0
  bool IsUnevaluatedOperand =
4251
10.3k
      (ExprKind == UETT_SizeOf || 
ExprKind == UETT_AlignOf189
||
4252
10.3k
       
ExprKind == UETT_PreferredAlignOf151
||
ExprKind == UETT_VecStep36
);
4253
10.3k
  if (IsUnevaluatedOperand) {
4254
10.3k
    ExprResult Result = CheckUnevaluatedOperand(E);
4255
10.3k
    if (Result.isInvalid())
4256
0
      return true;
4257
10.3k
    E = Result.get();
4258
10.3k
  }
4259
4260
  // The operand for sizeof and alignof is in an unevaluated expression context,
4261
  // so side effects could result in unintended consequences.
4262
  // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4263
  // used to build SFINAE gadgets.
4264
  // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4265
10.3k
  if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4266
10.3k
      
!E->isInstantiationDependent()6.29k
&&
4267
10.3k
      
!E->getType()->isVariableArrayType()5.14k
&&
4268
10.3k
      
E->HasSideEffects(Context, false)5.10k
)
4269
52
    Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4270
4271
10.3k
  if (ExprKind == UETT_VecStep)
4272
36
    return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4273
36
                                        E->getSourceRange());
4274
4275
  // Explicitly list some types as extensions.
4276
10.3k
  if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4277
10.3k
                                      E->getSourceRange(), ExprKind))
4278
6
    return false;
4279
4280
  // 'alignof' applied to an expression only requires the base element type of
4281
  // the expression to be complete. 'sizeof' requires the expression's type to
4282
  // be complete (and will attempt to complete it if it's an array of unknown
4283
  // bound).
4284
10.3k
  if (ExprKind == UETT_AlignOf || 
ExprKind == UETT_PreferredAlignOf10.2k
) {
4285
151
    if (RequireCompleteSizedType(
4286
151
            E->getExprLoc(), Context.getBaseElementType(E->getType()),
4287
151
            diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4288
151
            getTraitSpelling(ExprKind), E->getSourceRange()))
4289
12
      return true;
4290
10.1k
  } else {
4291
10.1k
    if (RequireCompleteSizedExprType(
4292
10.1k
            E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4293
10.1k
            getTraitSpelling(ExprKind), E->getSourceRange()))
4294
55
      return true;
4295
10.1k
  }
4296
4297
  // Completing the expression's type may have changed it.
4298
10.2k
  ExprTy = E->getType();
4299
10.2k
  assert(!ExprTy->isReferenceType());
4300
4301
10.2k
  if (ExprTy->isFunctionType()) {
4302
2
    Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4303
2
        << getTraitSpelling(ExprKind) << E->getSourceRange();
4304
2
    return true;
4305
2
  }
4306
4307
10.2k
  if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4308
10.2k
                                       E->getSourceRange(), ExprKind))
4309
0
    return true;
4310
4311
10.2k
  if (ExprKind == UETT_SizeOf) {
4312
10.1k
    if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4313
5.80k
      if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4314
777
        QualType OType = PVD->getOriginalType();
4315
777
        QualType Type = PVD->getType();
4316
777
        if (Type->isPointerType() && 
OType->isArrayType()129
) {
4317
5
          Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4318
5
            << Type << OType;
4319
5
          Diag(PVD->getLocation(), diag::note_declared_at);
4320
5
        }
4321
777
      }
4322
5.80k
    }
4323
4324
    // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4325
    // decays into a pointer and returns an unintended result. This is most
4326
    // likely a typo for "sizeof(array) op x".
4327
10.1k
    if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4328
90
      warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4329
90
                               BO->getLHS());
4330
90
      warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4331
90
                               BO->getRHS());
4332
90
    }
4333
10.1k
  }
4334
4335
10.2k
  return false;
4336
10.2k
}
4337
4338
/// Check the constraints on operands to unary expression and type
4339
/// traits.
4340
///
4341
/// This will complete any types necessary, and validate the various constraints
4342
/// on those operands.
4343
///
4344
/// The UsualUnaryConversions() function is *not* called by this routine.
4345
/// C99 6.3.2.1p[2-4] all state:
4346
///   Except when it is the operand of the sizeof operator ...
4347
///
4348
/// C++ [expr.sizeof]p4
4349
///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4350
///   standard conversions are not applied to the operand of sizeof.
4351
///
4352
/// This policy is followed for all of the unary trait expressions.
4353
bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4354
                                            SourceLocation OpLoc,
4355
                                            SourceRange ExprRange,
4356
61.3k
                                            UnaryExprOrTypeTrait ExprKind) {
4357
61.3k
  if (ExprType->isDependentType())
4358
0
    return false;
4359
4360
  // C++ [expr.sizeof]p2:
4361
  //     When applied to a reference or a reference type, the result
4362
  //     is the size of the referenced type.
4363
  // C++11 [expr.alignof]p3:
4364
  //     When alignof is applied to a reference type, the result
4365
  //     shall be the alignment of the referenced type.
4366
61.3k
  if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4367
40
    ExprType = Ref->getPointeeType();
4368
4369
  // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4370
  //   When alignof or _Alignof is applied to an array type, the result
4371
  //   is the alignment of the element type.
4372
61.3k
  if (ExprKind == UETT_AlignOf || 
ExprKind == UETT_PreferredAlignOf58.6k
||
4373
61.3k
      
ExprKind == UETT_OpenMPRequiredSimdAlign56.1k
)
4374
5.19k
    ExprType = Context.getBaseElementType(ExprType);
4375
4376
61.3k
  if (ExprKind == UETT_VecStep)
4377
9
    return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4378
4379
  // Explicitly list some types as extensions.
4380
61.3k
  if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4381
61.3k
                                      ExprKind))
4382
16
    return false;
4383
4384
61.2k
  if (RequireCompleteSizedType(
4385
61.2k
          OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4386
61.2k
          getTraitSpelling(ExprKind), ExprRange))
4387
110
    return true;
4388
4389
61.1k
  if (ExprType->isFunctionType()) {
4390
8
    Diag(OpLoc, diag::err_sizeof_alignof_function_type)
4391
8
        << getTraitSpelling(ExprKind) << ExprRange;
4392
8
    return true;
4393
8
  }
4394
4395
61.1k
  if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4396
61.1k
                                       ExprKind))
4397
3
    return true;
4398
4399
61.1k
  return false;
4400
61.1k
}
4401
4402
186
static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4403
  // Cannot know anything else if the expression is dependent.
4404
186
  if (E->isTypeDependent())
4405
0
    return false;
4406
4407
186
  if (E->getObjectKind() == OK_BitField) {
4408
1
    S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4409
1
       << 1 << E->getSourceRange();
4410
1
    return true;
4411
1
  }
4412
4413
185
  ValueDecl *D = nullptr;
4414
185
  Expr *Inner = E->IgnoreParens();
4415
185
  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4416
111
    D = DRE->getDecl();
4417
111
  } else 
if (MemberExpr *74
ME74
= dyn_cast<MemberExpr>(Inner)) {
4418
30
    D = ME->getMemberDecl();
4419
30
  }
4420
4421
  // If it's a field, require the containing struct to have a
4422
  // complete definition so that we can compute the layout.
4423
  //
4424
  // This can happen in C++11 onwards, either by naming the member
4425
  // in a way that is not transformed into a member access expression
4426
  // (in an unevaluated operand, for instance), or by naming the member
4427
  // in a trailing-return-type.
4428
  //
4429
  // For the record, since __alignof__ on expressions is a GCC
4430
  // extension, GCC seems to permit this but always gives the
4431
  // nonsensical answer 0.
4432
  //
4433
  // We don't really need the layout here --- we could instead just
4434
  // directly check for all the appropriate alignment-lowing
4435
  // attributes --- but that would require duplicating a lot of
4436
  // logic that just isn't worth duplicating for such a marginal
4437
  // use-case.
4438
185
  if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4439
    // Fast path this check, since we at least know the record has a
4440
    // definition if we can find a member of it.
4441
36
    if (!FD->getParent()->isCompleteDefinition()) {
4442
3
      S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4443
3
        << E->getSourceRange();
4444
3
      return true;
4445
3
    }
4446
4447
    // Otherwise, if it's a field, and the field doesn't have
4448
    // reference type, then it must have a complete type (or be a
4449
    // flexible array member, which we explicitly want to
4450
    // white-list anyway), which makes the following checks trivial.
4451
33
    if (!FD->getType()->isReferenceType())
4452
29
      return false;
4453
33
  }
4454
4455
153
  return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4456
185
}
4457
4458
36
bool Sema::CheckVecStepExpr(Expr *E) {
4459
36
  E = E->IgnoreParens();
4460
4461
  // Cannot know anything else if the expression is dependent.
4462
36
  if (E->isTypeDependent())
4463
0
    return false;
4464
4465
36
  return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4466
36
}
4467
4468
static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4469
18.3k
                                        CapturingScopeInfo *CSI) {
4470
18.3k
  assert(T->isVariablyModifiedType());
4471
0
  assert(CSI != nullptr);
4472
4473
  // We're going to walk down into the type and look for VLA expressions.
4474
26.1k
  do {
4475
26.1k
    const Type *Ty = T.getTypePtr();
4476
26.1k
    switch (Ty->getTypeClass()) {
4477
0
#define TYPE(Class, Base)
4478
0
#define ABSTRACT_TYPE(Class, Base)
4479
0
#define NON_CANONICAL_TYPE(Class, Base)
4480
0
#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4481
0
#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4482
0
#include "clang/AST/TypeNodes.inc"
4483
0
      T = QualType();
4484
0
      break;
4485
    // These types are never variably-modified.
4486
0
    case Type::Builtin:
4487
0
    case Type::Complex:
4488
0
    case Type::Vector:
4489
0
    case Type::ExtVector:
4490
0
    case Type::ConstantMatrix:
4491
0
    case Type::Record:
4492
0
    case Type::Enum:
4493
0
    case Type::Elaborated:
4494
0
    case Type::TemplateSpecialization:
4495
0
    case Type::ObjCObject:
4496
0
    case Type::ObjCInterface:
4497
0
    case Type::ObjCObjectPointer:
4498
0
    case Type::ObjCTypeParam:
4499
0
    case Type::Pipe:
4500
0
    case Type::BitInt:
4501
0
      llvm_unreachable("type class is never variably-modified!");
4502
0
    case Type::Adjusted:
4503
0
      T = cast<AdjustedType>(Ty)->getOriginalType();
4504
0
      break;
4505
0
    case Type::Decayed:
4506
0
      T = cast<DecayedType>(Ty)->getPointeeType();
4507
0
      break;
4508
35
    case Type::Pointer:
4509
35
      T = cast<PointerType>(Ty)->getPointeeType();
4510
35
      break;
4511
0
    case Type::BlockPointer:
4512
0
      T = cast<BlockPointerType>(Ty)->getPointeeType();
4513
0
      break;
4514
0
    case Type::LValueReference:
4515
0
    case Type::RValueReference:
4516
0
      T = cast<ReferenceType>(Ty)->getPointeeType();
4517
0
      break;
4518
0
    case Type::MemberPointer:
4519
0
      T = cast<MemberPointerType>(Ty)->getPointeeType();
4520
0
      break;
4521
0
    case Type::ConstantArray:
4522
0
    case Type::IncompleteArray:
4523
      // Losing element qualification here is fine.
4524
0
      T = cast<ArrayType>(Ty)->getElementType();
4525
0
      break;
4526
26.0k
    case Type::VariableArray: {
4527
      // Losing element qualification here is fine.
4528
26.0k
      const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4529
4530
      // Unknown size indication requires no size computation.
4531
      // Otherwise, evaluate and record it.
4532
26.0k
      auto Size = VAT->getSizeExpr();
4533
26.0k
      if (Size && !CSI->isVLATypeCaptured(VAT) &&
4534
26.0k
          
(8.94k
isa<CapturedRegionScopeInfo>(CSI)8.94k
||
isa<LambdaScopeInfo>(CSI)56
))
4535
8.94k
        CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4536
4537
26.0k
      T = VAT->getElementType();
4538
26.0k
      break;
4539
0
    }
4540
0
    case Type::FunctionProto:
4541
0
    case Type::FunctionNoProto:
4542
0
      T = cast<FunctionType>(Ty)->getReturnType();
4543
0
      break;
4544
32
    case Type::Paren:
4545
32
    case Type::TypeOf:
4546
32
    case Type::UnaryTransform:
4547
32
    case Type::Attributed:
4548
32
    case Type::BTFTagAttributed:
4549
32
    case Type::SubstTemplateTypeParm:
4550
32
    case Type::MacroQualified:
4551
      // Keep walking after single level desugaring.
4552
32
      T = T.getSingleStepDesugaredType(Context);
4553
32
      break;
4554
46
    case Type::Typedef:
4555
46
      T = cast<TypedefType>(Ty)->desugar();
4556
46
      break;
4557
0
    case Type::Decltype:
4558
0
      T = cast<DecltypeType>(Ty)->desugar();
4559
0
      break;
4560
0
    case Type::Using:
4561
0
      T = cast<UsingType>(Ty)->desugar();
4562
0
      break;
4563
0
    case Type::Auto:
4564
0
    case Type::DeducedTemplateSpecialization:
4565
0
      T = cast<DeducedType>(Ty)->getDeducedType();
4566
0
      break;
4567
0
    case Type::TypeOfExpr:
4568
0
      T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4569
0
      break;
4570
0
    case Type::Atomic:
4571
0
      T = cast<AtomicType>(Ty)->getValueType();
4572
0
      break;
4573
26.1k
    }
4574
26.1k
  } while (!T.isNull() && T->isVariablyModifiedType());
4575
18.3k
}
4576
4577
/// Build a sizeof or alignof expression given a type operand.
4578
ExprResult
4579
Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4580
                                     SourceLocation OpLoc,
4581
                                     UnaryExprOrTypeTrait ExprKind,
4582
93.6k
                                     SourceRange R) {
4583
93.6k
  if (!TInfo)
4584
0
    return ExprError();
4585
4586
93.6k
  QualType T = TInfo->getType();
4587
4588
93.6k
  if (!T->isDependentType() &&
4589
93.6k
      
CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)61.3k
)
4590
123
    return ExprError();
4591
4592
93.4k
  if (T->isVariablyModifiedType() && 
FunctionScopes.size() > 148
) {
4593
12
    if (auto *TT = T->getAs<TypedefType>()) {
4594
6
      for (auto I = FunctionScopes.rbegin(),
4595
6
                E = std::prev(FunctionScopes.rend());
4596
12
           I != E; 
++I6
) {
4597
10
        auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4598
10
        if (CSI == nullptr)
4599
0
          break;
4600
10
        DeclContext *DC = nullptr;
4601
10
        if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4602
10
          DC = LSI->CallOperator;
4603
0
        else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4604
0
          DC = CRSI->TheCapturedDecl;
4605
0
        else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4606
0
          DC = BSI->TheDecl;
4607
10
        if (DC) {
4608
10
          if (DC->containsDecl(TT->getDecl()))
4609
4
            break;
4610
6
          captureVariablyModifiedType(Context, T, CSI);
4611
6
        }
4612
10
      }
4613
6
    }
4614
12
  }
4615
4616
  // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4617
93.4k
  if (isUnevaluatedContext() && 
ExprKind == UETT_SizeOf65.8k
&&
4618
93.4k
      
TInfo->getType()->isVariablyModifiedType()57.3k
)
4619
28
    TInfo = TransformToPotentiallyEvaluated(TInfo);
4620
4621
93.4k
  return new (Context) UnaryExprOrTypeTraitExpr(
4622
93.4k
      ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4623
93.6k
}
4624
4625
/// Build a sizeof or alignof expression given an expression
4626
/// operand.
4627
ExprResult
4628
Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4629
17.9k
                                     UnaryExprOrTypeTrait ExprKind) {
4630
17.9k
  ExprResult PE = CheckPlaceholderExpr(E);
4631
17.9k
  if (PE.isInvalid())
4632
2
    return ExprError();
4633
4634
17.8k
  E = PE.get();
4635
4636
  // Verify that the operand is valid.
4637
17.8k
  bool isInvalid = false;
4638
17.8k
  if (E->isTypeDependent()) {
4639
    // Delay type-checking for type-dependent expressions.
4640
10.3k
  } else if (ExprKind == UETT_AlignOf || 
ExprKind == UETT_PreferredAlignOf10.3k
) {
4641
186
    isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4642
10.2k
  } else if (ExprKind == UETT_VecStep) {
4643
36
    isInvalid = CheckVecStepExpr(E);
4644
10.1k
  } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4645
1
      Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4646
1
      isInvalid = true;
4647
10.1k
  } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4648
9
    Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4649
9
    isInvalid = true;
4650
10.1k
  } else {
4651
10.1k
    isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4652
10.1k
  }
4653
4654
17.8k
  if (isInvalid)
4655
84
    return ExprError();
4656
4657
17.8k
  if (ExprKind == UETT_SizeOf && 
E->getType()->isVariableArrayType()17.5k
) {
4658
46
    PE = TransformToPotentiallyEvaluated(E);
4659
46
    if (PE.isInvalid()) 
return ExprError()0
;
4660
46
    E = PE.get();
4661
46
  }
4662
4663
  // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4664
17.8k
  return new (Context) UnaryExprOrTypeTraitExpr(
4665
17.8k
      ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4666
17.8k
}
4667
4668
/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4669
/// expr and the same for @c alignof and @c __alignof
4670
/// Note that the ArgRange is invalid if isType is false.
4671
ExprResult
4672
Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4673
                                    UnaryExprOrTypeTrait ExprKind, bool IsType,
4674
79.9k
                                    void *TyOrEx, SourceRange ArgRange) {
4675
  // If error parsing type, ignore.
4676
79.9k
  if (!TyOrEx) 
return ExprError()35
;
4677
4678
79.9k
  if (IsType) {
4679
66.4k
    TypeSourceInfo *TInfo;
4680
66.4k
    (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4681
66.4k
    return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4682
66.4k
  }
4683
4684
13.5k
  Expr *ArgEx = (Expr *)TyOrEx;
4685
13.5k
  ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4686
13.5k
  return Result;
4687
79.9k
}
4688
4689
static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4690
365
                                     bool IsReal) {
4691
365
  if (V.get()->isTypeDependent())
4692
0
    return S.Context.DependentTy;
4693
4694
  // _Real and _Imag are only l-values for normal l-values.
4695
365
  if (V.get()->getObjectKind() != OK_Ordinary) {
4696
0
    V = S.DefaultLvalueConversion(V.get());
4697
0
    if (V.isInvalid())
4698
0
      return QualType();
4699
0
  }
4700
4701
  // These operators return the element type of a complex type.
4702
365
  if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4703
258
    return CT->getElementType();
4704
4705
  // Otherwise they pass through real integer and floating point types here.
4706
107
  if (V.get()->getType()->isArithmeticType())
4707
90
    return V.get()->getType();
4708
4709
  // Test for placeholders.
4710
17
  ExprResult PR = S.CheckPlaceholderExpr(V.get());
4711
17
  if (PR.isInvalid()) 
return QualType()0
;
4712
17
  if (PR.get() != V.get()) {
4713
0
    V = PR;
4714
0
    return CheckRealImagOperand(S, V, Loc, IsReal);
4715
0
  }
4716
4717
  // Reject anything else.
4718
17
  S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4719
17
    << (IsReal ? 
"__real"9
:
"__imag"8
);
4720
17
  return QualType();
4721
17
}
4722
4723
4724
4725
ExprResult
4726
Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4727
43.2k
                          tok::TokenKind Kind, Expr *Input) {
4728
43.2k
  UnaryOperatorKind Opc;
4729
43.2k
  switch (Kind) {
4730
0
  default: llvm_unreachable("Unknown unary op!");
4731
41.8k
  case tok::plusplus:   Opc = UO_PostInc; break;
4732
1.48k
  case tok::minusminus: Opc = UO_PostDec; break;
4733
43.2k
  }
4734
4735
  // Since this might is a postfix expression, get rid of ParenListExprs.
4736
43.2k
  ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4737
43.2k
  if (Result.isInvalid()) 
return ExprError()0
;
4738
43.2k
  Input = Result.get();
4739
4740
43.2k
  return BuildUnaryOp(S, OpLoc, Opc, Input);
4741
43.2k
}
4742
4743
/// Diagnose if arithmetic on the given ObjC pointer is illegal.
4744
///
4745
/// \return true on error
4746
static bool checkArithmeticOnObjCPointer(Sema &S,
4747
                                         SourceLocation opLoc,
4748
16
                                         Expr *op) {
4749
16
  assert(op->getType()->isObjCObjectPointerType());
4750
16
  if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4751
16
      
!S.LangOpts.ObjCSubscriptingLegacyRuntime11
)
4752
11
    return false;
4753
4754
5
  S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4755
5
    << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4756
5
    << op->getSourceRange();
4757
5
  return true;
4758
16
}
4759
4760
159
static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4761
159
  auto *BaseNoParens = Base->IgnoreParens();
4762
159
  if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4763
76
    return MSProp->getPropertyDecl()->getType()->isArrayType();
4764
83
  return isa<MSPropertySubscriptExpr>(BaseNoParens);
4765
159
}
4766
4767
// Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
4768
// Typically this is DependentTy, but can sometimes be more precise.
4769
//
4770
// There are cases when we could determine a non-dependent type:
4771
//  - LHS and RHS may have non-dependent types despite being type-dependent
4772
//    (e.g. unbounded array static members of the current instantiation)
4773
//  - one may be a dependent-sized array with known element type
4774
//  - one may be a dependent-typed valid index (enum in current instantiation)
4775
//
4776
// We *always* return a dependent type, in such cases it is DependentTy.
4777
// This avoids creating type-dependent expressions with non-dependent types.
4778
// FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
4779
static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS,
4780
62.6k
                                               const ASTContext &Ctx) {
4781
62.6k
  assert(LHS->isTypeDependent() || RHS->isTypeDependent());
4782
0
  QualType LTy = LHS->getType(), RTy = RHS->getType();
4783
62.6k
  QualType Result = Ctx.DependentTy;
4784
62.6k
  if (RTy->isIntegralOrUnscopedEnumerationType()) {
4785
51.4k
    if (const PointerType *PT = LTy->getAs<PointerType>())
4786
32.7k
      Result = PT->getPointeeType();
4787
18.6k
    else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
4788
8.87k
      Result = AT->getElementType();
4789
51.4k
  } else 
if (11.2k
LTy->isIntegralOrUnscopedEnumerationType()11.2k
) {
4790
5
    if (const PointerType *PT = RTy->getAs<PointerType>())
4791
3
      Result = PT->getPointeeType();
4792
2
    else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
4793
2
      Result = AT->getElementType();
4794
5
  }
4795
  // Ensure we return a dependent type.
4796
62.6k
  return Result->isDependentType() ? 
Result61.6k
:
Ctx.DependentTy1.00k
;
4797
62.6k
}
4798
4799
static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args);
4800
4801
ExprResult Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base,
4802
                                         SourceLocation lbLoc,
4803
                                         MultiExprArg ArgExprs,
4804
330k
                                         SourceLocation rbLoc) {
4805
4806
330k
  if (base && !base->getType().isNull() &&
4807
330k
      
base->hasPlaceholderType(BuiltinType::OMPArraySection)330k
)
4808
255
    return ActOnOMPArraySectionExpr(base, lbLoc, ArgExprs.front(), SourceLocation(),
4809
255
                                    SourceLocation(), /*Length*/ nullptr,
4810
255
                                    /*Stride=*/nullptr, rbLoc);
4811
4812
  // Since this might be a postfix expression, get rid of ParenListExprs.
4813
330k
  if (isa<ParenListExpr>(base)) {
4814
12
    ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4815
12
    if (result.isInvalid())
4816
0
      return ExprError();
4817
12
    base = result.get();
4818
12
  }
4819
4820
  // Check if base and idx form a MatrixSubscriptExpr.
4821
  //
4822
  // Helper to check for comma expressions, which are not allowed as indices for
4823
  // matrix subscript expressions.
4824
330k
  auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4825
243
    if (isa<BinaryOperator>(E) && 
cast<BinaryOperator>(E)->isCommaOp()16
) {
4826
2
      Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4827
2
          << SourceRange(base->getBeginLoc(), rbLoc);
4828
2
      return true;
4829
2
    }
4830
241
    return false;
4831
243
  };
4832
  // The matrix subscript operator ([][])is considered a single operator.
4833
  // Separating the index expressions by parenthesis is not allowed.
4834
330k
  if (base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) &&
4835
330k
      
!isa<MatrixSubscriptExpr>(base)117
) {
4836
2
    Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4837
2
        << SourceRange(base->getBeginLoc(), rbLoc);
4838
2
    return ExprError();
4839
2
  }
4840
  // If the base is a MatrixSubscriptExpr, try to create a new
4841
  // MatrixSubscriptExpr.
4842
330k
  auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4843
330k
  if (matSubscriptE) {
4844
115
    assert(ArgExprs.size() == 1);
4845
115
    if (CheckAndReportCommaError(ArgExprs.front()))
4846
0
      return ExprError();
4847
4848
115
    assert(matSubscriptE->isIncomplete() &&
4849
115
           "base has to be an incomplete matrix subscript");
4850