Coverage Report

Created: 2020-02-25 14:32

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