Coverage Report

Created: 2022-01-18 06:27

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