1 //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
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 extra semantic analysis beyond what is enforced
10 //  by the C type system.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/APValue.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Attr.h"
17 #include "clang/AST/AttrIterator.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclBase.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclarationName.h"
24 #include "clang/AST/EvaluatedExprVisitor.h"
25 #include "clang/AST/Expr.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/ExprObjC.h"
28 #include "clang/AST/ExprOpenMP.h"
29 #include "clang/AST/FormatString.h"
30 #include "clang/AST/NSAPI.h"
31 #include "clang/AST/NonTrivialTypeVisitor.h"
32 #include "clang/AST/OperationKinds.h"
33 #include "clang/AST/RecordLayout.h"
34 #include "clang/AST/Stmt.h"
35 #include "clang/AST/TemplateBase.h"
36 #include "clang/AST/Type.h"
37 #include "clang/AST/TypeLoc.h"
38 #include "clang/AST/UnresolvedSet.h"
39 #include "clang/Basic/AddressSpaces.h"
40 #include "clang/Basic/CharInfo.h"
41 #include "clang/Basic/Diagnostic.h"
42 #include "clang/Basic/IdentifierTable.h"
43 #include "clang/Basic/LLVM.h"
44 #include "clang/Basic/LangOptions.h"
45 #include "clang/Basic/OpenCLOptions.h"
46 #include "clang/Basic/OperatorKinds.h"
47 #include "clang/Basic/PartialDiagnostic.h"
48 #include "clang/Basic/SourceLocation.h"
49 #include "clang/Basic/SourceManager.h"
50 #include "clang/Basic/Specifiers.h"
51 #include "clang/Basic/SyncScope.h"
52 #include "clang/Basic/TargetBuiltins.h"
53 #include "clang/Basic/TargetCXXABI.h"
54 #include "clang/Basic/TargetInfo.h"
55 #include "clang/Basic/TypeTraits.h"
56 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
57 #include "clang/Sema/Initialization.h"
58 #include "clang/Sema/Lookup.h"
59 #include "clang/Sema/Ownership.h"
60 #include "clang/Sema/Scope.h"
61 #include "clang/Sema/ScopeInfo.h"
62 #include "clang/Sema/Sema.h"
63 #include "clang/Sema/SemaInternal.h"
64 #include "llvm/ADT/APFloat.h"
65 #include "llvm/ADT/APInt.h"
66 #include "llvm/ADT/APSInt.h"
67 #include "llvm/ADT/ArrayRef.h"
68 #include "llvm/ADT/DenseMap.h"
69 #include "llvm/ADT/FoldingSet.h"
70 #include "llvm/ADT/None.h"
71 #include "llvm/ADT/Optional.h"
72 #include "llvm/ADT/STLExtras.h"
73 #include "llvm/ADT/SmallBitVector.h"
74 #include "llvm/ADT/SmallPtrSet.h"
75 #include "llvm/ADT/SmallString.h"
76 #include "llvm/ADT/SmallVector.h"
77 #include "llvm/ADT/StringRef.h"
78 #include "llvm/ADT/StringSwitch.h"
79 #include "llvm/ADT/Triple.h"
80 #include "llvm/Support/AtomicOrdering.h"
81 #include "llvm/Support/Casting.h"
82 #include "llvm/Support/Compiler.h"
83 #include "llvm/Support/ConvertUTF.h"
84 #include "llvm/Support/ErrorHandling.h"
85 #include "llvm/Support/Format.h"
86 #include "llvm/Support/Locale.h"
87 #include "llvm/Support/MathExtras.h"
88 #include "llvm/Support/SaveAndRestore.h"
89 #include "llvm/Support/raw_ostream.h"
90 #include <algorithm>
91 #include <cassert>
92 #include <cstddef>
93 #include <cstdint>
94 #include <functional>
95 #include <limits>
96 #include <string>
97 #include <tuple>
98 #include <utility>
99 
100 using namespace clang;
101 using namespace sema;
102 
103 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
104                                                     unsigned ByteNo) const {
105   return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
106                                Context.getTargetInfo());
107 }
108 
109 /// Checks that a call expression's argument count is the desired number.
110 /// This is useful when doing custom type-checking.  Returns true on error.
111 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
112   unsigned argCount = call->getNumArgs();
113   if (argCount == desiredArgCount) return false;
114 
115   if (argCount < desiredArgCount)
116     return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args)
117            << 0 /*function call*/ << desiredArgCount << argCount
118            << call->getSourceRange();
119 
120   // Highlight all the excess arguments.
121   SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(),
122                     call->getArg(argCount - 1)->getEndLoc());
123 
124   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
125     << 0 /*function call*/ << desiredArgCount << argCount
126     << call->getArg(1)->getSourceRange();
127 }
128 
129 /// Check that the first argument to __builtin_annotation is an integer
130 /// and the second argument is a non-wide string literal.
131 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
132   if (checkArgCount(S, TheCall, 2))
133     return true;
134 
135   // First argument should be an integer.
136   Expr *ValArg = TheCall->getArg(0);
137   QualType Ty = ValArg->getType();
138   if (!Ty->isIntegerType()) {
139     S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
140         << ValArg->getSourceRange();
141     return true;
142   }
143 
144   // Second argument should be a constant string.
145   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
146   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
147   if (!Literal || !Literal->isAscii()) {
148     S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
149         << StrArg->getSourceRange();
150     return true;
151   }
152 
153   TheCall->setType(Ty);
154   return false;
155 }
156 
157 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
158   // We need at least one argument.
159   if (TheCall->getNumArgs() < 1) {
160     S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
161         << 0 << 1 << TheCall->getNumArgs()
162         << TheCall->getCallee()->getSourceRange();
163     return true;
164   }
165 
166   // All arguments should be wide string literals.
167   for (Expr *Arg : TheCall->arguments()) {
168     auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
169     if (!Literal || !Literal->isWide()) {
170       S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
171           << Arg->getSourceRange();
172       return true;
173     }
174   }
175 
176   return false;
177 }
178 
179 /// Check that the argument to __builtin_addressof is a glvalue, and set the
180 /// result type to the corresponding pointer type.
181 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
182   if (checkArgCount(S, TheCall, 1))
183     return true;
184 
185   ExprResult Arg(TheCall->getArg(0));
186   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
187   if (ResultType.isNull())
188     return true;
189 
190   TheCall->setArg(0, Arg.get());
191   TheCall->setType(ResultType);
192   return false;
193 }
194 
195 /// Check the number of arguments and set the result type to
196 /// the argument type.
197 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
198   if (checkArgCount(S, TheCall, 1))
199     return true;
200 
201   TheCall->setType(TheCall->getArg(0)->getType());
202   return false;
203 }
204 
205 /// Check that the value argument for __builtin_is_aligned(value, alignment) and
206 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
207 /// type (but not a function pointer) and that the alignment is a power-of-two.
208 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
209   if (checkArgCount(S, TheCall, 2))
210     return true;
211 
212   clang::Expr *Source = TheCall->getArg(0);
213   bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
214 
215   auto IsValidIntegerType = [](QualType Ty) {
216     return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
217   };
218   QualType SrcTy = Source->getType();
219   // We should also be able to use it with arrays (but not functions!).
220   if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
221     SrcTy = S.Context.getDecayedType(SrcTy);
222   }
223   if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
224       SrcTy->isFunctionPointerType()) {
225     // FIXME: this is not quite the right error message since we don't allow
226     // floating point types, or member pointers.
227     S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
228         << SrcTy;
229     return true;
230   }
231 
232   clang::Expr *AlignOp = TheCall->getArg(1);
233   if (!IsValidIntegerType(AlignOp->getType())) {
234     S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
235         << AlignOp->getType();
236     return true;
237   }
238   Expr::EvalResult AlignResult;
239   unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
240   // We can't check validity of alignment if it is type dependent.
241   if (!AlignOp->isInstantiationDependent() &&
242       AlignOp->EvaluateAsInt(AlignResult, S.Context,
243                              Expr::SE_AllowSideEffects)) {
244     llvm::APSInt AlignValue = AlignResult.Val.getInt();
245     llvm::APSInt MaxValue(
246         llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
247     if (AlignValue < 1) {
248       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
249       return true;
250     }
251     if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
252       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
253           << MaxValue.toString(10);
254       return true;
255     }
256     if (!AlignValue.isPowerOf2()) {
257       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
258       return true;
259     }
260     if (AlignValue == 1) {
261       S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
262           << IsBooleanAlignBuiltin;
263     }
264   }
265 
266   ExprResult SrcArg = S.PerformCopyInitialization(
267       InitializedEntity::InitializeParameter(S.Context, SrcTy, false),
268       SourceLocation(), Source);
269   if (SrcArg.isInvalid())
270     return true;
271   TheCall->setArg(0, SrcArg.get());
272   ExprResult AlignArg =
273       S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
274                                       S.Context, AlignOp->getType(), false),
275                                   SourceLocation(), AlignOp);
276   if (AlignArg.isInvalid())
277     return true;
278   TheCall->setArg(1, AlignArg.get());
279   // For align_up/align_down, the return type is the same as the (potentially
280   // decayed) argument type including qualifiers. For is_aligned(), the result
281   // is always bool.
282   TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
283   return false;
284 }
285 
286 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
287   if (checkArgCount(S, TheCall, 3))
288     return true;
289 
290   // First two arguments should be integers.
291   for (unsigned I = 0; I < 2; ++I) {
292     ExprResult Arg = TheCall->getArg(I);
293     QualType Ty = Arg.get()->getType();
294     if (!Ty->isIntegerType()) {
295       S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
296           << Ty << Arg.get()->getSourceRange();
297       return true;
298     }
299     InitializedEntity Entity = InitializedEntity::InitializeParameter(
300         S.getASTContext(), Ty, /*consume*/ false);
301     Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
302     if (Arg.isInvalid())
303       return true;
304     TheCall->setArg(I, Arg.get());
305   }
306 
307   // Third argument should be a pointer to a non-const integer.
308   // IRGen correctly handles volatile, restrict, and address spaces, and
309   // the other qualifiers aren't possible.
310   {
311     ExprResult Arg = TheCall->getArg(2);
312     QualType Ty = Arg.get()->getType();
313     const auto *PtrTy = Ty->getAs<PointerType>();
314     if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
315           !PtrTy->getPointeeType().isConstQualified())) {
316       S.Diag(Arg.get()->getBeginLoc(),
317              diag::err_overflow_builtin_must_be_ptr_int)
318           << Ty << Arg.get()->getSourceRange();
319       return true;
320     }
321     InitializedEntity Entity = InitializedEntity::InitializeParameter(
322         S.getASTContext(), Ty, /*consume*/ false);
323     Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
324     if (Arg.isInvalid())
325       return true;
326     TheCall->setArg(2, Arg.get());
327   }
328   return false;
329 }
330 
331 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
332   if (checkArgCount(S, BuiltinCall, 2))
333     return true;
334 
335   SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
336   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
337   Expr *Call = BuiltinCall->getArg(0);
338   Expr *Chain = BuiltinCall->getArg(1);
339 
340   if (Call->getStmtClass() != Stmt::CallExprClass) {
341     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
342         << Call->getSourceRange();
343     return true;
344   }
345 
346   auto CE = cast<CallExpr>(Call);
347   if (CE->getCallee()->getType()->isBlockPointerType()) {
348     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
349         << Call->getSourceRange();
350     return true;
351   }
352 
353   const Decl *TargetDecl = CE->getCalleeDecl();
354   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
355     if (FD->getBuiltinID()) {
356       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
357           << Call->getSourceRange();
358       return true;
359     }
360 
361   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
362     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
363         << Call->getSourceRange();
364     return true;
365   }
366 
367   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
368   if (ChainResult.isInvalid())
369     return true;
370   if (!ChainResult.get()->getType()->isPointerType()) {
371     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
372         << Chain->getSourceRange();
373     return true;
374   }
375 
376   QualType ReturnTy = CE->getCallReturnType(S.Context);
377   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
378   QualType BuiltinTy = S.Context.getFunctionType(
379       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
380   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
381 
382   Builtin =
383       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
384 
385   BuiltinCall->setType(CE->getType());
386   BuiltinCall->setValueKind(CE->getValueKind());
387   BuiltinCall->setObjectKind(CE->getObjectKind());
388   BuiltinCall->setCallee(Builtin);
389   BuiltinCall->setArg(1, ChainResult.get());
390 
391   return false;
392 }
393 
394 namespace {
395 
396 class EstimateSizeFormatHandler
397     : public analyze_format_string::FormatStringHandler {
398   size_t Size;
399 
400 public:
401   EstimateSizeFormatHandler(StringRef Format)
402       : Size(std::min(Format.find(0), Format.size()) +
403              1 /* null byte always written by sprintf */) {}
404 
405   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
406                              const char *, unsigned SpecifierLen) override {
407 
408     const size_t FieldWidth = computeFieldWidth(FS);
409     const size_t Precision = computePrecision(FS);
410 
411     // The actual format.
412     switch (FS.getConversionSpecifier().getKind()) {
413     // Just a char.
414     case analyze_format_string::ConversionSpecifier::cArg:
415     case analyze_format_string::ConversionSpecifier::CArg:
416       Size += std::max(FieldWidth, (size_t)1);
417       break;
418     // Just an integer.
419     case analyze_format_string::ConversionSpecifier::dArg:
420     case analyze_format_string::ConversionSpecifier::DArg:
421     case analyze_format_string::ConversionSpecifier::iArg:
422     case analyze_format_string::ConversionSpecifier::oArg:
423     case analyze_format_string::ConversionSpecifier::OArg:
424     case analyze_format_string::ConversionSpecifier::uArg:
425     case analyze_format_string::ConversionSpecifier::UArg:
426     case analyze_format_string::ConversionSpecifier::xArg:
427     case analyze_format_string::ConversionSpecifier::XArg:
428       Size += std::max(FieldWidth, Precision);
429       break;
430 
431     // %g style conversion switches between %f or %e style dynamically.
432     // %f always takes less space, so default to it.
433     case analyze_format_string::ConversionSpecifier::gArg:
434     case analyze_format_string::ConversionSpecifier::GArg:
435 
436     // Floating point number in the form '[+]ddd.ddd'.
437     case analyze_format_string::ConversionSpecifier::fArg:
438     case analyze_format_string::ConversionSpecifier::FArg:
439       Size += std::max(FieldWidth, 1 /* integer part */ +
440                                        (Precision ? 1 + Precision
441                                                   : 0) /* period + decimal */);
442       break;
443 
444     // Floating point number in the form '[-]d.ddde[+-]dd'.
445     case analyze_format_string::ConversionSpecifier::eArg:
446     case analyze_format_string::ConversionSpecifier::EArg:
447       Size +=
448           std::max(FieldWidth,
449                    1 /* integer part */ +
450                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
451                        1 /* e or E letter */ + 2 /* exponent */);
452       break;
453 
454     // Floating point number in the form '[-]0xh.hhhhp±dd'.
455     case analyze_format_string::ConversionSpecifier::aArg:
456     case analyze_format_string::ConversionSpecifier::AArg:
457       Size +=
458           std::max(FieldWidth,
459                    2 /* 0x */ + 1 /* integer part */ +
460                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
461                        1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
462       break;
463 
464     // Just a string.
465     case analyze_format_string::ConversionSpecifier::sArg:
466     case analyze_format_string::ConversionSpecifier::SArg:
467       Size += FieldWidth;
468       break;
469 
470     // Just a pointer in the form '0xddd'.
471     case analyze_format_string::ConversionSpecifier::pArg:
472       Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
473       break;
474 
475     // A plain percent.
476     case analyze_format_string::ConversionSpecifier::PercentArg:
477       Size += 1;
478       break;
479 
480     default:
481       break;
482     }
483 
484     Size += FS.hasPlusPrefix() || FS.hasSpacePrefix();
485 
486     if (FS.hasAlternativeForm()) {
487       switch (FS.getConversionSpecifier().getKind()) {
488       default:
489         break;
490       // Force a leading '0'.
491       case analyze_format_string::ConversionSpecifier::oArg:
492         Size += 1;
493         break;
494       // Force a leading '0x'.
495       case analyze_format_string::ConversionSpecifier::xArg:
496       case analyze_format_string::ConversionSpecifier::XArg:
497         Size += 2;
498         break;
499       // Force a period '.' before decimal, even if precision is 0.
500       case analyze_format_string::ConversionSpecifier::aArg:
501       case analyze_format_string::ConversionSpecifier::AArg:
502       case analyze_format_string::ConversionSpecifier::eArg:
503       case analyze_format_string::ConversionSpecifier::EArg:
504       case analyze_format_string::ConversionSpecifier::fArg:
505       case analyze_format_string::ConversionSpecifier::FArg:
506       case analyze_format_string::ConversionSpecifier::gArg:
507       case analyze_format_string::ConversionSpecifier::GArg:
508         Size += (Precision ? 0 : 1);
509         break;
510       }
511     }
512     assert(SpecifierLen <= Size && "no underflow");
513     Size -= SpecifierLen;
514     return true;
515   }
516 
517   size_t getSizeLowerBound() const { return Size; }
518 
519 private:
520   static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
521     const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
522     size_t FieldWidth = 0;
523     if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant)
524       FieldWidth = FW.getConstantAmount();
525     return FieldWidth;
526   }
527 
528   static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
529     const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
530     size_t Precision = 0;
531 
532     // See man 3 printf for default precision value based on the specifier.
533     switch (FW.getHowSpecified()) {
534     case analyze_format_string::OptionalAmount::NotSpecified:
535       switch (FS.getConversionSpecifier().getKind()) {
536       default:
537         break;
538       case analyze_format_string::ConversionSpecifier::dArg: // %d
539       case analyze_format_string::ConversionSpecifier::DArg: // %D
540       case analyze_format_string::ConversionSpecifier::iArg: // %i
541         Precision = 1;
542         break;
543       case analyze_format_string::ConversionSpecifier::oArg: // %d
544       case analyze_format_string::ConversionSpecifier::OArg: // %D
545       case analyze_format_string::ConversionSpecifier::uArg: // %d
546       case analyze_format_string::ConversionSpecifier::UArg: // %D
547       case analyze_format_string::ConversionSpecifier::xArg: // %d
548       case analyze_format_string::ConversionSpecifier::XArg: // %D
549         Precision = 1;
550         break;
551       case analyze_format_string::ConversionSpecifier::fArg: // %f
552       case analyze_format_string::ConversionSpecifier::FArg: // %F
553       case analyze_format_string::ConversionSpecifier::eArg: // %e
554       case analyze_format_string::ConversionSpecifier::EArg: // %E
555       case analyze_format_string::ConversionSpecifier::gArg: // %g
556       case analyze_format_string::ConversionSpecifier::GArg: // %G
557         Precision = 6;
558         break;
559       case analyze_format_string::ConversionSpecifier::pArg: // %d
560         Precision = 1;
561         break;
562       }
563       break;
564     case analyze_format_string::OptionalAmount::Constant:
565       Precision = FW.getConstantAmount();
566       break;
567     default:
568       break;
569     }
570     return Precision;
571   }
572 };
573 
574 } // namespace
575 
576 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a
577 /// __builtin_*_chk function, then use the object size argument specified in the
578 /// source. Otherwise, infer the object size using __builtin_object_size.
579 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
580                                                CallExpr *TheCall) {
581   // FIXME: There are some more useful checks we could be doing here:
582   //  - Evaluate strlen of strcpy arguments, use as object size.
583 
584   if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
585       isConstantEvaluated())
586     return;
587 
588   unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
589   if (!BuiltinID)
590     return;
591 
592   const TargetInfo &TI = getASTContext().getTargetInfo();
593   unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
594 
595   unsigned DiagID = 0;
596   bool IsChkVariant = false;
597   Optional<llvm::APSInt> UsedSize;
598   unsigned SizeIndex, ObjectIndex;
599   switch (BuiltinID) {
600   default:
601     return;
602   case Builtin::BIsprintf:
603   case Builtin::BI__builtin___sprintf_chk: {
604     size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
605     auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
606 
607     if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) {
608 
609       if (!Format->isAscii() && !Format->isUTF8())
610         return;
611 
612       StringRef FormatStrRef = Format->getString();
613       EstimateSizeFormatHandler H(FormatStrRef);
614       const char *FormatBytes = FormatStrRef.data();
615       const ConstantArrayType *T =
616           Context.getAsConstantArrayType(Format->getType());
617       assert(T && "String literal not of constant array type!");
618       size_t TypeSize = T->getSize().getZExtValue();
619 
620       // In case there's a null byte somewhere.
621       size_t StrLen =
622           std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
623       if (!analyze_format_string::ParsePrintfString(
624               H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
625               Context.getTargetInfo(), false)) {
626         DiagID = diag::warn_fortify_source_format_overflow;
627         UsedSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
628                        .extOrTrunc(SizeTypeWidth);
629         if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
630           IsChkVariant = true;
631           ObjectIndex = 2;
632         } else {
633           IsChkVariant = false;
634           ObjectIndex = 0;
635         }
636         break;
637       }
638     }
639     return;
640   }
641   case Builtin::BI__builtin___memcpy_chk:
642   case Builtin::BI__builtin___memmove_chk:
643   case Builtin::BI__builtin___memset_chk:
644   case Builtin::BI__builtin___strlcat_chk:
645   case Builtin::BI__builtin___strlcpy_chk:
646   case Builtin::BI__builtin___strncat_chk:
647   case Builtin::BI__builtin___strncpy_chk:
648   case Builtin::BI__builtin___stpncpy_chk:
649   case Builtin::BI__builtin___memccpy_chk:
650   case Builtin::BI__builtin___mempcpy_chk: {
651     DiagID = diag::warn_builtin_chk_overflow;
652     IsChkVariant = true;
653     SizeIndex = TheCall->getNumArgs() - 2;
654     ObjectIndex = TheCall->getNumArgs() - 1;
655     break;
656   }
657 
658   case Builtin::BI__builtin___snprintf_chk:
659   case Builtin::BI__builtin___vsnprintf_chk: {
660     DiagID = diag::warn_builtin_chk_overflow;
661     IsChkVariant = true;
662     SizeIndex = 1;
663     ObjectIndex = 3;
664     break;
665   }
666 
667   case Builtin::BIstrncat:
668   case Builtin::BI__builtin_strncat:
669   case Builtin::BIstrncpy:
670   case Builtin::BI__builtin_strncpy:
671   case Builtin::BIstpncpy:
672   case Builtin::BI__builtin_stpncpy: {
673     // Whether these functions overflow depends on the runtime strlen of the
674     // string, not just the buffer size, so emitting the "always overflow"
675     // diagnostic isn't quite right. We should still diagnose passing a buffer
676     // size larger than the destination buffer though; this is a runtime abort
677     // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
678     DiagID = diag::warn_fortify_source_size_mismatch;
679     SizeIndex = TheCall->getNumArgs() - 1;
680     ObjectIndex = 0;
681     break;
682   }
683 
684   case Builtin::BImemcpy:
685   case Builtin::BI__builtin_memcpy:
686   case Builtin::BImemmove:
687   case Builtin::BI__builtin_memmove:
688   case Builtin::BImemset:
689   case Builtin::BI__builtin_memset:
690   case Builtin::BImempcpy:
691   case Builtin::BI__builtin_mempcpy: {
692     DiagID = diag::warn_fortify_source_overflow;
693     SizeIndex = TheCall->getNumArgs() - 1;
694     ObjectIndex = 0;
695     break;
696   }
697   case Builtin::BIsnprintf:
698   case Builtin::BI__builtin_snprintf:
699   case Builtin::BIvsnprintf:
700   case Builtin::BI__builtin_vsnprintf: {
701     DiagID = diag::warn_fortify_source_size_mismatch;
702     SizeIndex = 1;
703     ObjectIndex = 0;
704     break;
705   }
706   }
707 
708   llvm::APSInt ObjectSize;
709   // For __builtin___*_chk, the object size is explicitly provided by the caller
710   // (usually using __builtin_object_size). Use that value to check this call.
711   if (IsChkVariant) {
712     Expr::EvalResult Result;
713     Expr *SizeArg = TheCall->getArg(ObjectIndex);
714     if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
715       return;
716     ObjectSize = Result.Val.getInt();
717 
718   // Otherwise, try to evaluate an imaginary call to __builtin_object_size.
719   } else {
720     // If the parameter has a pass_object_size attribute, then we should use its
721     // (potentially) more strict checking mode. Otherwise, conservatively assume
722     // type 0.
723     int BOSType = 0;
724     if (const auto *POS =
725             FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>())
726       BOSType = POS->getType();
727 
728     Expr *ObjArg = TheCall->getArg(ObjectIndex);
729     uint64_t Result;
730     if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
731       return;
732     // Get the object size in the target's size_t width.
733     ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
734   }
735 
736   // Evaluate the number of bytes of the object that this call will use.
737   if (!UsedSize) {
738     Expr::EvalResult Result;
739     Expr *UsedSizeArg = TheCall->getArg(SizeIndex);
740     if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext()))
741       return;
742     UsedSize = Result.Val.getInt().extOrTrunc(SizeTypeWidth);
743   }
744 
745   if (UsedSize.getValue().ule(ObjectSize))
746     return;
747 
748   StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
749   // Skim off the details of whichever builtin was called to produce a better
750   // diagnostic, as it's unlikley that the user wrote the __builtin explicitly.
751   if (IsChkVariant) {
752     FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
753     FunctionName = FunctionName.drop_back(std::strlen("_chk"));
754   } else if (FunctionName.startswith("__builtin_")) {
755     FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
756   }
757 
758   DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
759                       PDiag(DiagID)
760                           << FunctionName << ObjectSize.toString(/*Radix=*/10)
761                           << UsedSize.getValue().toString(/*Radix=*/10));
762 }
763 
764 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
765                                      Scope::ScopeFlags NeededScopeFlags,
766                                      unsigned DiagID) {
767   // Scopes aren't available during instantiation. Fortunately, builtin
768   // functions cannot be template args so they cannot be formed through template
769   // instantiation. Therefore checking once during the parse is sufficient.
770   if (SemaRef.inTemplateInstantiation())
771     return false;
772 
773   Scope *S = SemaRef.getCurScope();
774   while (S && !S->isSEHExceptScope())
775     S = S->getParent();
776   if (!S || !(S->getFlags() & NeededScopeFlags)) {
777     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
778     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
779         << DRE->getDecl()->getIdentifier();
780     return true;
781   }
782 
783   return false;
784 }
785 
786 static inline bool isBlockPointer(Expr *Arg) {
787   return Arg->getType()->isBlockPointerType();
788 }
789 
790 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
791 /// void*, which is a requirement of device side enqueue.
792 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
793   const BlockPointerType *BPT =
794       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
795   ArrayRef<QualType> Params =
796       BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
797   unsigned ArgCounter = 0;
798   bool IllegalParams = false;
799   // Iterate through the block parameters until either one is found that is not
800   // a local void*, or the block is valid.
801   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
802        I != E; ++I, ++ArgCounter) {
803     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
804         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
805             LangAS::opencl_local) {
806       // Get the location of the error. If a block literal has been passed
807       // (BlockExpr) then we can point straight to the offending argument,
808       // else we just point to the variable reference.
809       SourceLocation ErrorLoc;
810       if (isa<BlockExpr>(BlockArg)) {
811         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
812         ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
813       } else if (isa<DeclRefExpr>(BlockArg)) {
814         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
815       }
816       S.Diag(ErrorLoc,
817              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
818       IllegalParams = true;
819     }
820   }
821 
822   return IllegalParams;
823 }
824 
825 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
826   if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
827     S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
828         << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
829     return true;
830   }
831   return false;
832 }
833 
834 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
835   if (checkArgCount(S, TheCall, 2))
836     return true;
837 
838   if (checkOpenCLSubgroupExt(S, TheCall))
839     return true;
840 
841   // First argument is an ndrange_t type.
842   Expr *NDRangeArg = TheCall->getArg(0);
843   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
844     S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
845         << TheCall->getDirectCallee() << "'ndrange_t'";
846     return true;
847   }
848 
849   Expr *BlockArg = TheCall->getArg(1);
850   if (!isBlockPointer(BlockArg)) {
851     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
852         << TheCall->getDirectCallee() << "block";
853     return true;
854   }
855   return checkOpenCLBlockArgs(S, BlockArg);
856 }
857 
858 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
859 /// get_kernel_work_group_size
860 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
861 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
862   if (checkArgCount(S, TheCall, 1))
863     return true;
864 
865   Expr *BlockArg = TheCall->getArg(0);
866   if (!isBlockPointer(BlockArg)) {
867     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
868         << TheCall->getDirectCallee() << "block";
869     return true;
870   }
871   return checkOpenCLBlockArgs(S, BlockArg);
872 }
873 
874 /// Diagnose integer type and any valid implicit conversion to it.
875 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
876                                       const QualType &IntType);
877 
878 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
879                                             unsigned Start, unsigned End) {
880   bool IllegalParams = false;
881   for (unsigned I = Start; I <= End; ++I)
882     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
883                                               S.Context.getSizeType());
884   return IllegalParams;
885 }
886 
887 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
888 /// 'local void*' parameter of passed block.
889 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
890                                            Expr *BlockArg,
891                                            unsigned NumNonVarArgs) {
892   const BlockPointerType *BPT =
893       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
894   unsigned NumBlockParams =
895       BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
896   unsigned TotalNumArgs = TheCall->getNumArgs();
897 
898   // For each argument passed to the block, a corresponding uint needs to
899   // be passed to describe the size of the local memory.
900   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
901     S.Diag(TheCall->getBeginLoc(),
902            diag::err_opencl_enqueue_kernel_local_size_args);
903     return true;
904   }
905 
906   // Check that the sizes of the local memory are specified by integers.
907   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
908                                          TotalNumArgs - 1);
909 }
910 
911 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
912 /// overload formats specified in Table 6.13.17.1.
913 /// int enqueue_kernel(queue_t queue,
914 ///                    kernel_enqueue_flags_t flags,
915 ///                    const ndrange_t ndrange,
916 ///                    void (^block)(void))
917 /// int enqueue_kernel(queue_t queue,
918 ///                    kernel_enqueue_flags_t flags,
919 ///                    const ndrange_t ndrange,
920 ///                    uint num_events_in_wait_list,
921 ///                    clk_event_t *event_wait_list,
922 ///                    clk_event_t *event_ret,
923 ///                    void (^block)(void))
924 /// int enqueue_kernel(queue_t queue,
925 ///                    kernel_enqueue_flags_t flags,
926 ///                    const ndrange_t ndrange,
927 ///                    void (^block)(local void*, ...),
928 ///                    uint size0, ...)
929 /// int enqueue_kernel(queue_t queue,
930 ///                    kernel_enqueue_flags_t flags,
931 ///                    const ndrange_t ndrange,
932 ///                    uint num_events_in_wait_list,
933 ///                    clk_event_t *event_wait_list,
934 ///                    clk_event_t *event_ret,
935 ///                    void (^block)(local void*, ...),
936 ///                    uint size0, ...)
937 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
938   unsigned NumArgs = TheCall->getNumArgs();
939 
940   if (NumArgs < 4) {
941     S.Diag(TheCall->getBeginLoc(),
942            diag::err_typecheck_call_too_few_args_at_least)
943         << 0 << 4 << NumArgs;
944     return true;
945   }
946 
947   Expr *Arg0 = TheCall->getArg(0);
948   Expr *Arg1 = TheCall->getArg(1);
949   Expr *Arg2 = TheCall->getArg(2);
950   Expr *Arg3 = TheCall->getArg(3);
951 
952   // First argument always needs to be a queue_t type.
953   if (!Arg0->getType()->isQueueT()) {
954     S.Diag(TheCall->getArg(0)->getBeginLoc(),
955            diag::err_opencl_builtin_expected_type)
956         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
957     return true;
958   }
959 
960   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
961   if (!Arg1->getType()->isIntegerType()) {
962     S.Diag(TheCall->getArg(1)->getBeginLoc(),
963            diag::err_opencl_builtin_expected_type)
964         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
965     return true;
966   }
967 
968   // Third argument is always an ndrange_t type.
969   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
970     S.Diag(TheCall->getArg(2)->getBeginLoc(),
971            diag::err_opencl_builtin_expected_type)
972         << TheCall->getDirectCallee() << "'ndrange_t'";
973     return true;
974   }
975 
976   // With four arguments, there is only one form that the function could be
977   // called in: no events and no variable arguments.
978   if (NumArgs == 4) {
979     // check that the last argument is the right block type.
980     if (!isBlockPointer(Arg3)) {
981       S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
982           << TheCall->getDirectCallee() << "block";
983       return true;
984     }
985     // we have a block type, check the prototype
986     const BlockPointerType *BPT =
987         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
988     if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
989       S.Diag(Arg3->getBeginLoc(),
990              diag::err_opencl_enqueue_kernel_blocks_no_args);
991       return true;
992     }
993     return false;
994   }
995   // we can have block + varargs.
996   if (isBlockPointer(Arg3))
997     return (checkOpenCLBlockArgs(S, Arg3) ||
998             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
999   // last two cases with either exactly 7 args or 7 args and varargs.
1000   if (NumArgs >= 7) {
1001     // check common block argument.
1002     Expr *Arg6 = TheCall->getArg(6);
1003     if (!isBlockPointer(Arg6)) {
1004       S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1005           << TheCall->getDirectCallee() << "block";
1006       return true;
1007     }
1008     if (checkOpenCLBlockArgs(S, Arg6))
1009       return true;
1010 
1011     // Forth argument has to be any integer type.
1012     if (!Arg3->getType()->isIntegerType()) {
1013       S.Diag(TheCall->getArg(3)->getBeginLoc(),
1014              diag::err_opencl_builtin_expected_type)
1015           << TheCall->getDirectCallee() << "integer";
1016       return true;
1017     }
1018     // check remaining common arguments.
1019     Expr *Arg4 = TheCall->getArg(4);
1020     Expr *Arg5 = TheCall->getArg(5);
1021 
1022     // Fifth argument is always passed as a pointer to clk_event_t.
1023     if (!Arg4->isNullPointerConstant(S.Context,
1024                                      Expr::NPC_ValueDependentIsNotNull) &&
1025         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
1026       S.Diag(TheCall->getArg(4)->getBeginLoc(),
1027              diag::err_opencl_builtin_expected_type)
1028           << TheCall->getDirectCallee()
1029           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1030       return true;
1031     }
1032 
1033     // Sixth argument is always passed as a pointer to clk_event_t.
1034     if (!Arg5->isNullPointerConstant(S.Context,
1035                                      Expr::NPC_ValueDependentIsNotNull) &&
1036         !(Arg5->getType()->isPointerType() &&
1037           Arg5->getType()->getPointeeType()->isClkEventT())) {
1038       S.Diag(TheCall->getArg(5)->getBeginLoc(),
1039              diag::err_opencl_builtin_expected_type)
1040           << TheCall->getDirectCallee()
1041           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1042       return true;
1043     }
1044 
1045     if (NumArgs == 7)
1046       return false;
1047 
1048     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
1049   }
1050 
1051   // None of the specific case has been detected, give generic error
1052   S.Diag(TheCall->getBeginLoc(),
1053          diag::err_opencl_enqueue_kernel_incorrect_args);
1054   return true;
1055 }
1056 
1057 /// Returns OpenCL access qual.
1058 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
1059     return D->getAttr<OpenCLAccessAttr>();
1060 }
1061 
1062 /// Returns true if pipe element type is different from the pointer.
1063 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
1064   const Expr *Arg0 = Call->getArg(0);
1065   // First argument type should always be pipe.
1066   if (!Arg0->getType()->isPipeType()) {
1067     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1068         << Call->getDirectCallee() << Arg0->getSourceRange();
1069     return true;
1070   }
1071   OpenCLAccessAttr *AccessQual =
1072       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
1073   // Validates the access qualifier is compatible with the call.
1074   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
1075   // read_only and write_only, and assumed to be read_only if no qualifier is
1076   // specified.
1077   switch (Call->getDirectCallee()->getBuiltinID()) {
1078   case Builtin::BIread_pipe:
1079   case Builtin::BIreserve_read_pipe:
1080   case Builtin::BIcommit_read_pipe:
1081   case Builtin::BIwork_group_reserve_read_pipe:
1082   case Builtin::BIsub_group_reserve_read_pipe:
1083   case Builtin::BIwork_group_commit_read_pipe:
1084   case Builtin::BIsub_group_commit_read_pipe:
1085     if (!(!AccessQual || AccessQual->isReadOnly())) {
1086       S.Diag(Arg0->getBeginLoc(),
1087              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1088           << "read_only" << Arg0->getSourceRange();
1089       return true;
1090     }
1091     break;
1092   case Builtin::BIwrite_pipe:
1093   case Builtin::BIreserve_write_pipe:
1094   case Builtin::BIcommit_write_pipe:
1095   case Builtin::BIwork_group_reserve_write_pipe:
1096   case Builtin::BIsub_group_reserve_write_pipe:
1097   case Builtin::BIwork_group_commit_write_pipe:
1098   case Builtin::BIsub_group_commit_write_pipe:
1099     if (!(AccessQual && AccessQual->isWriteOnly())) {
1100       S.Diag(Arg0->getBeginLoc(),
1101              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1102           << "write_only" << Arg0->getSourceRange();
1103       return true;
1104     }
1105     break;
1106   default:
1107     break;
1108   }
1109   return false;
1110 }
1111 
1112 /// Returns true if pipe element type is different from the pointer.
1113 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
1114   const Expr *Arg0 = Call->getArg(0);
1115   const Expr *ArgIdx = Call->getArg(Idx);
1116   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
1117   const QualType EltTy = PipeTy->getElementType();
1118   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
1119   // The Idx argument should be a pointer and the type of the pointer and
1120   // the type of pipe element should also be the same.
1121   if (!ArgTy ||
1122       !S.Context.hasSameType(
1123           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
1124     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1125         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
1126         << ArgIdx->getType() << ArgIdx->getSourceRange();
1127     return true;
1128   }
1129   return false;
1130 }
1131 
1132 // Performs semantic analysis for the read/write_pipe call.
1133 // \param S Reference to the semantic analyzer.
1134 // \param Call A pointer to the builtin call.
1135 // \return True if a semantic error has been found, false otherwise.
1136 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
1137   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
1138   // functions have two forms.
1139   switch (Call->getNumArgs()) {
1140   case 2:
1141     if (checkOpenCLPipeArg(S, Call))
1142       return true;
1143     // The call with 2 arguments should be
1144     // read/write_pipe(pipe T, T*).
1145     // Check packet type T.
1146     if (checkOpenCLPipePacketType(S, Call, 1))
1147       return true;
1148     break;
1149 
1150   case 4: {
1151     if (checkOpenCLPipeArg(S, Call))
1152       return true;
1153     // The call with 4 arguments should be
1154     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
1155     // Check reserve_id_t.
1156     if (!Call->getArg(1)->getType()->isReserveIDT()) {
1157       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1158           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1159           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1160       return true;
1161     }
1162 
1163     // Check the index.
1164     const Expr *Arg2 = Call->getArg(2);
1165     if (!Arg2->getType()->isIntegerType() &&
1166         !Arg2->getType()->isUnsignedIntegerType()) {
1167       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1168           << Call->getDirectCallee() << S.Context.UnsignedIntTy
1169           << Arg2->getType() << Arg2->getSourceRange();
1170       return true;
1171     }
1172 
1173     // Check packet type T.
1174     if (checkOpenCLPipePacketType(S, Call, 3))
1175       return true;
1176   } break;
1177   default:
1178     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
1179         << Call->getDirectCallee() << Call->getSourceRange();
1180     return true;
1181   }
1182 
1183   return false;
1184 }
1185 
1186 // Performs a semantic analysis on the {work_group_/sub_group_
1187 //        /_}reserve_{read/write}_pipe
1188 // \param S Reference to the semantic analyzer.
1189 // \param Call The call to the builtin function to be analyzed.
1190 // \return True if a semantic error was found, false otherwise.
1191 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
1192   if (checkArgCount(S, Call, 2))
1193     return true;
1194 
1195   if (checkOpenCLPipeArg(S, Call))
1196     return true;
1197 
1198   // Check the reserve size.
1199   if (!Call->getArg(1)->getType()->isIntegerType() &&
1200       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
1201     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1202         << Call->getDirectCallee() << S.Context.UnsignedIntTy
1203         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1204     return true;
1205   }
1206 
1207   // Since return type of reserve_read/write_pipe built-in function is
1208   // reserve_id_t, which is not defined in the builtin def file , we used int
1209   // as return type and need to override the return type of these functions.
1210   Call->setType(S.Context.OCLReserveIDTy);
1211 
1212   return false;
1213 }
1214 
1215 // Performs a semantic analysis on {work_group_/sub_group_
1216 //        /_}commit_{read/write}_pipe
1217 // \param S Reference to the semantic analyzer.
1218 // \param Call The call to the builtin function to be analyzed.
1219 // \return True if a semantic error was found, false otherwise.
1220 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
1221   if (checkArgCount(S, Call, 2))
1222     return true;
1223 
1224   if (checkOpenCLPipeArg(S, Call))
1225     return true;
1226 
1227   // Check reserve_id_t.
1228   if (!Call->getArg(1)->getType()->isReserveIDT()) {
1229     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1230         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1231         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1232     return true;
1233   }
1234 
1235   return false;
1236 }
1237 
1238 // Performs a semantic analysis on the call to built-in Pipe
1239 //        Query Functions.
1240 // \param S Reference to the semantic analyzer.
1241 // \param Call The call to the builtin function to be analyzed.
1242 // \return True if a semantic error was found, false otherwise.
1243 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
1244   if (checkArgCount(S, Call, 1))
1245     return true;
1246 
1247   if (!Call->getArg(0)->getType()->isPipeType()) {
1248     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1249         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
1250     return true;
1251   }
1252 
1253   return false;
1254 }
1255 
1256 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
1257 // Performs semantic analysis for the to_global/local/private call.
1258 // \param S Reference to the semantic analyzer.
1259 // \param BuiltinID ID of the builtin function.
1260 // \param Call A pointer to the builtin call.
1261 // \return True if a semantic error has been found, false otherwise.
1262 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
1263                                     CallExpr *Call) {
1264   if (Call->getNumArgs() != 1) {
1265     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num)
1266         << Call->getDirectCallee() << Call->getSourceRange();
1267     return true;
1268   }
1269 
1270   auto RT = Call->getArg(0)->getType();
1271   if (!RT->isPointerType() || RT->getPointeeType()
1272       .getAddressSpace() == LangAS::opencl_constant) {
1273     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
1274         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
1275     return true;
1276   }
1277 
1278   if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
1279     S.Diag(Call->getArg(0)->getBeginLoc(),
1280            diag::warn_opencl_generic_address_space_arg)
1281         << Call->getDirectCallee()->getNameInfo().getAsString()
1282         << Call->getArg(0)->getSourceRange();
1283   }
1284 
1285   RT = RT->getPointeeType();
1286   auto Qual = RT.getQualifiers();
1287   switch (BuiltinID) {
1288   case Builtin::BIto_global:
1289     Qual.setAddressSpace(LangAS::opencl_global);
1290     break;
1291   case Builtin::BIto_local:
1292     Qual.setAddressSpace(LangAS::opencl_local);
1293     break;
1294   case Builtin::BIto_private:
1295     Qual.setAddressSpace(LangAS::opencl_private);
1296     break;
1297   default:
1298     llvm_unreachable("Invalid builtin function");
1299   }
1300   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
1301       RT.getUnqualifiedType(), Qual)));
1302 
1303   return false;
1304 }
1305 
1306 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
1307   if (checkArgCount(S, TheCall, 1))
1308     return ExprError();
1309 
1310   // Compute __builtin_launder's parameter type from the argument.
1311   // The parameter type is:
1312   //  * The type of the argument if it's not an array or function type,
1313   //  Otherwise,
1314   //  * The decayed argument type.
1315   QualType ParamTy = [&]() {
1316     QualType ArgTy = TheCall->getArg(0)->getType();
1317     if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1318       return S.Context.getPointerType(Ty->getElementType());
1319     if (ArgTy->isFunctionType()) {
1320       return S.Context.getPointerType(ArgTy);
1321     }
1322     return ArgTy;
1323   }();
1324 
1325   TheCall->setType(ParamTy);
1326 
1327   auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1328     if (!ParamTy->isPointerType())
1329       return 0;
1330     if (ParamTy->isFunctionPointerType())
1331       return 1;
1332     if (ParamTy->isVoidPointerType())
1333       return 2;
1334     return llvm::Optional<unsigned>{};
1335   }();
1336   if (DiagSelect.hasValue()) {
1337     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1338         << DiagSelect.getValue() << TheCall->getSourceRange();
1339     return ExprError();
1340   }
1341 
1342   // We either have an incomplete class type, or we have a class template
1343   // whose instantiation has not been forced. Example:
1344   //
1345   //   template <class T> struct Foo { T value; };
1346   //   Foo<int> *p = nullptr;
1347   //   auto *d = __builtin_launder(p);
1348   if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1349                             diag::err_incomplete_type))
1350     return ExprError();
1351 
1352   assert(ParamTy->getPointeeType()->isObjectType() &&
1353          "Unhandled non-object pointer case");
1354 
1355   InitializedEntity Entity =
1356       InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1357   ExprResult Arg =
1358       S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1359   if (Arg.isInvalid())
1360     return ExprError();
1361   TheCall->setArg(0, Arg.get());
1362 
1363   return TheCall;
1364 }
1365 
1366 // Emit an error and return true if the current architecture is not in the list
1367 // of supported architectures.
1368 static bool
1369 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1370                           ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1371   llvm::Triple::ArchType CurArch =
1372       S.getASTContext().getTargetInfo().getTriple().getArch();
1373   if (llvm::is_contained(SupportedArchs, CurArch))
1374     return false;
1375   S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1376       << TheCall->getSourceRange();
1377   return true;
1378 }
1379 
1380 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
1381                                  SourceLocation CallSiteLoc);
1382 
1383 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
1384                                       CallExpr *TheCall) {
1385   switch (TI.getTriple().getArch()) {
1386   default:
1387     // Some builtins don't require additional checking, so just consider these
1388     // acceptable.
1389     return false;
1390   case llvm::Triple::arm:
1391   case llvm::Triple::armeb:
1392   case llvm::Triple::thumb:
1393   case llvm::Triple::thumbeb:
1394     return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
1395   case llvm::Triple::aarch64:
1396   case llvm::Triple::aarch64_32:
1397   case llvm::Triple::aarch64_be:
1398     return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
1399   case llvm::Triple::bpfeb:
1400   case llvm::Triple::bpfel:
1401     return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
1402   case llvm::Triple::hexagon:
1403     return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
1404   case llvm::Triple::mips:
1405   case llvm::Triple::mipsel:
1406   case llvm::Triple::mips64:
1407   case llvm::Triple::mips64el:
1408     return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
1409   case llvm::Triple::systemz:
1410     return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
1411   case llvm::Triple::x86:
1412   case llvm::Triple::x86_64:
1413     return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall);
1414   case llvm::Triple::ppc:
1415   case llvm::Triple::ppc64:
1416   case llvm::Triple::ppc64le:
1417     return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
1418   case llvm::Triple::amdgcn:
1419     return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
1420   }
1421 }
1422 
1423 ExprResult
1424 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1425                                CallExpr *TheCall) {
1426   ExprResult TheCallResult(TheCall);
1427 
1428   // Find out if any arguments are required to be integer constant expressions.
1429   unsigned ICEArguments = 0;
1430   ASTContext::GetBuiltinTypeError Error;
1431   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1432   if (Error != ASTContext::GE_None)
1433     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
1434 
1435   // If any arguments are required to be ICE's, check and diagnose.
1436   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1437     // Skip arguments not required to be ICE's.
1438     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1439 
1440     llvm::APSInt Result;
1441     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1442       return true;
1443     ICEArguments &= ~(1 << ArgNo);
1444   }
1445 
1446   switch (BuiltinID) {
1447   case Builtin::BI__builtin___CFStringMakeConstantString:
1448     assert(TheCall->getNumArgs() == 1 &&
1449            "Wrong # arguments to builtin CFStringMakeConstantString");
1450     if (CheckObjCString(TheCall->getArg(0)))
1451       return ExprError();
1452     break;
1453   case Builtin::BI__builtin_ms_va_start:
1454   case Builtin::BI__builtin_stdarg_start:
1455   case Builtin::BI__builtin_va_start:
1456     if (SemaBuiltinVAStart(BuiltinID, TheCall))
1457       return ExprError();
1458     break;
1459   case Builtin::BI__va_start: {
1460     switch (Context.getTargetInfo().getTriple().getArch()) {
1461     case llvm::Triple::aarch64:
1462     case llvm::Triple::arm:
1463     case llvm::Triple::thumb:
1464       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1465         return ExprError();
1466       break;
1467     default:
1468       if (SemaBuiltinVAStart(BuiltinID, TheCall))
1469         return ExprError();
1470       break;
1471     }
1472     break;
1473   }
1474 
1475   // The acquire, release, and no fence variants are ARM and AArch64 only.
1476   case Builtin::BI_interlockedbittestandset_acq:
1477   case Builtin::BI_interlockedbittestandset_rel:
1478   case Builtin::BI_interlockedbittestandset_nf:
1479   case Builtin::BI_interlockedbittestandreset_acq:
1480   case Builtin::BI_interlockedbittestandreset_rel:
1481   case Builtin::BI_interlockedbittestandreset_nf:
1482     if (CheckBuiltinTargetSupport(
1483             *this, BuiltinID, TheCall,
1484             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1485       return ExprError();
1486     break;
1487 
1488   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1489   case Builtin::BI_bittest64:
1490   case Builtin::BI_bittestandcomplement64:
1491   case Builtin::BI_bittestandreset64:
1492   case Builtin::BI_bittestandset64:
1493   case Builtin::BI_interlockedbittestandreset64:
1494   case Builtin::BI_interlockedbittestandset64:
1495     if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1496                                   {llvm::Triple::x86_64, llvm::Triple::arm,
1497                                    llvm::Triple::thumb, llvm::Triple::aarch64}))
1498       return ExprError();
1499     break;
1500 
1501   case Builtin::BI__builtin_isgreater:
1502   case Builtin::BI__builtin_isgreaterequal:
1503   case Builtin::BI__builtin_isless:
1504   case Builtin::BI__builtin_islessequal:
1505   case Builtin::BI__builtin_islessgreater:
1506   case Builtin::BI__builtin_isunordered:
1507     if (SemaBuiltinUnorderedCompare(TheCall))
1508       return ExprError();
1509     break;
1510   case Builtin::BI__builtin_fpclassify:
1511     if (SemaBuiltinFPClassification(TheCall, 6))
1512       return ExprError();
1513     break;
1514   case Builtin::BI__builtin_isfinite:
1515   case Builtin::BI__builtin_isinf:
1516   case Builtin::BI__builtin_isinf_sign:
1517   case Builtin::BI__builtin_isnan:
1518   case Builtin::BI__builtin_isnormal:
1519   case Builtin::BI__builtin_signbit:
1520   case Builtin::BI__builtin_signbitf:
1521   case Builtin::BI__builtin_signbitl:
1522     if (SemaBuiltinFPClassification(TheCall, 1))
1523       return ExprError();
1524     break;
1525   case Builtin::BI__builtin_shufflevector:
1526     return SemaBuiltinShuffleVector(TheCall);
1527     // TheCall will be freed by the smart pointer here, but that's fine, since
1528     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1529   case Builtin::BI__builtin_prefetch:
1530     if (SemaBuiltinPrefetch(TheCall))
1531       return ExprError();
1532     break;
1533   case Builtin::BI__builtin_alloca_with_align:
1534     if (SemaBuiltinAllocaWithAlign(TheCall))
1535       return ExprError();
1536     LLVM_FALLTHROUGH;
1537   case Builtin::BI__builtin_alloca:
1538     Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1539         << TheCall->getDirectCallee();
1540     break;
1541   case Builtin::BI__assume:
1542   case Builtin::BI__builtin_assume:
1543     if (SemaBuiltinAssume(TheCall))
1544       return ExprError();
1545     break;
1546   case Builtin::BI__builtin_assume_aligned:
1547     if (SemaBuiltinAssumeAligned(TheCall))
1548       return ExprError();
1549     break;
1550   case Builtin::BI__builtin_dynamic_object_size:
1551   case Builtin::BI__builtin_object_size:
1552     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1553       return ExprError();
1554     break;
1555   case Builtin::BI__builtin_longjmp:
1556     if (SemaBuiltinLongjmp(TheCall))
1557       return ExprError();
1558     break;
1559   case Builtin::BI__builtin_setjmp:
1560     if (SemaBuiltinSetjmp(TheCall))
1561       return ExprError();
1562     break;
1563   case Builtin::BI_setjmp:
1564   case Builtin::BI_setjmpex:
1565     if (checkArgCount(*this, TheCall, 1))
1566       return true;
1567     break;
1568   case Builtin::BI__builtin_classify_type:
1569     if (checkArgCount(*this, TheCall, 1)) return true;
1570     TheCall->setType(Context.IntTy);
1571     break;
1572   case Builtin::BI__builtin_constant_p: {
1573     if (checkArgCount(*this, TheCall, 1)) return true;
1574     ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1575     if (Arg.isInvalid()) return true;
1576     TheCall->setArg(0, Arg.get());
1577     TheCall->setType(Context.IntTy);
1578     break;
1579   }
1580   case Builtin::BI__builtin_launder:
1581     return SemaBuiltinLaunder(*this, TheCall);
1582   case Builtin::BI__sync_fetch_and_add:
1583   case Builtin::BI__sync_fetch_and_add_1:
1584   case Builtin::BI__sync_fetch_and_add_2:
1585   case Builtin::BI__sync_fetch_and_add_4:
1586   case Builtin::BI__sync_fetch_and_add_8:
1587   case Builtin::BI__sync_fetch_and_add_16:
1588   case Builtin::BI__sync_fetch_and_sub:
1589   case Builtin::BI__sync_fetch_and_sub_1:
1590   case Builtin::BI__sync_fetch_and_sub_2:
1591   case Builtin::BI__sync_fetch_and_sub_4:
1592   case Builtin::BI__sync_fetch_and_sub_8:
1593   case Builtin::BI__sync_fetch_and_sub_16:
1594   case Builtin::BI__sync_fetch_and_or:
1595   case Builtin::BI__sync_fetch_and_or_1:
1596   case Builtin::BI__sync_fetch_and_or_2:
1597   case Builtin::BI__sync_fetch_and_or_4:
1598   case Builtin::BI__sync_fetch_and_or_8:
1599   case Builtin::BI__sync_fetch_and_or_16:
1600   case Builtin::BI__sync_fetch_and_and:
1601   case Builtin::BI__sync_fetch_and_and_1:
1602   case Builtin::BI__sync_fetch_and_and_2:
1603   case Builtin::BI__sync_fetch_and_and_4:
1604   case Builtin::BI__sync_fetch_and_and_8:
1605   case Builtin::BI__sync_fetch_and_and_16:
1606   case Builtin::BI__sync_fetch_and_xor:
1607   case Builtin::BI__sync_fetch_and_xor_1:
1608   case Builtin::BI__sync_fetch_and_xor_2:
1609   case Builtin::BI__sync_fetch_and_xor_4:
1610   case Builtin::BI__sync_fetch_and_xor_8:
1611   case Builtin::BI__sync_fetch_and_xor_16:
1612   case Builtin::BI__sync_fetch_and_nand:
1613   case Builtin::BI__sync_fetch_and_nand_1:
1614   case Builtin::BI__sync_fetch_and_nand_2:
1615   case Builtin::BI__sync_fetch_and_nand_4:
1616   case Builtin::BI__sync_fetch_and_nand_8:
1617   case Builtin::BI__sync_fetch_and_nand_16:
1618   case Builtin::BI__sync_add_and_fetch:
1619   case Builtin::BI__sync_add_and_fetch_1:
1620   case Builtin::BI__sync_add_and_fetch_2:
1621   case Builtin::BI__sync_add_and_fetch_4:
1622   case Builtin::BI__sync_add_and_fetch_8:
1623   case Builtin::BI__sync_add_and_fetch_16:
1624   case Builtin::BI__sync_sub_and_fetch:
1625   case Builtin::BI__sync_sub_and_fetch_1:
1626   case Builtin::BI__sync_sub_and_fetch_2:
1627   case Builtin::BI__sync_sub_and_fetch_4:
1628   case Builtin::BI__sync_sub_and_fetch_8:
1629   case Builtin::BI__sync_sub_and_fetch_16:
1630   case Builtin::BI__sync_and_and_fetch:
1631   case Builtin::BI__sync_and_and_fetch_1:
1632   case Builtin::BI__sync_and_and_fetch_2:
1633   case Builtin::BI__sync_and_and_fetch_4:
1634   case Builtin::BI__sync_and_and_fetch_8:
1635   case Builtin::BI__sync_and_and_fetch_16:
1636   case Builtin::BI__sync_or_and_fetch:
1637   case Builtin::BI__sync_or_and_fetch_1:
1638   case Builtin::BI__sync_or_and_fetch_2:
1639   case Builtin::BI__sync_or_and_fetch_4:
1640   case Builtin::BI__sync_or_and_fetch_8:
1641   case Builtin::BI__sync_or_and_fetch_16:
1642   case Builtin::BI__sync_xor_and_fetch:
1643   case Builtin::BI__sync_xor_and_fetch_1:
1644   case Builtin::BI__sync_xor_and_fetch_2:
1645   case Builtin::BI__sync_xor_and_fetch_4:
1646   case Builtin::BI__sync_xor_and_fetch_8:
1647   case Builtin::BI__sync_xor_and_fetch_16:
1648   case Builtin::BI__sync_nand_and_fetch:
1649   case Builtin::BI__sync_nand_and_fetch_1:
1650   case Builtin::BI__sync_nand_and_fetch_2:
1651   case Builtin::BI__sync_nand_and_fetch_4:
1652   case Builtin::BI__sync_nand_and_fetch_8:
1653   case Builtin::BI__sync_nand_and_fetch_16:
1654   case Builtin::BI__sync_val_compare_and_swap:
1655   case Builtin::BI__sync_val_compare_and_swap_1:
1656   case Builtin::BI__sync_val_compare_and_swap_2:
1657   case Builtin::BI__sync_val_compare_and_swap_4:
1658   case Builtin::BI__sync_val_compare_and_swap_8:
1659   case Builtin::BI__sync_val_compare_and_swap_16:
1660   case Builtin::BI__sync_bool_compare_and_swap:
1661   case Builtin::BI__sync_bool_compare_and_swap_1:
1662   case Builtin::BI__sync_bool_compare_and_swap_2:
1663   case Builtin::BI__sync_bool_compare_and_swap_4:
1664   case Builtin::BI__sync_bool_compare_and_swap_8:
1665   case Builtin::BI__sync_bool_compare_and_swap_16:
1666   case Builtin::BI__sync_lock_test_and_set:
1667   case Builtin::BI__sync_lock_test_and_set_1:
1668   case Builtin::BI__sync_lock_test_and_set_2:
1669   case Builtin::BI__sync_lock_test_and_set_4:
1670   case Builtin::BI__sync_lock_test_and_set_8:
1671   case Builtin::BI__sync_lock_test_and_set_16:
1672   case Builtin::BI__sync_lock_release:
1673   case Builtin::BI__sync_lock_release_1:
1674   case Builtin::BI__sync_lock_release_2:
1675   case Builtin::BI__sync_lock_release_4:
1676   case Builtin::BI__sync_lock_release_8:
1677   case Builtin::BI__sync_lock_release_16:
1678   case Builtin::BI__sync_swap:
1679   case Builtin::BI__sync_swap_1:
1680   case Builtin::BI__sync_swap_2:
1681   case Builtin::BI__sync_swap_4:
1682   case Builtin::BI__sync_swap_8:
1683   case Builtin::BI__sync_swap_16:
1684     return SemaBuiltinAtomicOverloaded(TheCallResult);
1685   case Builtin::BI__sync_synchronize:
1686     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1687         << TheCall->getCallee()->getSourceRange();
1688     break;
1689   case Builtin::BI__builtin_nontemporal_load:
1690   case Builtin::BI__builtin_nontemporal_store:
1691     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1692   case Builtin::BI__builtin_memcpy_inline: {
1693     clang::Expr *SizeOp = TheCall->getArg(2);
1694     // We warn about copying to or from `nullptr` pointers when `size` is
1695     // greater than 0. When `size` is value dependent we cannot evaluate its
1696     // value so we bail out.
1697     if (SizeOp->isValueDependent())
1698       break;
1699     if (!SizeOp->EvaluateKnownConstInt(Context).isNullValue()) {
1700       CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
1701       CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
1702     }
1703     break;
1704   }
1705 #define BUILTIN(ID, TYPE, ATTRS)
1706 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1707   case Builtin::BI##ID: \
1708     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1709 #include "clang/Basic/Builtins.def"
1710   case Builtin::BI__annotation:
1711     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1712       return ExprError();
1713     break;
1714   case Builtin::BI__builtin_annotation:
1715     if (SemaBuiltinAnnotation(*this, TheCall))
1716       return ExprError();
1717     break;
1718   case Builtin::BI__builtin_addressof:
1719     if (SemaBuiltinAddressof(*this, TheCall))
1720       return ExprError();
1721     break;
1722   case Builtin::BI__builtin_is_aligned:
1723   case Builtin::BI__builtin_align_up:
1724   case Builtin::BI__builtin_align_down:
1725     if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
1726       return ExprError();
1727     break;
1728   case Builtin::BI__builtin_add_overflow:
1729   case Builtin::BI__builtin_sub_overflow:
1730   case Builtin::BI__builtin_mul_overflow:
1731     if (SemaBuiltinOverflow(*this, TheCall))
1732       return ExprError();
1733     break;
1734   case Builtin::BI__builtin_operator_new:
1735   case Builtin::BI__builtin_operator_delete: {
1736     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1737     ExprResult Res =
1738         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1739     if (Res.isInvalid())
1740       CorrectDelayedTyposInExpr(TheCallResult.get());
1741     return Res;
1742   }
1743   case Builtin::BI__builtin_dump_struct: {
1744     // We first want to ensure we are called with 2 arguments
1745     if (checkArgCount(*this, TheCall, 2))
1746       return ExprError();
1747     // Ensure that the first argument is of type 'struct XX *'
1748     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1749     const QualType PtrArgType = PtrArg->getType();
1750     if (!PtrArgType->isPointerType() ||
1751         !PtrArgType->getPointeeType()->isRecordType()) {
1752       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1753           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1754           << "structure pointer";
1755       return ExprError();
1756     }
1757 
1758     // Ensure that the second argument is of type 'FunctionType'
1759     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1760     const QualType FnPtrArgType = FnPtrArg->getType();
1761     if (!FnPtrArgType->isPointerType()) {
1762       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1763           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1764           << FnPtrArgType << "'int (*)(const char *, ...)'";
1765       return ExprError();
1766     }
1767 
1768     const auto *FuncType =
1769         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1770 
1771     if (!FuncType) {
1772       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1773           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1774           << FnPtrArgType << "'int (*)(const char *, ...)'";
1775       return ExprError();
1776     }
1777 
1778     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1779       if (!FT->getNumParams()) {
1780         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1781             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1782             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1783         return ExprError();
1784       }
1785       QualType PT = FT->getParamType(0);
1786       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1787           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1788           !PT->getPointeeType().isConstQualified()) {
1789         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1790             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1791             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1792         return ExprError();
1793       }
1794     }
1795 
1796     TheCall->setType(Context.IntTy);
1797     break;
1798   }
1799   case Builtin::BI__builtin_preserve_access_index:
1800     if (SemaBuiltinPreserveAI(*this, TheCall))
1801       return ExprError();
1802     break;
1803   case Builtin::BI__builtin_call_with_static_chain:
1804     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1805       return ExprError();
1806     break;
1807   case Builtin::BI__exception_code:
1808   case Builtin::BI_exception_code:
1809     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1810                                  diag::err_seh___except_block))
1811       return ExprError();
1812     break;
1813   case Builtin::BI__exception_info:
1814   case Builtin::BI_exception_info:
1815     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1816                                  diag::err_seh___except_filter))
1817       return ExprError();
1818     break;
1819   case Builtin::BI__GetExceptionInfo:
1820     if (checkArgCount(*this, TheCall, 1))
1821       return ExprError();
1822 
1823     if (CheckCXXThrowOperand(
1824             TheCall->getBeginLoc(),
1825             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1826             TheCall))
1827       return ExprError();
1828 
1829     TheCall->setType(Context.VoidPtrTy);
1830     break;
1831   // OpenCL v2.0, s6.13.16 - Pipe functions
1832   case Builtin::BIread_pipe:
1833   case Builtin::BIwrite_pipe:
1834     // Since those two functions are declared with var args, we need a semantic
1835     // check for the argument.
1836     if (SemaBuiltinRWPipe(*this, TheCall))
1837       return ExprError();
1838     break;
1839   case Builtin::BIreserve_read_pipe:
1840   case Builtin::BIreserve_write_pipe:
1841   case Builtin::BIwork_group_reserve_read_pipe:
1842   case Builtin::BIwork_group_reserve_write_pipe:
1843     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1844       return ExprError();
1845     break;
1846   case Builtin::BIsub_group_reserve_read_pipe:
1847   case Builtin::BIsub_group_reserve_write_pipe:
1848     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1849         SemaBuiltinReserveRWPipe(*this, TheCall))
1850       return ExprError();
1851     break;
1852   case Builtin::BIcommit_read_pipe:
1853   case Builtin::BIcommit_write_pipe:
1854   case Builtin::BIwork_group_commit_read_pipe:
1855   case Builtin::BIwork_group_commit_write_pipe:
1856     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1857       return ExprError();
1858     break;
1859   case Builtin::BIsub_group_commit_read_pipe:
1860   case Builtin::BIsub_group_commit_write_pipe:
1861     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1862         SemaBuiltinCommitRWPipe(*this, TheCall))
1863       return ExprError();
1864     break;
1865   case Builtin::BIget_pipe_num_packets:
1866   case Builtin::BIget_pipe_max_packets:
1867     if (SemaBuiltinPipePackets(*this, TheCall))
1868       return ExprError();
1869     break;
1870   case Builtin::BIto_global:
1871   case Builtin::BIto_local:
1872   case Builtin::BIto_private:
1873     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1874       return ExprError();
1875     break;
1876   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1877   case Builtin::BIenqueue_kernel:
1878     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1879       return ExprError();
1880     break;
1881   case Builtin::BIget_kernel_work_group_size:
1882   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1883     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1884       return ExprError();
1885     break;
1886   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1887   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1888     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1889       return ExprError();
1890     break;
1891   case Builtin::BI__builtin_os_log_format:
1892     Cleanup.setExprNeedsCleanups(true);
1893     LLVM_FALLTHROUGH;
1894   case Builtin::BI__builtin_os_log_format_buffer_size:
1895     if (SemaBuiltinOSLogFormat(TheCall))
1896       return ExprError();
1897     break;
1898   case Builtin::BI__builtin_frame_address:
1899   case Builtin::BI__builtin_return_address:
1900     if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
1901       return ExprError();
1902 
1903     // -Wframe-address warning if non-zero passed to builtin
1904     // return/frame address.
1905     Expr::EvalResult Result;
1906     if (TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
1907         Result.Val.getInt() != 0)
1908       Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
1909           << ((BuiltinID == Builtin::BI__builtin_return_address)
1910                   ? "__builtin_return_address"
1911                   : "__builtin_frame_address")
1912           << TheCall->getSourceRange();
1913     break;
1914   }
1915 
1916   // Since the target specific builtins for each arch overlap, only check those
1917   // of the arch we are compiling for.
1918   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1919     if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
1920       assert(Context.getAuxTargetInfo() &&
1921              "Aux Target Builtin, but not an aux target?");
1922 
1923       if (CheckTSBuiltinFunctionCall(
1924               *Context.getAuxTargetInfo(),
1925               Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
1926         return ExprError();
1927     } else {
1928       if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
1929                                      TheCall))
1930         return ExprError();
1931     }
1932   }
1933 
1934   return TheCallResult;
1935 }
1936 
1937 // Get the valid immediate range for the specified NEON type code.
1938 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1939   NeonTypeFlags Type(t);
1940   int IsQuad = ForceQuad ? true : Type.isQuad();
1941   switch (Type.getEltType()) {
1942   case NeonTypeFlags::Int8:
1943   case NeonTypeFlags::Poly8:
1944     return shift ? 7 : (8 << IsQuad) - 1;
1945   case NeonTypeFlags::Int16:
1946   case NeonTypeFlags::Poly16:
1947     return shift ? 15 : (4 << IsQuad) - 1;
1948   case NeonTypeFlags::Int32:
1949     return shift ? 31 : (2 << IsQuad) - 1;
1950   case NeonTypeFlags::Int64:
1951   case NeonTypeFlags::Poly64:
1952     return shift ? 63 : (1 << IsQuad) - 1;
1953   case NeonTypeFlags::Poly128:
1954     return shift ? 127 : (1 << IsQuad) - 1;
1955   case NeonTypeFlags::Float16:
1956     assert(!shift && "cannot shift float types!");
1957     return (4 << IsQuad) - 1;
1958   case NeonTypeFlags::Float32:
1959     assert(!shift && "cannot shift float types!");
1960     return (2 << IsQuad) - 1;
1961   case NeonTypeFlags::Float64:
1962     assert(!shift && "cannot shift float types!");
1963     return (1 << IsQuad) - 1;
1964   case NeonTypeFlags::BFloat16:
1965     assert(!shift && "cannot shift float types!");
1966     return (4 << IsQuad) - 1;
1967   }
1968   llvm_unreachable("Invalid NeonTypeFlag!");
1969 }
1970 
1971 /// getNeonEltType - Return the QualType corresponding to the elements of
1972 /// the vector type specified by the NeonTypeFlags.  This is used to check
1973 /// the pointer arguments for Neon load/store intrinsics.
1974 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
1975                                bool IsPolyUnsigned, bool IsInt64Long) {
1976   switch (Flags.getEltType()) {
1977   case NeonTypeFlags::Int8:
1978     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1979   case NeonTypeFlags::Int16:
1980     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1981   case NeonTypeFlags::Int32:
1982     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1983   case NeonTypeFlags::Int64:
1984     if (IsInt64Long)
1985       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1986     else
1987       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1988                                 : Context.LongLongTy;
1989   case NeonTypeFlags::Poly8:
1990     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
1991   case NeonTypeFlags::Poly16:
1992     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
1993   case NeonTypeFlags::Poly64:
1994     if (IsInt64Long)
1995       return Context.UnsignedLongTy;
1996     else
1997       return Context.UnsignedLongLongTy;
1998   case NeonTypeFlags::Poly128:
1999     break;
2000   case NeonTypeFlags::Float16:
2001     return Context.HalfTy;
2002   case NeonTypeFlags::Float32:
2003     return Context.FloatTy;
2004   case NeonTypeFlags::Float64:
2005     return Context.DoubleTy;
2006   case NeonTypeFlags::BFloat16:
2007     return Context.BFloat16Ty;
2008   }
2009   llvm_unreachable("Invalid NeonTypeFlag!");
2010 }
2011 
2012 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2013   // Range check SVE intrinsics that take immediate values.
2014   SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
2015 
2016   switch (BuiltinID) {
2017   default:
2018     return false;
2019 #define GET_SVE_IMMEDIATE_CHECK
2020 #include "clang/Basic/arm_sve_sema_rangechecks.inc"
2021 #undef GET_SVE_IMMEDIATE_CHECK
2022   }
2023 
2024   // Perform all the immediate checks for this builtin call.
2025   bool HasError = false;
2026   for (auto &I : ImmChecks) {
2027     int ArgNum, CheckTy, ElementSizeInBits;
2028     std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
2029 
2030     typedef bool(*OptionSetCheckFnTy)(int64_t Value);
2031 
2032     // Function that checks whether the operand (ArgNum) is an immediate
2033     // that is one of the predefined values.
2034     auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
2035                                    int ErrDiag) -> bool {
2036       // We can't check the value of a dependent argument.
2037       Expr *Arg = TheCall->getArg(ArgNum);
2038       if (Arg->isTypeDependent() || Arg->isValueDependent())
2039         return false;
2040 
2041       // Check constant-ness first.
2042       llvm::APSInt Imm;
2043       if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
2044         return true;
2045 
2046       if (!CheckImm(Imm.getSExtValue()))
2047         return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
2048       return false;
2049     };
2050 
2051     switch ((SVETypeFlags::ImmCheckType)CheckTy) {
2052     case SVETypeFlags::ImmCheck0_31:
2053       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
2054         HasError = true;
2055       break;
2056     case SVETypeFlags::ImmCheck0_13:
2057       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
2058         HasError = true;
2059       break;
2060     case SVETypeFlags::ImmCheck1_16:
2061       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
2062         HasError = true;
2063       break;
2064     case SVETypeFlags::ImmCheck0_7:
2065       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
2066         HasError = true;
2067       break;
2068     case SVETypeFlags::ImmCheckExtract:
2069       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2070                                       (2048 / ElementSizeInBits) - 1))
2071         HasError = true;
2072       break;
2073     case SVETypeFlags::ImmCheckShiftRight:
2074       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
2075         HasError = true;
2076       break;
2077     case SVETypeFlags::ImmCheckShiftRightNarrow:
2078       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
2079                                       ElementSizeInBits / 2))
2080         HasError = true;
2081       break;
2082     case SVETypeFlags::ImmCheckShiftLeft:
2083       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2084                                       ElementSizeInBits - 1))
2085         HasError = true;
2086       break;
2087     case SVETypeFlags::ImmCheckLaneIndex:
2088       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2089                                       (128 / (1 * ElementSizeInBits)) - 1))
2090         HasError = true;
2091       break;
2092     case SVETypeFlags::ImmCheckLaneIndexCompRotate:
2093       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2094                                       (128 / (2 * ElementSizeInBits)) - 1))
2095         HasError = true;
2096       break;
2097     case SVETypeFlags::ImmCheckLaneIndexDot:
2098       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2099                                       (128 / (4 * ElementSizeInBits)) - 1))
2100         HasError = true;
2101       break;
2102     case SVETypeFlags::ImmCheckComplexRot90_270:
2103       if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
2104                               diag::err_rotation_argument_to_cadd))
2105         HasError = true;
2106       break;
2107     case SVETypeFlags::ImmCheckComplexRotAll90:
2108       if (CheckImmediateInSet(
2109               [](int64_t V) {
2110                 return V == 0 || V == 90 || V == 180 || V == 270;
2111               },
2112               diag::err_rotation_argument_to_cmla))
2113         HasError = true;
2114       break;
2115     }
2116   }
2117 
2118   return HasError;
2119 }
2120 
2121 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
2122                                         unsigned BuiltinID, CallExpr *TheCall) {
2123   llvm::APSInt Result;
2124   uint64_t mask = 0;
2125   unsigned TV = 0;
2126   int PtrArgNum = -1;
2127   bool HasConstPtr = false;
2128   switch (BuiltinID) {
2129 #define GET_NEON_OVERLOAD_CHECK
2130 #include "clang/Basic/arm_neon.inc"
2131 #include "clang/Basic/arm_fp16.inc"
2132 #undef GET_NEON_OVERLOAD_CHECK
2133   }
2134 
2135   // For NEON intrinsics which are overloaded on vector element type, validate
2136   // the immediate which specifies which variant to emit.
2137   unsigned ImmArg = TheCall->getNumArgs()-1;
2138   if (mask) {
2139     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
2140       return true;
2141 
2142     TV = Result.getLimitedValue(64);
2143     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
2144       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
2145              << TheCall->getArg(ImmArg)->getSourceRange();
2146   }
2147 
2148   if (PtrArgNum >= 0) {
2149     // Check that pointer arguments have the specified type.
2150     Expr *Arg = TheCall->getArg(PtrArgNum);
2151     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
2152       Arg = ICE->getSubExpr();
2153     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
2154     QualType RHSTy = RHS.get()->getType();
2155 
2156     llvm::Triple::ArchType Arch = TI.getTriple().getArch();
2157     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2158                           Arch == llvm::Triple::aarch64_32 ||
2159                           Arch == llvm::Triple::aarch64_be;
2160     bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
2161     QualType EltTy =
2162         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2163     if (HasConstPtr)
2164       EltTy = EltTy.withConst();
2165     QualType LHSTy = Context.getPointerType(EltTy);
2166     AssignConvertType ConvTy;
2167     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2168     if (RHS.isInvalid())
2169       return true;
2170     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2171                                  RHS.get(), AA_Assigning))
2172       return true;
2173   }
2174 
2175   // For NEON intrinsics which take an immediate value as part of the
2176   // instruction, range check them here.
2177   unsigned i = 0, l = 0, u = 0;
2178   switch (BuiltinID) {
2179   default:
2180     return false;
2181   #define GET_NEON_IMMEDIATE_CHECK
2182   #include "clang/Basic/arm_neon.inc"
2183   #include "clang/Basic/arm_fp16.inc"
2184   #undef GET_NEON_IMMEDIATE_CHECK
2185   }
2186 
2187   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2188 }
2189 
2190 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2191   switch (BuiltinID) {
2192   default:
2193     return false;
2194   #include "clang/Basic/arm_mve_builtin_sema.inc"
2195   }
2196 }
2197 
2198 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2199                                        CallExpr *TheCall) {
2200   bool Err = false;
2201   switch (BuiltinID) {
2202   default:
2203     return false;
2204 #include "clang/Basic/arm_cde_builtin_sema.inc"
2205   }
2206 
2207   if (Err)
2208     return true;
2209 
2210   return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
2211 }
2212 
2213 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
2214                                         const Expr *CoprocArg, bool WantCDE) {
2215   if (isConstantEvaluated())
2216     return false;
2217 
2218   // We can't check the value of a dependent argument.
2219   if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
2220     return false;
2221 
2222   llvm::APSInt CoprocNoAP;
2223   bool IsICE = CoprocArg->isIntegerConstantExpr(CoprocNoAP, Context);
2224   (void)IsICE;
2225   assert(IsICE && "Coprocossor immediate is not a constant expression");
2226   int64_t CoprocNo = CoprocNoAP.getExtValue();
2227   assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
2228 
2229   uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
2230   bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
2231 
2232   if (IsCDECoproc != WantCDE)
2233     return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
2234            << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
2235 
2236   return false;
2237 }
2238 
2239 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2240                                         unsigned MaxWidth) {
2241   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
2242           BuiltinID == ARM::BI__builtin_arm_ldaex ||
2243           BuiltinID == ARM::BI__builtin_arm_strex ||
2244           BuiltinID == ARM::BI__builtin_arm_stlex ||
2245           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2246           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2247           BuiltinID == AArch64::BI__builtin_arm_strex ||
2248           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
2249          "unexpected ARM builtin");
2250   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2251                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
2252                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2253                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
2254 
2255   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2256 
2257   // Ensure that we have the proper number of arguments.
2258   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
2259     return true;
2260 
2261   // Inspect the pointer argument of the atomic builtin.  This should always be
2262   // a pointer type, whose element is an integral scalar or pointer type.
2263   // Because it is a pointer type, we don't have to worry about any implicit
2264   // casts here.
2265   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
2266   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
2267   if (PointerArgRes.isInvalid())
2268     return true;
2269   PointerArg = PointerArgRes.get();
2270 
2271   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2272   if (!pointerType) {
2273     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
2274         << PointerArg->getType() << PointerArg->getSourceRange();
2275     return true;
2276   }
2277 
2278   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
2279   // task is to insert the appropriate casts into the AST. First work out just
2280   // what the appropriate type is.
2281   QualType ValType = pointerType->getPointeeType();
2282   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
2283   if (IsLdrex)
2284     AddrType.addConst();
2285 
2286   // Issue a warning if the cast is dodgy.
2287   CastKind CastNeeded = CK_NoOp;
2288   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
2289     CastNeeded = CK_BitCast;
2290     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
2291         << PointerArg->getType() << Context.getPointerType(AddrType)
2292         << AA_Passing << PointerArg->getSourceRange();
2293   }
2294 
2295   // Finally, do the cast and replace the argument with the corrected version.
2296   AddrType = Context.getPointerType(AddrType);
2297   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
2298   if (PointerArgRes.isInvalid())
2299     return true;
2300   PointerArg = PointerArgRes.get();
2301 
2302   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
2303 
2304   // In general, we allow ints, floats and pointers to be loaded and stored.
2305   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2306       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
2307     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
2308         << PointerArg->getType() << PointerArg->getSourceRange();
2309     return true;
2310   }
2311 
2312   // But ARM doesn't have instructions to deal with 128-bit versions.
2313   if (Context.getTypeSize(ValType) > MaxWidth) {
2314     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
2315     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
2316         << PointerArg->getType() << PointerArg->getSourceRange();
2317     return true;
2318   }
2319 
2320   switch (ValType.getObjCLifetime()) {
2321   case Qualifiers::OCL_None:
2322   case Qualifiers::OCL_ExplicitNone:
2323     // okay
2324     break;
2325 
2326   case Qualifiers::OCL_Weak:
2327   case Qualifiers::OCL_Strong:
2328   case Qualifiers::OCL_Autoreleasing:
2329     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
2330         << ValType << PointerArg->getSourceRange();
2331     return true;
2332   }
2333 
2334   if (IsLdrex) {
2335     TheCall->setType(ValType);
2336     return false;
2337   }
2338 
2339   // Initialize the argument to be stored.
2340   ExprResult ValArg = TheCall->getArg(0);
2341   InitializedEntity Entity = InitializedEntity::InitializeParameter(
2342       Context, ValType, /*consume*/ false);
2343   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2344   if (ValArg.isInvalid())
2345     return true;
2346   TheCall->setArg(0, ValArg.get());
2347 
2348   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
2349   // but the custom checker bypasses all default analysis.
2350   TheCall->setType(Context.IntTy);
2351   return false;
2352 }
2353 
2354 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2355                                        CallExpr *TheCall) {
2356   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
2357       BuiltinID == ARM::BI__builtin_arm_ldaex ||
2358       BuiltinID == ARM::BI__builtin_arm_strex ||
2359       BuiltinID == ARM::BI__builtin_arm_stlex) {
2360     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
2361   }
2362 
2363   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
2364     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2365       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
2366   }
2367 
2368   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2369       BuiltinID == ARM::BI__builtin_arm_wsr64)
2370     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
2371 
2372   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
2373       BuiltinID == ARM::BI__builtin_arm_rsrp ||
2374       BuiltinID == ARM::BI__builtin_arm_wsr ||
2375       BuiltinID == ARM::BI__builtin_arm_wsrp)
2376     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2377 
2378   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2379     return true;
2380   if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
2381     return true;
2382   if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
2383     return true;
2384 
2385   // For intrinsics which take an immediate value as part of the instruction,
2386   // range check them here.
2387   // FIXME: VFP Intrinsics should error if VFP not present.
2388   switch (BuiltinID) {
2389   default: return false;
2390   case ARM::BI__builtin_arm_ssat:
2391     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
2392   case ARM::BI__builtin_arm_usat:
2393     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
2394   case ARM::BI__builtin_arm_ssat16:
2395     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
2396   case ARM::BI__builtin_arm_usat16:
2397     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2398   case ARM::BI__builtin_arm_vcvtr_f:
2399   case ARM::BI__builtin_arm_vcvtr_d:
2400     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2401   case ARM::BI__builtin_arm_dmb:
2402   case ARM::BI__builtin_arm_dsb:
2403   case ARM::BI__builtin_arm_isb:
2404   case ARM::BI__builtin_arm_dbg:
2405     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
2406   case ARM::BI__builtin_arm_cdp:
2407   case ARM::BI__builtin_arm_cdp2:
2408   case ARM::BI__builtin_arm_mcr:
2409   case ARM::BI__builtin_arm_mcr2:
2410   case ARM::BI__builtin_arm_mrc:
2411   case ARM::BI__builtin_arm_mrc2:
2412   case ARM::BI__builtin_arm_mcrr:
2413   case ARM::BI__builtin_arm_mcrr2:
2414   case ARM::BI__builtin_arm_mrrc:
2415   case ARM::BI__builtin_arm_mrrc2:
2416   case ARM::BI__builtin_arm_ldc:
2417   case ARM::BI__builtin_arm_ldcl:
2418   case ARM::BI__builtin_arm_ldc2:
2419   case ARM::BI__builtin_arm_ldc2l:
2420   case ARM::BI__builtin_arm_stc:
2421   case ARM::BI__builtin_arm_stcl:
2422   case ARM::BI__builtin_arm_stc2:
2423   case ARM::BI__builtin_arm_stc2l:
2424     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
2425            CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
2426                                         /*WantCDE*/ false);
2427   }
2428 }
2429 
2430 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
2431                                            unsigned BuiltinID,
2432                                            CallExpr *TheCall) {
2433   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2434       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2435       BuiltinID == AArch64::BI__builtin_arm_strex ||
2436       BuiltinID == AArch64::BI__builtin_arm_stlex) {
2437     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
2438   }
2439 
2440   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
2441     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2442       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
2443       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2444       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2445   }
2446 
2447   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2448       BuiltinID == AArch64::BI__builtin_arm_wsr64)
2449     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2450 
2451   // Memory Tagging Extensions (MTE) Intrinsics
2452   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2453       BuiltinID == AArch64::BI__builtin_arm_addg ||
2454       BuiltinID == AArch64::BI__builtin_arm_gmi ||
2455       BuiltinID == AArch64::BI__builtin_arm_ldg ||
2456       BuiltinID == AArch64::BI__builtin_arm_stg ||
2457       BuiltinID == AArch64::BI__builtin_arm_subp) {
2458     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2459   }
2460 
2461   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2462       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2463       BuiltinID == AArch64::BI__builtin_arm_wsr ||
2464       BuiltinID == AArch64::BI__builtin_arm_wsrp)
2465     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2466 
2467   // Only check the valid encoding range. Any constant in this range would be
2468   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2469   // an exception for incorrect registers. This matches MSVC behavior.
2470   if (BuiltinID == AArch64::BI_ReadStatusReg ||
2471       BuiltinID == AArch64::BI_WriteStatusReg)
2472     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2473 
2474   if (BuiltinID == AArch64::BI__getReg)
2475     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2476 
2477   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2478     return true;
2479 
2480   if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
2481     return true;
2482 
2483   // For intrinsics which take an immediate value as part of the instruction,
2484   // range check them here.
2485   unsigned i = 0, l = 0, u = 0;
2486   switch (BuiltinID) {
2487   default: return false;
2488   case AArch64::BI__builtin_arm_dmb:
2489   case AArch64::BI__builtin_arm_dsb:
2490   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2491   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2492   }
2493 
2494   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2495 }
2496 
2497 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
2498                                        CallExpr *TheCall) {
2499   assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
2500           BuiltinID == BPF::BI__builtin_btf_type_id) &&
2501          "unexpected ARM builtin");
2502 
2503   if (checkArgCount(*this, TheCall, 2))
2504     return true;
2505 
2506   Expr *Arg;
2507   if (BuiltinID == BPF::BI__builtin_btf_type_id) {
2508     // The second argument needs to be a constant int
2509     llvm::APSInt Value;
2510     Arg = TheCall->getArg(1);
2511     if (!Arg->isIntegerConstantExpr(Value, Context)) {
2512       Diag(Arg->getBeginLoc(), diag::err_btf_type_id_not_const)
2513           << 2 << Arg->getSourceRange();
2514       return true;
2515     }
2516 
2517     TheCall->setType(Context.UnsignedIntTy);
2518     return false;
2519   }
2520 
2521   // The first argument needs to be a record field access.
2522   // If it is an array element access, we delay decision
2523   // to BPF backend to check whether the access is a
2524   // field access or not.
2525   Arg = TheCall->getArg(0);
2526   if (Arg->getType()->getAsPlaceholderType() ||
2527       (Arg->IgnoreParens()->getObjectKind() != OK_BitField &&
2528        !dyn_cast<MemberExpr>(Arg->IgnoreParens()) &&
2529        !dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()))) {
2530     Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_field)
2531         << 1 << Arg->getSourceRange();
2532     return true;
2533   }
2534 
2535   // The second argument needs to be a constant int
2536   Arg = TheCall->getArg(1);
2537   llvm::APSInt Value;
2538   if (!Arg->isIntegerConstantExpr(Value, Context)) {
2539     Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_const)
2540         << 2 << Arg->getSourceRange();
2541     return true;
2542   }
2543 
2544   TheCall->setType(Context.UnsignedIntTy);
2545   return false;
2546 }
2547 
2548 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2549   struct ArgInfo {
2550     uint8_t OpNum;
2551     bool IsSigned;
2552     uint8_t BitWidth;
2553     uint8_t Align;
2554   };
2555   struct BuiltinInfo {
2556     unsigned BuiltinID;
2557     ArgInfo Infos[2];
2558   };
2559 
2560   static BuiltinInfo Infos[] = {
2561     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2562     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2563     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2564     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  1 }} },
2565     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2566     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2567     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2568     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2569     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2570     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2571     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2572 
2573     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2574     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2575     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2576     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2577     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2578     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2579     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2580     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2581     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2582     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2583     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2584 
2585     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2586     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2587     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2588     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2589     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2590     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2591     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2592     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2593     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2594     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2595     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2596     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2597     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2598     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2599     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2600     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2601     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2602     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2603     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2604     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2605     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2606     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2607     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2608     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2609     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2610     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2611     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2612     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2613     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2614     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2615     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2616     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
2617     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
2618     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
2619     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
2620     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
2621     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
2622     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
2623     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
2624     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
2625     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
2626     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
2627     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
2628     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
2629     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
2630     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
2631     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
2632     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
2633     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
2634     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
2635     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
2636     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2637                                                       {{ 1, false, 6,  0 }} },
2638     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
2639     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
2640     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
2641     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
2642     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
2643     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
2644     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2645                                                       {{ 1, false, 5,  0 }} },
2646     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
2647     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
2648     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
2649     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
2650     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
2651     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
2652                                                        { 2, false, 5,  0 }} },
2653     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
2654                                                        { 2, false, 6,  0 }} },
2655     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
2656                                                        { 3, false, 5,  0 }} },
2657     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
2658                                                        { 3, false, 6,  0 }} },
2659     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
2660     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
2661     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
2662     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
2663     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
2664     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
2665     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
2666     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
2667     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
2668     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
2669     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
2670     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
2671     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
2672     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
2673     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
2674     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2675                                                       {{ 2, false, 4,  0 },
2676                                                        { 3, false, 5,  0 }} },
2677     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2678                                                       {{ 2, false, 4,  0 },
2679                                                        { 3, false, 5,  0 }} },
2680     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2681                                                       {{ 2, false, 4,  0 },
2682                                                        { 3, false, 5,  0 }} },
2683     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2684                                                       {{ 2, false, 4,  0 },
2685                                                        { 3, false, 5,  0 }} },
2686     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
2687     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
2688     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
2689     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
2690     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
2691     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
2692     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
2693     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
2694     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
2695     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
2696     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
2697                                                        { 2, false, 5,  0 }} },
2698     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
2699                                                        { 2, false, 6,  0 }} },
2700     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
2701     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
2702     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
2703     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
2704     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
2705     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
2706     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
2707     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
2708     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2709                                                       {{ 1, false, 4,  0 }} },
2710     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
2711     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2712                                                       {{ 1, false, 4,  0 }} },
2713     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
2714     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
2715     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
2716     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
2717     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
2718     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
2719     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
2720     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
2721     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
2722     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
2723     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
2724     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
2725     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
2726     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
2727     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
2728     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
2729     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
2730     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
2731     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
2732     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2733                                                       {{ 3, false, 1,  0 }} },
2734     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
2735     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
2736     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
2737     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2738                                                       {{ 3, false, 1,  0 }} },
2739     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
2740     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
2741     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
2742     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2743                                                       {{ 3, false, 1,  0 }} },
2744   };
2745 
2746   // Use a dynamically initialized static to sort the table exactly once on
2747   // first run.
2748   static const bool SortOnce =
2749       (llvm::sort(Infos,
2750                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
2751                    return LHS.BuiltinID < RHS.BuiltinID;
2752                  }),
2753        true);
2754   (void)SortOnce;
2755 
2756   const BuiltinInfo *F = llvm::partition_point(
2757       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
2758   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
2759     return false;
2760 
2761   bool Error = false;
2762 
2763   for (const ArgInfo &A : F->Infos) {
2764     // Ignore empty ArgInfo elements.
2765     if (A.BitWidth == 0)
2766       continue;
2767 
2768     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
2769     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
2770     if (!A.Align) {
2771       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2772     } else {
2773       unsigned M = 1 << A.Align;
2774       Min *= M;
2775       Max *= M;
2776       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
2777                SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
2778     }
2779   }
2780   return Error;
2781 }
2782 
2783 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
2784                                            CallExpr *TheCall) {
2785   return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
2786 }
2787 
2788 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
2789                                         unsigned BuiltinID, CallExpr *TheCall) {
2790   return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
2791          CheckMipsBuiltinArgument(BuiltinID, TheCall);
2792 }
2793 
2794 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
2795                                CallExpr *TheCall) {
2796 
2797   if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
2798       BuiltinID <= Mips::BI__builtin_mips_lwx) {
2799     if (!TI.hasFeature("dsp"))
2800       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
2801   }
2802 
2803   if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
2804       BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
2805     if (!TI.hasFeature("dspr2"))
2806       return Diag(TheCall->getBeginLoc(),
2807                   diag::err_mips_builtin_requires_dspr2);
2808   }
2809 
2810   if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
2811       BuiltinID <= Mips::BI__builtin_msa_xori_b) {
2812     if (!TI.hasFeature("msa"))
2813       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
2814   }
2815 
2816   return false;
2817 }
2818 
2819 // CheckMipsBuiltinArgument - Checks the constant value passed to the
2820 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
2821 // ordering for DSP is unspecified. MSA is ordered by the data format used
2822 // by the underlying instruction i.e., df/m, df/n and then by size.
2823 //
2824 // FIXME: The size tests here should instead be tablegen'd along with the
2825 //        definitions from include/clang/Basic/BuiltinsMips.def.
2826 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
2827 //        be too.
2828 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2829   unsigned i = 0, l = 0, u = 0, m = 0;
2830   switch (BuiltinID) {
2831   default: return false;
2832   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
2833   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
2834   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
2835   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
2836   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
2837   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
2838   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
2839   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
2840   // df/m field.
2841   // These intrinsics take an unsigned 3 bit immediate.
2842   case Mips::BI__builtin_msa_bclri_b:
2843   case Mips::BI__builtin_msa_bnegi_b:
2844   case Mips::BI__builtin_msa_bseti_b:
2845   case Mips::BI__builtin_msa_sat_s_b:
2846   case Mips::BI__builtin_msa_sat_u_b:
2847   case Mips::BI__builtin_msa_slli_b:
2848   case Mips::BI__builtin_msa_srai_b:
2849   case Mips::BI__builtin_msa_srari_b:
2850   case Mips::BI__builtin_msa_srli_b:
2851   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
2852   case Mips::BI__builtin_msa_binsli_b:
2853   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
2854   // These intrinsics take an unsigned 4 bit immediate.
2855   case Mips::BI__builtin_msa_bclri_h:
2856   case Mips::BI__builtin_msa_bnegi_h:
2857   case Mips::BI__builtin_msa_bseti_h:
2858   case Mips::BI__builtin_msa_sat_s_h:
2859   case Mips::BI__builtin_msa_sat_u_h:
2860   case Mips::BI__builtin_msa_slli_h:
2861   case Mips::BI__builtin_msa_srai_h:
2862   case Mips::BI__builtin_msa_srari_h:
2863   case Mips::BI__builtin_msa_srli_h:
2864   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
2865   case Mips::BI__builtin_msa_binsli_h:
2866   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
2867   // These intrinsics take an unsigned 5 bit immediate.
2868   // The first block of intrinsics actually have an unsigned 5 bit field,
2869   // not a df/n field.
2870   case Mips::BI__builtin_msa_cfcmsa:
2871   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
2872   case Mips::BI__builtin_msa_clei_u_b:
2873   case Mips::BI__builtin_msa_clei_u_h:
2874   case Mips::BI__builtin_msa_clei_u_w:
2875   case Mips::BI__builtin_msa_clei_u_d:
2876   case Mips::BI__builtin_msa_clti_u_b:
2877   case Mips::BI__builtin_msa_clti_u_h:
2878   case Mips::BI__builtin_msa_clti_u_w:
2879   case Mips::BI__builtin_msa_clti_u_d:
2880   case Mips::BI__builtin_msa_maxi_u_b:
2881   case Mips::BI__builtin_msa_maxi_u_h:
2882   case Mips::BI__builtin_msa_maxi_u_w:
2883   case Mips::BI__builtin_msa_maxi_u_d:
2884   case Mips::BI__builtin_msa_mini_u_b:
2885   case Mips::BI__builtin_msa_mini_u_h:
2886   case Mips::BI__builtin_msa_mini_u_w:
2887   case Mips::BI__builtin_msa_mini_u_d:
2888   case Mips::BI__builtin_msa_addvi_b:
2889   case Mips::BI__builtin_msa_addvi_h:
2890   case Mips::BI__builtin_msa_addvi_w:
2891   case Mips::BI__builtin_msa_addvi_d:
2892   case Mips::BI__builtin_msa_bclri_w:
2893   case Mips::BI__builtin_msa_bnegi_w:
2894   case Mips::BI__builtin_msa_bseti_w:
2895   case Mips::BI__builtin_msa_sat_s_w:
2896   case Mips::BI__builtin_msa_sat_u_w:
2897   case Mips::BI__builtin_msa_slli_w:
2898   case Mips::BI__builtin_msa_srai_w:
2899   case Mips::BI__builtin_msa_srari_w:
2900   case Mips::BI__builtin_msa_srli_w:
2901   case Mips::BI__builtin_msa_srlri_w:
2902   case Mips::BI__builtin_msa_subvi_b:
2903   case Mips::BI__builtin_msa_subvi_h:
2904   case Mips::BI__builtin_msa_subvi_w:
2905   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
2906   case Mips::BI__builtin_msa_binsli_w:
2907   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
2908   // These intrinsics take an unsigned 6 bit immediate.
2909   case Mips::BI__builtin_msa_bclri_d:
2910   case Mips::BI__builtin_msa_bnegi_d:
2911   case Mips::BI__builtin_msa_bseti_d:
2912   case Mips::BI__builtin_msa_sat_s_d:
2913   case Mips::BI__builtin_msa_sat_u_d:
2914   case Mips::BI__builtin_msa_slli_d:
2915   case Mips::BI__builtin_msa_srai_d:
2916   case Mips::BI__builtin_msa_srari_d:
2917   case Mips::BI__builtin_msa_srli_d:
2918   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
2919   case Mips::BI__builtin_msa_binsli_d:
2920   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
2921   // These intrinsics take a signed 5 bit immediate.
2922   case Mips::BI__builtin_msa_ceqi_b:
2923   case Mips::BI__builtin_msa_ceqi_h:
2924   case Mips::BI__builtin_msa_ceqi_w:
2925   case Mips::BI__builtin_msa_ceqi_d:
2926   case Mips::BI__builtin_msa_clti_s_b:
2927   case Mips::BI__builtin_msa_clti_s_h:
2928   case Mips::BI__builtin_msa_clti_s_w:
2929   case Mips::BI__builtin_msa_clti_s_d:
2930   case Mips::BI__builtin_msa_clei_s_b:
2931   case Mips::BI__builtin_msa_clei_s_h:
2932   case Mips::BI__builtin_msa_clei_s_w:
2933   case Mips::BI__builtin_msa_clei_s_d:
2934   case Mips::BI__builtin_msa_maxi_s_b:
2935   case Mips::BI__builtin_msa_maxi_s_h:
2936   case Mips::BI__builtin_msa_maxi_s_w:
2937   case Mips::BI__builtin_msa_maxi_s_d:
2938   case Mips::BI__builtin_msa_mini_s_b:
2939   case Mips::BI__builtin_msa_mini_s_h:
2940   case Mips::BI__builtin_msa_mini_s_w:
2941   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
2942   // These intrinsics take an unsigned 8 bit immediate.
2943   case Mips::BI__builtin_msa_andi_b:
2944   case Mips::BI__builtin_msa_nori_b:
2945   case Mips::BI__builtin_msa_ori_b:
2946   case Mips::BI__builtin_msa_shf_b:
2947   case Mips::BI__builtin_msa_shf_h:
2948   case Mips::BI__builtin_msa_shf_w:
2949   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
2950   case Mips::BI__builtin_msa_bseli_b:
2951   case Mips::BI__builtin_msa_bmnzi_b:
2952   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
2953   // df/n format
2954   // These intrinsics take an unsigned 4 bit immediate.
2955   case Mips::BI__builtin_msa_copy_s_b:
2956   case Mips::BI__builtin_msa_copy_u_b:
2957   case Mips::BI__builtin_msa_insve_b:
2958   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
2959   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
2960   // These intrinsics take an unsigned 3 bit immediate.
2961   case Mips::BI__builtin_msa_copy_s_h:
2962   case Mips::BI__builtin_msa_copy_u_h:
2963   case Mips::BI__builtin_msa_insve_h:
2964   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
2965   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
2966   // These intrinsics take an unsigned 2 bit immediate.
2967   case Mips::BI__builtin_msa_copy_s_w:
2968   case Mips::BI__builtin_msa_copy_u_w:
2969   case Mips::BI__builtin_msa_insve_w:
2970   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
2971   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
2972   // These intrinsics take an unsigned 1 bit immediate.
2973   case Mips::BI__builtin_msa_copy_s_d:
2974   case Mips::BI__builtin_msa_copy_u_d:
2975   case Mips::BI__builtin_msa_insve_d:
2976   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
2977   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
2978   // Memory offsets and immediate loads.
2979   // These intrinsics take a signed 10 bit immediate.
2980   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
2981   case Mips::BI__builtin_msa_ldi_h:
2982   case Mips::BI__builtin_msa_ldi_w:
2983   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
2984   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
2985   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
2986   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
2987   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
2988   case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
2989   case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
2990   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
2991   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
2992   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
2993   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
2994   case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
2995   case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
2996   }
2997 
2998   if (!m)
2999     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3000 
3001   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3002          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3003 }
3004 
3005 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3006                                        CallExpr *TheCall) {
3007   unsigned i = 0, l = 0, u = 0;
3008   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
3009                       BuiltinID == PPC::BI__builtin_divdeu ||
3010                       BuiltinID == PPC::BI__builtin_bpermd;
3011   bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
3012   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
3013                        BuiltinID == PPC::BI__builtin_divweu ||
3014                        BuiltinID == PPC::BI__builtin_divde ||
3015                        BuiltinID == PPC::BI__builtin_divdeu;
3016 
3017   if (Is64BitBltin && !IsTarget64Bit)
3018     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3019            << TheCall->getSourceRange();
3020 
3021   if ((IsBltinExtDiv && !TI.hasFeature("extdiv")) ||
3022       (BuiltinID == PPC::BI__builtin_bpermd && !TI.hasFeature("bpermd")))
3023     return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3024            << TheCall->getSourceRange();
3025 
3026   auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
3027     if (!TI.hasFeature("vsx"))
3028       return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3029              << TheCall->getSourceRange();
3030     return false;
3031   };
3032 
3033   switch (BuiltinID) {
3034   default: return false;
3035   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3036   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3037     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3038            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3039   case PPC::BI__builtin_altivec_dss:
3040     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3041   case PPC::BI__builtin_tbegin:
3042   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3043   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3044   case PPC::BI__builtin_tabortwc:
3045   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3046   case PPC::BI__builtin_tabortwci:
3047   case PPC::BI__builtin_tabortdci:
3048     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3049            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3050   case PPC::BI__builtin_altivec_dst:
3051   case PPC::BI__builtin_altivec_dstt:
3052   case PPC::BI__builtin_altivec_dstst:
3053   case PPC::BI__builtin_altivec_dststt:
3054     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3055   case PPC::BI__builtin_vsx_xxpermdi:
3056   case PPC::BI__builtin_vsx_xxsldwi:
3057     return SemaBuiltinVSX(TheCall);
3058   case PPC::BI__builtin_unpack_vector_int128:
3059     return SemaVSXCheck(TheCall) ||
3060            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3061   case PPC::BI__builtin_pack_vector_int128:
3062     return SemaVSXCheck(TheCall);
3063   }
3064   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3065 }
3066 
3067 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
3068                                           CallExpr *TheCall) {
3069   switch (BuiltinID) {
3070   case AMDGPU::BI__builtin_amdgcn_fence: {
3071     ExprResult Arg = TheCall->getArg(0);
3072     auto ArgExpr = Arg.get();
3073     Expr::EvalResult ArgResult;
3074 
3075     if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
3076       return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
3077              << ArgExpr->getType();
3078     int ord = ArgResult.Val.getInt().getZExtValue();
3079 
3080     // Check valididty of memory ordering as per C11 / C++11's memody model.
3081     switch (static_cast<llvm::AtomicOrderingCABI>(ord)) {
3082     case llvm::AtomicOrderingCABI::acquire:
3083     case llvm::AtomicOrderingCABI::release:
3084     case llvm::AtomicOrderingCABI::acq_rel:
3085     case llvm::AtomicOrderingCABI::seq_cst:
3086       break;
3087     default: {
3088       return Diag(ArgExpr->getBeginLoc(),
3089                   diag::warn_atomic_op_has_invalid_memory_order)
3090              << ArgExpr->getSourceRange();
3091     }
3092     }
3093 
3094     Arg = TheCall->getArg(1);
3095     ArgExpr = Arg.get();
3096     Expr::EvalResult ArgResult1;
3097     // Check that sync scope is a constant literal
3098     if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Expr::EvaluateForCodeGen,
3099                                          Context))
3100       return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
3101              << ArgExpr->getType();
3102   } break;
3103   }
3104   return false;
3105 }
3106 
3107 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3108                                            CallExpr *TheCall) {
3109   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3110     Expr *Arg = TheCall->getArg(0);
3111     llvm::APSInt AbortCode(32);
3112     if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
3113         AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
3114       return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3115              << Arg->getSourceRange();
3116   }
3117 
3118   // For intrinsics which take an immediate value as part of the instruction,
3119   // range check them here.
3120   unsigned i = 0, l = 0, u = 0;
3121   switch (BuiltinID) {
3122   default: return false;
3123   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3124   case SystemZ::BI__builtin_s390_verimb:
3125   case SystemZ::BI__builtin_s390_verimh:
3126   case SystemZ::BI__builtin_s390_verimf:
3127   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3128   case SystemZ::BI__builtin_s390_vfaeb:
3129   case SystemZ::BI__builtin_s390_vfaeh:
3130   case SystemZ::BI__builtin_s390_vfaef:
3131   case SystemZ::BI__builtin_s390_vfaebs:
3132   case SystemZ::BI__builtin_s390_vfaehs:
3133   case SystemZ::BI__builtin_s390_vfaefs:
3134   case SystemZ::BI__builtin_s390_vfaezb:
3135   case SystemZ::BI__builtin_s390_vfaezh:
3136   case SystemZ::BI__builtin_s390_vfaezf:
3137   case SystemZ::BI__builtin_s390_vfaezbs:
3138   case SystemZ::BI__builtin_s390_vfaezhs:
3139   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3140   case SystemZ::BI__builtin_s390_vfisb:
3141   case SystemZ::BI__builtin_s390_vfidb:
3142     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3143            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3144   case SystemZ::BI__builtin_s390_vftcisb:
3145   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3146   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3147   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3148   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3149   case SystemZ::BI__builtin_s390_vstrcb:
3150   case SystemZ::BI__builtin_s390_vstrch:
3151   case SystemZ::BI__builtin_s390_vstrcf:
3152   case SystemZ::BI__builtin_s390_vstrczb:
3153   case SystemZ::BI__builtin_s390_vstrczh:
3154   case SystemZ::BI__builtin_s390_vstrczf:
3155   case SystemZ::BI__builtin_s390_vstrcbs:
3156   case SystemZ::BI__builtin_s390_vstrchs:
3157   case SystemZ::BI__builtin_s390_vstrcfs:
3158   case SystemZ::BI__builtin_s390_vstrczbs:
3159   case SystemZ::BI__builtin_s390_vstrczhs:
3160   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3161   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3162   case SystemZ::BI__builtin_s390_vfminsb:
3163   case SystemZ::BI__builtin_s390_vfmaxsb:
3164   case SystemZ::BI__builtin_s390_vfmindb:
3165   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3166   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
3167   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
3168   }
3169   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3170 }
3171 
3172 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3173 /// This checks that the target supports __builtin_cpu_supports and
3174 /// that the string argument is constant and valid.
3175 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
3176                                    CallExpr *TheCall) {
3177   Expr *Arg = TheCall->getArg(0);
3178 
3179   // Check if the argument is a string literal.
3180   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3181     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3182            << Arg->getSourceRange();
3183 
3184   // Check the contents of the string.
3185   StringRef Feature =
3186       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3187   if (!TI.validateCpuSupports(Feature))
3188     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3189            << Arg->getSourceRange();
3190   return false;
3191 }
3192 
3193 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3194 /// This checks that the target supports __builtin_cpu_is and
3195 /// that the string argument is constant and valid.
3196 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
3197   Expr *Arg = TheCall->getArg(0);
3198 
3199   // Check if the argument is a string literal.
3200   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3201     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3202            << Arg->getSourceRange();
3203 
3204   // Check the contents of the string.
3205   StringRef Feature =
3206       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3207   if (!TI.validateCpuIs(Feature))
3208     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3209            << Arg->getSourceRange();
3210   return false;
3211 }
3212 
3213 // Check if the rounding mode is legal.
3214 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3215   // Indicates if this instruction has rounding control or just SAE.
3216   bool HasRC = false;
3217 
3218   unsigned ArgNum = 0;
3219   switch (BuiltinID) {
3220   default:
3221     return false;
3222   case X86::BI__builtin_ia32_vcvttsd2si32:
3223   case X86::BI__builtin_ia32_vcvttsd2si64:
3224   case X86::BI__builtin_ia32_vcvttsd2usi32:
3225   case X86::BI__builtin_ia32_vcvttsd2usi64:
3226   case X86::BI__builtin_ia32_vcvttss2si32:
3227   case X86::BI__builtin_ia32_vcvttss2si64:
3228   case X86::BI__builtin_ia32_vcvttss2usi32:
3229   case X86::BI__builtin_ia32_vcvttss2usi64:
3230     ArgNum = 1;
3231     break;
3232   case X86::BI__builtin_ia32_maxpd512:
3233   case X86::BI__builtin_ia32_maxps512:
3234   case X86::BI__builtin_ia32_minpd512:
3235   case X86::BI__builtin_ia32_minps512:
3236     ArgNum = 2;
3237     break;
3238   case X86::BI__builtin_ia32_cvtps2pd512_mask:
3239   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3240   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3241   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3242   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3243   case X86::BI__builtin_ia32_cvttps2dq512_mask:
3244   case X86::BI__builtin_ia32_cvttps2qq512_mask:
3245   case X86::BI__builtin_ia32_cvttps2udq512_mask:
3246   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3247   case X86::BI__builtin_ia32_exp2pd_mask:
3248   case X86::BI__builtin_ia32_exp2ps_mask:
3249   case X86::BI__builtin_ia32_getexppd512_mask:
3250   case X86::BI__builtin_ia32_getexpps512_mask:
3251   case X86::BI__builtin_ia32_rcp28pd_mask:
3252   case X86::BI__builtin_ia32_rcp28ps_mask:
3253   case X86::BI__builtin_ia32_rsqrt28pd_mask:
3254   case X86::BI__builtin_ia32_rsqrt28ps_mask:
3255   case X86::BI__builtin_ia32_vcomisd:
3256   case X86::BI__builtin_ia32_vcomiss:
3257   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3258     ArgNum = 3;
3259     break;
3260   case X86::BI__builtin_ia32_cmppd512_mask:
3261   case X86::BI__builtin_ia32_cmpps512_mask:
3262   case X86::BI__builtin_ia32_cmpsd_mask:
3263   case X86::BI__builtin_ia32_cmpss_mask:
3264   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3265   case X86::BI__builtin_ia32_getexpsd128_round_mask:
3266   case X86::BI__builtin_ia32_getexpss128_round_mask:
3267   case X86::BI__builtin_ia32_getmantpd512_mask:
3268   case X86::BI__builtin_ia32_getmantps512_mask:
3269   case X86::BI__builtin_ia32_maxsd_round_mask:
3270   case X86::BI__builtin_ia32_maxss_round_mask:
3271   case X86::BI__builtin_ia32_minsd_round_mask:
3272   case X86::BI__builtin_ia32_minss_round_mask:
3273   case X86::BI__builtin_ia32_rcp28sd_round_mask:
3274   case X86::BI__builtin_ia32_rcp28ss_round_mask:
3275   case X86::BI__builtin_ia32_reducepd512_mask:
3276   case X86::BI__builtin_ia32_reduceps512_mask:
3277   case X86::BI__builtin_ia32_rndscalepd_mask:
3278   case X86::BI__builtin_ia32_rndscaleps_mask:
3279   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3280   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3281     ArgNum = 4;
3282     break;
3283   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3284   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3285   case X86::BI__builtin_ia32_fixupimmps512_mask:
3286   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3287   case X86::BI__builtin_ia32_fixupimmsd_mask:
3288   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3289   case X86::BI__builtin_ia32_fixupimmss_mask:
3290   case X86::BI__builtin_ia32_fixupimmss_maskz:
3291   case X86::BI__builtin_ia32_getmantsd_round_mask:
3292   case X86::BI__builtin_ia32_getmantss_round_mask:
3293   case X86::BI__builtin_ia32_rangepd512_mask:
3294   case X86::BI__builtin_ia32_rangeps512_mask:
3295   case X86::BI__builtin_ia32_rangesd128_round_mask:
3296   case X86::BI__builtin_ia32_rangess128_round_mask:
3297   case X86::BI__builtin_ia32_reducesd_mask:
3298   case X86::BI__builtin_ia32_reducess_mask:
3299   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3300   case X86::BI__builtin_ia32_rndscaless_round_mask:
3301     ArgNum = 5;
3302     break;
3303   case X86::BI__builtin_ia32_vcvtsd2si64:
3304   case X86::BI__builtin_ia32_vcvtsd2si32:
3305   case X86::BI__builtin_ia32_vcvtsd2usi32:
3306   case X86::BI__builtin_ia32_vcvtsd2usi64:
3307   case X86::BI__builtin_ia32_vcvtss2si32:
3308   case X86::BI__builtin_ia32_vcvtss2si64:
3309   case X86::BI__builtin_ia32_vcvtss2usi32:
3310   case X86::BI__builtin_ia32_vcvtss2usi64:
3311   case X86::BI__builtin_ia32_sqrtpd512:
3312   case X86::BI__builtin_ia32_sqrtps512:
3313     ArgNum = 1;
3314     HasRC = true;
3315     break;
3316   case X86::BI__builtin_ia32_addpd512:
3317   case X86::BI__builtin_ia32_addps512:
3318   case X86::BI__builtin_ia32_divpd512:
3319   case X86::BI__builtin_ia32_divps512:
3320   case X86::BI__builtin_ia32_mulpd512:
3321   case X86::BI__builtin_ia32_mulps512:
3322   case X86::BI__builtin_ia32_subpd512:
3323   case X86::BI__builtin_ia32_subps512:
3324   case X86::BI__builtin_ia32_cvtsi2sd64:
3325   case X86::BI__builtin_ia32_cvtsi2ss32:
3326   case X86::BI__builtin_ia32_cvtsi2ss64:
3327   case X86::BI__builtin_ia32_cvtusi2sd64:
3328   case X86::BI__builtin_ia32_cvtusi2ss32:
3329   case X86::BI__builtin_ia32_cvtusi2ss64:
3330     ArgNum = 2;
3331     HasRC = true;
3332     break;
3333   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3334   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3335   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
3336   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
3337   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3338   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
3339   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3340   case X86::BI__builtin_ia32_cvtps2dq512_mask:
3341   case X86::BI__builtin_ia32_cvtps2qq512_mask:
3342   case X86::BI__builtin_ia32_cvtps2udq512_mask:
3343   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3344   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3345   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3346   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3347   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3348     ArgNum = 3;
3349     HasRC = true;
3350     break;
3351   case X86::BI__builtin_ia32_addss_round_mask:
3352   case X86::BI__builtin_ia32_addsd_round_mask:
3353   case X86::BI__builtin_ia32_divss_round_mask:
3354   case X86::BI__builtin_ia32_divsd_round_mask:
3355   case X86::BI__builtin_ia32_mulss_round_mask:
3356   case X86::BI__builtin_ia32_mulsd_round_mask:
3357   case X86::BI__builtin_ia32_subss_round_mask:
3358   case X86::BI__builtin_ia32_subsd_round_mask:
3359   case X86::BI__builtin_ia32_scalefpd512_mask:
3360   case X86::BI__builtin_ia32_scalefps512_mask:
3361   case X86::BI__builtin_ia32_scalefsd_round_mask:
3362   case X86::BI__builtin_ia32_scalefss_round_mask:
3363   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3364   case X86::BI__builtin_ia32_sqrtsd_round_mask:
3365   case X86::BI__builtin_ia32_sqrtss_round_mask:
3366   case X86::BI__builtin_ia32_vfmaddsd3_mask:
3367   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3368   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
3369   case X86::BI__builtin_ia32_vfmaddss3_mask:
3370   case X86::BI__builtin_ia32_vfmaddss3_maskz:
3371   case X86::BI__builtin_ia32_vfmaddss3_mask3:
3372   case X86::BI__builtin_ia32_vfmaddpd512_mask:
3373   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
3374   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
3375   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
3376   case X86::BI__builtin_ia32_vfmaddps512_mask:
3377   case X86::BI__builtin_ia32_vfmaddps512_maskz:
3378   case X86::BI__builtin_ia32_vfmaddps512_mask3:
3379   case X86::BI__builtin_ia32_vfmsubps512_mask3:
3380   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
3381   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
3382   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
3383   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
3384   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
3385   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
3386   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
3387   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
3388     ArgNum = 4;
3389     HasRC = true;
3390     break;
3391   }
3392 
3393   llvm::APSInt Result;
3394 
3395   // We can't check the value of a dependent argument.
3396   Expr *Arg = TheCall->getArg(ArgNum);
3397   if (Arg->isTypeDependent() || Arg->isValueDependent())
3398     return false;
3399 
3400   // Check constant-ness first.
3401   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3402     return true;
3403 
3404   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
3405   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
3406   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
3407   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
3408   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
3409       Result == 8/*ROUND_NO_EXC*/ ||
3410       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
3411       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
3412     return false;
3413 
3414   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
3415          << Arg->getSourceRange();
3416 }
3417 
3418 // Check if the gather/scatter scale is legal.
3419 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
3420                                              CallExpr *TheCall) {
3421   unsigned ArgNum = 0;
3422   switch (BuiltinID) {
3423   default:
3424     return false;
3425   case X86::BI__builtin_ia32_gatherpfdpd:
3426   case X86::BI__builtin_ia32_gatherpfdps:
3427   case X86::BI__builtin_ia32_gatherpfqpd:
3428   case X86::BI__builtin_ia32_gatherpfqps:
3429   case X86::BI__builtin_ia32_scatterpfdpd:
3430   case X86::BI__builtin_ia32_scatterpfdps:
3431   case X86::BI__builtin_ia32_scatterpfqpd:
3432   case X86::BI__builtin_ia32_scatterpfqps:
3433     ArgNum = 3;
3434     break;
3435   case X86::BI__builtin_ia32_gatherd_pd:
3436   case X86::BI__builtin_ia32_gatherd_pd256:
3437   case X86::BI__builtin_ia32_gatherq_pd:
3438   case X86::BI__builtin_ia32_gatherq_pd256:
3439   case X86::BI__builtin_ia32_gatherd_ps:
3440   case X86::BI__builtin_ia32_gatherd_ps256:
3441   case X86::BI__builtin_ia32_gatherq_ps:
3442   case X86::BI__builtin_ia32_gatherq_ps256:
3443   case X86::BI__builtin_ia32_gatherd_q:
3444   case X86::BI__builtin_ia32_gatherd_q256:
3445   case X86::BI__builtin_ia32_gatherq_q:
3446   case X86::BI__builtin_ia32_gatherq_q256:
3447   case X86::BI__builtin_ia32_gatherd_d:
3448   case X86::BI__builtin_ia32_gatherd_d256:
3449   case X86::BI__builtin_ia32_gatherq_d:
3450   case X86::BI__builtin_ia32_gatherq_d256:
3451   case X86::BI__builtin_ia32_gather3div2df:
3452   case X86::BI__builtin_ia32_gather3div2di:
3453   case X86::BI__builtin_ia32_gather3div4df:
3454   case X86::BI__builtin_ia32_gather3div4di:
3455   case X86::BI__builtin_ia32_gather3div4sf:
3456   case X86::BI__builtin_ia32_gather3div4si:
3457   case X86::BI__builtin_ia32_gather3div8sf:
3458   case X86::BI__builtin_ia32_gather3div8si:
3459   case X86::BI__builtin_ia32_gather3siv2df:
3460   case X86::BI__builtin_ia32_gather3siv2di:
3461   case X86::BI__builtin_ia32_gather3siv4df:
3462   case X86::BI__builtin_ia32_gather3siv4di:
3463   case X86::BI__builtin_ia32_gather3siv4sf:
3464   case X86::BI__builtin_ia32_gather3siv4si:
3465   case X86::BI__builtin_ia32_gather3siv8sf:
3466   case X86::BI__builtin_ia32_gather3siv8si:
3467   case X86::BI__builtin_ia32_gathersiv8df:
3468   case X86::BI__builtin_ia32_gathersiv16sf:
3469   case X86::BI__builtin_ia32_gatherdiv8df:
3470   case X86::BI__builtin_ia32_gatherdiv16sf:
3471   case X86::BI__builtin_ia32_gathersiv8di:
3472   case X86::BI__builtin_ia32_gathersiv16si:
3473   case X86::BI__builtin_ia32_gatherdiv8di:
3474   case X86::BI__builtin_ia32_gatherdiv16si:
3475   case X86::BI__builtin_ia32_scatterdiv2df:
3476   case X86::BI__builtin_ia32_scatterdiv2di:
3477   case X86::BI__builtin_ia32_scatterdiv4df:
3478   case X86::BI__builtin_ia32_scatterdiv4di:
3479   case X86::BI__builtin_ia32_scatterdiv4sf:
3480   case X86::BI__builtin_ia32_scatterdiv4si:
3481   case X86::BI__builtin_ia32_scatterdiv8sf:
3482   case X86::BI__builtin_ia32_scatterdiv8si:
3483   case X86::BI__builtin_ia32_scattersiv2df:
3484   case X86::BI__builtin_ia32_scattersiv2di:
3485   case X86::BI__builtin_ia32_scattersiv4df:
3486   case X86::BI__builtin_ia32_scattersiv4di:
3487   case X86::BI__builtin_ia32_scattersiv4sf:
3488   case X86::BI__builtin_ia32_scattersiv4si:
3489   case X86::BI__builtin_ia32_scattersiv8sf:
3490   case X86::BI__builtin_ia32_scattersiv8si:
3491   case X86::BI__builtin_ia32_scattersiv8df:
3492   case X86::BI__builtin_ia32_scattersiv16sf:
3493   case X86::BI__builtin_ia32_scatterdiv8df:
3494   case X86::BI__builtin_ia32_scatterdiv16sf:
3495   case X86::BI__builtin_ia32_scattersiv8di:
3496   case X86::BI__builtin_ia32_scattersiv16si:
3497   case X86::BI__builtin_ia32_scatterdiv8di:
3498   case X86::BI__builtin_ia32_scatterdiv16si:
3499     ArgNum = 4;
3500     break;
3501   }
3502 
3503   llvm::APSInt Result;
3504 
3505   // We can't check the value of a dependent argument.
3506   Expr *Arg = TheCall->getArg(ArgNum);
3507   if (Arg->isTypeDependent() || Arg->isValueDependent())
3508     return false;
3509 
3510   // Check constant-ness first.
3511   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3512     return true;
3513 
3514   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
3515     return false;
3516 
3517   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
3518          << Arg->getSourceRange();
3519 }
3520 
3521 static bool isX86_32Builtin(unsigned BuiltinID) {
3522   // These builtins only work on x86-32 targets.
3523   switch (BuiltinID) {
3524   case X86::BI__builtin_ia32_readeflags_u32:
3525   case X86::BI__builtin_ia32_writeeflags_u32:
3526     return true;
3527   }
3528 
3529   return false;
3530 }
3531 
3532 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3533                                        CallExpr *TheCall) {
3534   if (BuiltinID == X86::BI__builtin_cpu_supports)
3535     return SemaBuiltinCpuSupports(*this, TI, TheCall);
3536 
3537   if (BuiltinID == X86::BI__builtin_cpu_is)
3538     return SemaBuiltinCpuIs(*this, TI, TheCall);
3539 
3540   // Check for 32-bit only builtins on a 64-bit target.
3541   const llvm::Triple &TT = TI.getTriple();
3542   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
3543     return Diag(TheCall->getCallee()->getBeginLoc(),
3544                 diag::err_32_bit_builtin_64_bit_tgt);
3545 
3546   // If the intrinsic has rounding or SAE make sure its valid.
3547   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
3548     return true;
3549 
3550   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
3551   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
3552     return true;
3553 
3554   // For intrinsics which take an immediate value as part of the instruction,
3555   // range check them here.
3556   int i = 0, l = 0, u = 0;
3557   switch (BuiltinID) {
3558   default:
3559     return false;
3560   case X86::BI__builtin_ia32_vec_ext_v2si:
3561   case X86::BI__builtin_ia32_vec_ext_v2di:
3562   case X86::BI__builtin_ia32_vextractf128_pd256:
3563   case X86::BI__builtin_ia32_vextractf128_ps256:
3564   case X86::BI__builtin_ia32_vextractf128_si256:
3565   case X86::BI__builtin_ia32_extract128i256:
3566   case X86::BI__builtin_ia32_extractf64x4_mask:
3567   case X86::BI__builtin_ia32_extracti64x4_mask:
3568   case X86::BI__builtin_ia32_extractf32x8_mask:
3569   case X86::BI__builtin_ia32_extracti32x8_mask:
3570   case X86::BI__builtin_ia32_extractf64x2_256_mask:
3571   case X86::BI__builtin_ia32_extracti64x2_256_mask:
3572   case X86::BI__builtin_ia32_extractf32x4_256_mask:
3573   case X86::BI__builtin_ia32_extracti32x4_256_mask:
3574     i = 1; l = 0; u = 1;
3575     break;
3576   case X86::BI__builtin_ia32_vec_set_v2di:
3577   case X86::BI__builtin_ia32_vinsertf128_pd256:
3578   case X86::BI__builtin_ia32_vinsertf128_ps256:
3579   case X86::BI__builtin_ia32_vinsertf128_si256:
3580   case X86::BI__builtin_ia32_insert128i256:
3581   case X86::BI__builtin_ia32_insertf32x8:
3582   case X86::BI__builtin_ia32_inserti32x8:
3583   case X86::BI__builtin_ia32_insertf64x4:
3584   case X86::BI__builtin_ia32_inserti64x4:
3585   case X86::BI__builtin_ia32_insertf64x2_256:
3586   case X86::BI__builtin_ia32_inserti64x2_256:
3587   case X86::BI__builtin_ia32_insertf32x4_256:
3588   case X86::BI__builtin_ia32_inserti32x4_256:
3589     i = 2; l = 0; u = 1;
3590     break;
3591   case X86::BI__builtin_ia32_vpermilpd:
3592   case X86::BI__builtin_ia32_vec_ext_v4hi:
3593   case X86::BI__builtin_ia32_vec_ext_v4si:
3594   case X86::BI__builtin_ia32_vec_ext_v4sf:
3595   case X86::BI__builtin_ia32_vec_ext_v4di:
3596   case X86::BI__builtin_ia32_extractf32x4_mask:
3597   case X86::BI__builtin_ia32_extracti32x4_mask:
3598   case X86::BI__builtin_ia32_extractf64x2_512_mask:
3599   case X86::BI__builtin_ia32_extracti64x2_512_mask:
3600     i = 1; l = 0; u = 3;
3601     break;
3602   case X86::BI_mm_prefetch:
3603   case X86::BI__builtin_ia32_vec_ext_v8hi:
3604   case X86::BI__builtin_ia32_vec_ext_v8si:
3605     i = 1; l = 0; u = 7;
3606     break;
3607   case X86::BI__builtin_ia32_sha1rnds4:
3608   case X86::BI__builtin_ia32_blendpd:
3609   case X86::BI__builtin_ia32_shufpd:
3610   case X86::BI__builtin_ia32_vec_set_v4hi:
3611   case X86::BI__builtin_ia32_vec_set_v4si:
3612   case X86::BI__builtin_ia32_vec_set_v4di:
3613   case X86::BI__builtin_ia32_shuf_f32x4_256:
3614   case X86::BI__builtin_ia32_shuf_f64x2_256:
3615   case X86::BI__builtin_ia32_shuf_i32x4_256:
3616   case X86::BI__builtin_ia32_shuf_i64x2_256:
3617   case X86::BI__builtin_ia32_insertf64x2_512:
3618   case X86::BI__builtin_ia32_inserti64x2_512:
3619   case X86::BI__builtin_ia32_insertf32x4:
3620   case X86::BI__builtin_ia32_inserti32x4:
3621     i = 2; l = 0; u = 3;
3622     break;
3623   case X86::BI__builtin_ia32_vpermil2pd:
3624   case X86::BI__builtin_ia32_vpermil2pd256:
3625   case X86::BI__builtin_ia32_vpermil2ps:
3626   case X86::BI__builtin_ia32_vpermil2ps256:
3627     i = 3; l = 0; u = 3;
3628     break;
3629   case X86::BI__builtin_ia32_cmpb128_mask:
3630   case X86::BI__builtin_ia32_cmpw128_mask:
3631   case X86::BI__builtin_ia32_cmpd128_mask:
3632   case X86::BI__builtin_ia32_cmpq128_mask:
3633   case X86::BI__builtin_ia32_cmpb256_mask:
3634   case X86::BI__builtin_ia32_cmpw256_mask:
3635   case X86::BI__builtin_ia32_cmpd256_mask:
3636   case X86::BI__builtin_ia32_cmpq256_mask:
3637   case X86::BI__builtin_ia32_cmpb512_mask:
3638   case X86::BI__builtin_ia32_cmpw512_mask:
3639   case X86::BI__builtin_ia32_cmpd512_mask:
3640   case X86::BI__builtin_ia32_cmpq512_mask:
3641   case X86::BI__builtin_ia32_ucmpb128_mask:
3642   case X86::BI__builtin_ia32_ucmpw128_mask:
3643   case X86::BI__builtin_ia32_ucmpd128_mask:
3644   case X86::BI__builtin_ia32_ucmpq128_mask:
3645   case X86::BI__builtin_ia32_ucmpb256_mask:
3646   case X86::BI__builtin_ia32_ucmpw256_mask:
3647   case X86::BI__builtin_ia32_ucmpd256_mask:
3648   case X86::BI__builtin_ia32_ucmpq256_mask:
3649   case X86::BI__builtin_ia32_ucmpb512_mask:
3650   case X86::BI__builtin_ia32_ucmpw512_mask:
3651   case X86::BI__builtin_ia32_ucmpd512_mask:
3652   case X86::BI__builtin_ia32_ucmpq512_mask:
3653   case X86::BI__builtin_ia32_vpcomub:
3654   case X86::BI__builtin_ia32_vpcomuw:
3655   case X86::BI__builtin_ia32_vpcomud:
3656   case X86::BI__builtin_ia32_vpcomuq:
3657   case X86::BI__builtin_ia32_vpcomb:
3658   case X86::BI__builtin_ia32_vpcomw:
3659   case X86::BI__builtin_ia32_vpcomd:
3660   case X86::BI__builtin_ia32_vpcomq:
3661   case X86::BI__builtin_ia32_vec_set_v8hi:
3662   case X86::BI__builtin_ia32_vec_set_v8si:
3663     i = 2; l = 0; u = 7;
3664     break;
3665   case X86::BI__builtin_ia32_vpermilpd256:
3666   case X86::BI__builtin_ia32_roundps:
3667   case X86::BI__builtin_ia32_roundpd:
3668   case X86::BI__builtin_ia32_roundps256:
3669   case X86::BI__builtin_ia32_roundpd256:
3670   case X86::BI__builtin_ia32_getmantpd128_mask:
3671   case X86::BI__builtin_ia32_getmantpd256_mask:
3672   case X86::BI__builtin_ia32_getmantps128_mask:
3673   case X86::BI__builtin_ia32_getmantps256_mask:
3674   case X86::BI__builtin_ia32_getmantpd512_mask:
3675   case X86::BI__builtin_ia32_getmantps512_mask:
3676   case X86::BI__builtin_ia32_vec_ext_v16qi:
3677   case X86::BI__builtin_ia32_vec_ext_v16hi:
3678     i = 1; l = 0; u = 15;
3679     break;
3680   case X86::BI__builtin_ia32_pblendd128:
3681   case X86::BI__builtin_ia32_blendps:
3682   case X86::BI__builtin_ia32_blendpd256:
3683   case X86::BI__builtin_ia32_shufpd256:
3684   case X86::BI__builtin_ia32_roundss:
3685   case X86::BI__builtin_ia32_roundsd:
3686   case X86::BI__builtin_ia32_rangepd128_mask:
3687   case X86::BI__builtin_ia32_rangepd256_mask:
3688   case X86::BI__builtin_ia32_rangepd512_mask:
3689   case X86::BI__builtin_ia32_rangeps128_mask:
3690   case X86::BI__builtin_ia32_rangeps256_mask:
3691   case X86::BI__builtin_ia32_rangeps512_mask:
3692   case X86::BI__builtin_ia32_getmantsd_round_mask:
3693   case X86::BI__builtin_ia32_getmantss_round_mask:
3694   case X86::BI__builtin_ia32_vec_set_v16qi:
3695   case X86::BI__builtin_ia32_vec_set_v16hi:
3696     i = 2; l = 0; u = 15;
3697     break;
3698   case X86::BI__builtin_ia32_vec_ext_v32qi:
3699     i = 1; l = 0; u = 31;
3700     break;
3701   case X86::BI__builtin_ia32_cmpps:
3702   case X86::BI__builtin_ia32_cmpss:
3703   case X86::BI__builtin_ia32_cmppd:
3704   case X86::BI__builtin_ia32_cmpsd:
3705   case X86::BI__builtin_ia32_cmpps256:
3706   case X86::BI__builtin_ia32_cmppd256:
3707   case X86::BI__builtin_ia32_cmpps128_mask:
3708   case X86::BI__builtin_ia32_cmppd128_mask:
3709   case X86::BI__builtin_ia32_cmpps256_mask:
3710   case X86::BI__builtin_ia32_cmppd256_mask:
3711   case X86::BI__builtin_ia32_cmpps512_mask:
3712   case X86::BI__builtin_ia32_cmppd512_mask:
3713   case X86::BI__builtin_ia32_cmpsd_mask:
3714   case X86::BI__builtin_ia32_cmpss_mask:
3715   case X86::BI__builtin_ia32_vec_set_v32qi:
3716     i = 2; l = 0; u = 31;
3717     break;
3718   case X86::BI__builtin_ia32_permdf256:
3719   case X86::BI__builtin_ia32_permdi256:
3720   case X86::BI__builtin_ia32_permdf512:
3721   case X86::BI__builtin_ia32_permdi512:
3722   case X86::BI__builtin_ia32_vpermilps:
3723   case X86::BI__builtin_ia32_vpermilps256:
3724   case X86::BI__builtin_ia32_vpermilpd512:
3725   case X86::BI__builtin_ia32_vpermilps512:
3726   case X86::BI__builtin_ia32_pshufd:
3727   case X86::BI__builtin_ia32_pshufd256:
3728   case X86::BI__builtin_ia32_pshufd512:
3729   case X86::BI__builtin_ia32_pshufhw:
3730   case X86::BI__builtin_ia32_pshufhw256:
3731   case X86::BI__builtin_ia32_pshufhw512:
3732   case X86::BI__builtin_ia32_pshuflw:
3733   case X86::BI__builtin_ia32_pshuflw256:
3734   case X86::BI__builtin_ia32_pshuflw512:
3735   case X86::BI__builtin_ia32_vcvtps2ph:
3736   case X86::BI__builtin_ia32_vcvtps2ph_mask:
3737   case X86::BI__builtin_ia32_vcvtps2ph256:
3738   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
3739   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
3740   case X86::BI__builtin_ia32_rndscaleps_128_mask:
3741   case X86::BI__builtin_ia32_rndscalepd_128_mask:
3742   case X86::BI__builtin_ia32_rndscaleps_256_mask:
3743   case X86::BI__builtin_ia32_rndscalepd_256_mask:
3744   case X86::BI__builtin_ia32_rndscaleps_mask:
3745   case X86::BI__builtin_ia32_rndscalepd_mask:
3746   case X86::BI__builtin_ia32_reducepd128_mask:
3747   case X86::BI__builtin_ia32_reducepd256_mask:
3748   case X86::BI__builtin_ia32_reducepd512_mask:
3749   case X86::BI__builtin_ia32_reduceps128_mask:
3750   case X86::BI__builtin_ia32_reduceps256_mask:
3751   case X86::BI__builtin_ia32_reduceps512_mask:
3752   case X86::BI__builtin_ia32_prold512:
3753   case X86::BI__builtin_ia32_prolq512:
3754   case X86::BI__builtin_ia32_prold128:
3755   case X86::BI__builtin_ia32_prold256:
3756   case X86::BI__builtin_ia32_prolq128:
3757   case X86::BI__builtin_ia32_prolq256:
3758   case X86::BI__builtin_ia32_prord512:
3759   case X86::BI__builtin_ia32_prorq512:
3760   case X86::BI__builtin_ia32_prord128:
3761   case X86::BI__builtin_ia32_prord256:
3762   case X86::BI__builtin_ia32_prorq128:
3763   case X86::BI__builtin_ia32_prorq256:
3764   case X86::BI__builtin_ia32_fpclasspd128_mask:
3765   case X86::BI__builtin_ia32_fpclasspd256_mask:
3766   case X86::BI__builtin_ia32_fpclassps128_mask:
3767   case X86::BI__builtin_ia32_fpclassps256_mask:
3768   case X86::BI__builtin_ia32_fpclassps512_mask:
3769   case X86::BI__builtin_ia32_fpclasspd512_mask:
3770   case X86::BI__builtin_ia32_fpclasssd_mask:
3771   case X86::BI__builtin_ia32_fpclassss_mask:
3772   case X86::BI__builtin_ia32_pslldqi128_byteshift:
3773   case X86::BI__builtin_ia32_pslldqi256_byteshift:
3774   case X86::BI__builtin_ia32_pslldqi512_byteshift:
3775   case X86::BI__builtin_ia32_psrldqi128_byteshift:
3776   case X86::BI__builtin_ia32_psrldqi256_byteshift:
3777   case X86::BI__builtin_ia32_psrldqi512_byteshift:
3778   case X86::BI__builtin_ia32_kshiftliqi:
3779   case X86::BI__builtin_ia32_kshiftlihi:
3780   case X86::BI__builtin_ia32_kshiftlisi:
3781   case X86::BI__builtin_ia32_kshiftlidi:
3782   case X86::BI__builtin_ia32_kshiftriqi:
3783   case X86::BI__builtin_ia32_kshiftrihi:
3784   case X86::BI__builtin_ia32_kshiftrisi:
3785   case X86::BI__builtin_ia32_kshiftridi:
3786     i = 1; l = 0; u = 255;
3787     break;
3788   case X86::BI__builtin_ia32_vperm2f128_pd256:
3789   case X86::BI__builtin_ia32_vperm2f128_ps256:
3790   case X86::BI__builtin_ia32_vperm2f128_si256:
3791   case X86::BI__builtin_ia32_permti256:
3792   case X86::BI__builtin_ia32_pblendw128:
3793   case X86::BI__builtin_ia32_pblendw256:
3794   case X86::BI__builtin_ia32_blendps256:
3795   case X86::BI__builtin_ia32_pblendd256:
3796   case X86::BI__builtin_ia32_palignr128:
3797   case X86::BI__builtin_ia32_palignr256:
3798   case X86::BI__builtin_ia32_palignr512:
3799   case X86::BI__builtin_ia32_alignq512:
3800   case X86::BI__builtin_ia32_alignd512:
3801   case X86::BI__builtin_ia32_alignd128:
3802   case X86::BI__builtin_ia32_alignd256:
3803   case X86::BI__builtin_ia32_alignq128:
3804   case X86::BI__builtin_ia32_alignq256:
3805   case X86::BI__builtin_ia32_vcomisd:
3806   case X86::BI__builtin_ia32_vcomiss:
3807   case X86::BI__builtin_ia32_shuf_f32x4:
3808   case X86::BI__builtin_ia32_shuf_f64x2:
3809   case X86::BI__builtin_ia32_shuf_i32x4:
3810   case X86::BI__builtin_ia32_shuf_i64x2:
3811   case X86::BI__builtin_ia32_shufpd512:
3812   case X86::BI__builtin_ia32_shufps:
3813   case X86::BI__builtin_ia32_shufps256:
3814   case X86::BI__builtin_ia32_shufps512:
3815   case X86::BI__builtin_ia32_dbpsadbw128:
3816   case X86::BI__builtin_ia32_dbpsadbw256:
3817   case X86::BI__builtin_ia32_dbpsadbw512:
3818   case X86::BI__builtin_ia32_vpshldd128:
3819   case X86::BI__builtin_ia32_vpshldd256:
3820   case X86::BI__builtin_ia32_vpshldd512:
3821   case X86::BI__builtin_ia32_vpshldq128:
3822   case X86::BI__builtin_ia32_vpshldq256:
3823   case X86::BI__builtin_ia32_vpshldq512:
3824   case X86::BI__builtin_ia32_vpshldw128:
3825   case X86::BI__builtin_ia32_vpshldw256:
3826   case X86::BI__builtin_ia32_vpshldw512:
3827   case X86::BI__builtin_ia32_vpshrdd128:
3828   case X86::BI__builtin_ia32_vpshrdd256:
3829   case X86::BI__builtin_ia32_vpshrdd512:
3830   case X86::BI__builtin_ia32_vpshrdq128:
3831   case X86::BI__builtin_ia32_vpshrdq256:
3832   case X86::BI__builtin_ia32_vpshrdq512:
3833   case X86::BI__builtin_ia32_vpshrdw128:
3834   case X86::BI__builtin_ia32_vpshrdw256:
3835   case X86::BI__builtin_ia32_vpshrdw512:
3836     i = 2; l = 0; u = 255;
3837     break;
3838   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3839   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3840   case X86::BI__builtin_ia32_fixupimmps512_mask:
3841   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3842   case X86::BI__builtin_ia32_fixupimmsd_mask:
3843   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3844   case X86::BI__builtin_ia32_fixupimmss_mask:
3845   case X86::BI__builtin_ia32_fixupimmss_maskz:
3846   case X86::BI__builtin_ia32_fixupimmpd128_mask:
3847   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
3848   case X86::BI__builtin_ia32_fixupimmpd256_mask:
3849   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
3850   case X86::BI__builtin_ia32_fixupimmps128_mask:
3851   case X86::BI__builtin_ia32_fixupimmps128_maskz:
3852   case X86::BI__builtin_ia32_fixupimmps256_mask:
3853   case X86::BI__builtin_ia32_fixupimmps256_maskz:
3854   case X86::BI__builtin_ia32_pternlogd512_mask:
3855   case X86::BI__builtin_ia32_pternlogd512_maskz:
3856   case X86::BI__builtin_ia32_pternlogq512_mask:
3857   case X86::BI__builtin_ia32_pternlogq512_maskz:
3858   case X86::BI__builtin_ia32_pternlogd128_mask:
3859   case X86::BI__builtin_ia32_pternlogd128_maskz:
3860   case X86::BI__builtin_ia32_pternlogd256_mask:
3861   case X86::BI__builtin_ia32_pternlogd256_maskz:
3862   case X86::BI__builtin_ia32_pternlogq128_mask:
3863   case X86::BI__builtin_ia32_pternlogq128_maskz:
3864   case X86::BI__builtin_ia32_pternlogq256_mask:
3865   case X86::BI__builtin_ia32_pternlogq256_maskz:
3866     i = 3; l = 0; u = 255;
3867     break;
3868   case X86::BI__builtin_ia32_gatherpfdpd:
3869   case X86::BI__builtin_ia32_gatherpfdps:
3870   case X86::BI__builtin_ia32_gatherpfqpd:
3871   case X86::BI__builtin_ia32_gatherpfqps:
3872   case X86::BI__builtin_ia32_scatterpfdpd:
3873   case X86::BI__builtin_ia32_scatterpfdps:
3874   case X86::BI__builtin_ia32_scatterpfqpd:
3875   case X86::BI__builtin_ia32_scatterpfqps:
3876     i = 4; l = 2; u = 3;
3877     break;
3878   case X86::BI__builtin_ia32_reducesd_mask:
3879   case X86::BI__builtin_ia32_reducess_mask:
3880   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3881   case X86::BI__builtin_ia32_rndscaless_round_mask:
3882     i = 4; l = 0; u = 255;
3883     break;
3884   }
3885 
3886   // Note that we don't force a hard error on the range check here, allowing
3887   // template-generated or macro-generated dead code to potentially have out-of-
3888   // range values. These need to code generate, but don't need to necessarily
3889   // make any sense. We use a warning that defaults to an error.
3890   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
3891 }
3892 
3893 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
3894 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
3895 /// Returns true when the format fits the function and the FormatStringInfo has
3896 /// been populated.
3897 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
3898                                FormatStringInfo *FSI) {
3899   FSI->HasVAListArg = Format->getFirstArg() == 0;
3900   FSI->FormatIdx = Format->getFormatIdx() - 1;
3901   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
3902 
3903   // The way the format attribute works in GCC, the implicit this argument
3904   // of member functions is counted. However, it doesn't appear in our own
3905   // lists, so decrement format_idx in that case.
3906   if (IsCXXMember) {
3907     if(FSI->FormatIdx == 0)
3908       return false;
3909     --FSI->FormatIdx;
3910     if (FSI->FirstDataArg != 0)
3911       --FSI->FirstDataArg;
3912   }
3913   return true;
3914 }
3915 
3916 /// Checks if a the given expression evaluates to null.
3917 ///
3918 /// Returns true if the value evaluates to null.
3919 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
3920   // If the expression has non-null type, it doesn't evaluate to null.
3921   if (auto nullability
3922         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
3923     if (*nullability == NullabilityKind::NonNull)
3924       return false;
3925   }
3926 
3927   // As a special case, transparent unions initialized with zero are
3928   // considered null for the purposes of the nonnull attribute.
3929   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
3930     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
3931       if (const CompoundLiteralExpr *CLE =
3932           dyn_cast<CompoundLiteralExpr>(Expr))
3933         if (const InitListExpr *ILE =
3934             dyn_cast<InitListExpr>(CLE->getInitializer()))
3935           Expr = ILE->getInit(0);
3936   }
3937 
3938   bool Result;
3939   return (!Expr->isValueDependent() &&
3940           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
3941           !Result);
3942 }
3943 
3944 static void CheckNonNullArgument(Sema &S,
3945                                  const Expr *ArgExpr,
3946                                  SourceLocation CallSiteLoc) {
3947   if (CheckNonNullExpr(S, ArgExpr))
3948     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
3949                           S.PDiag(diag::warn_null_arg)
3950                               << ArgExpr->getSourceRange());
3951 }
3952 
3953 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
3954   FormatStringInfo FSI;
3955   if ((GetFormatStringType(Format) == FST_NSString) &&
3956       getFormatStringInfo(Format, false, &FSI)) {
3957     Idx = FSI.FormatIdx;
3958     return true;
3959   }
3960   return false;
3961 }
3962 
3963 /// Diagnose use of %s directive in an NSString which is being passed
3964 /// as formatting string to formatting method.
3965 static void
3966 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
3967                                         const NamedDecl *FDecl,
3968                                         Expr **Args,
3969                                         unsigned NumArgs) {
3970   unsigned Idx = 0;
3971   bool Format = false;
3972   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
3973   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
3974     Idx = 2;
3975     Format = true;
3976   }
3977   else
3978     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
3979       if (S.GetFormatNSStringIdx(I, Idx)) {
3980         Format = true;
3981         break;
3982       }
3983     }
3984   if (!Format || NumArgs <= Idx)
3985     return;
3986   const Expr *FormatExpr = Args[Idx];
3987   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
3988     FormatExpr = CSCE->getSubExpr();
3989   const StringLiteral *FormatString;
3990   if (const ObjCStringLiteral *OSL =
3991       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
3992     FormatString = OSL->getString();
3993   else
3994     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
3995   if (!FormatString)
3996     return;
3997   if (S.FormatStringHasSArg(FormatString)) {
3998     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
3999       << "%s" << 1 << 1;
4000     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4001       << FDecl->getDeclName();
4002   }
4003 }
4004 
4005 /// Determine whether the given type has a non-null nullability annotation.
4006 static bool isNonNullType(ASTContext &ctx, QualType type) {
4007   if (auto nullability = type->getNullability(ctx))
4008     return *nullability == NullabilityKind::NonNull;
4009 
4010   return false;
4011 }
4012 
4013 static void CheckNonNullArguments(Sema &S,
4014                                   const NamedDecl *FDecl,
4015                                   const FunctionProtoType *Proto,
4016                                   ArrayRef<const Expr *> Args,
4017                                   SourceLocation CallSiteLoc) {
4018   assert((FDecl || Proto) && "Need a function declaration or prototype");
4019 
4020   // Already checked by by constant evaluator.
4021   if (S.isConstantEvaluated())
4022     return;
4023   // Check the attributes attached to the method/function itself.
4024   llvm::SmallBitVector NonNullArgs;
4025   if (FDecl) {
4026     // Handle the nonnull attribute on the function/method declaration itself.
4027     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4028       if (!NonNull->args_size()) {
4029         // Easy case: all pointer arguments are nonnull.
4030         for (const auto *Arg : Args)
4031           if (S.isValidPointerAttrType(Arg->getType()))
4032             CheckNonNullArgument(S, Arg, CallSiteLoc);
4033         return;
4034       }
4035 
4036       for (const ParamIdx &Idx : NonNull->args()) {
4037         unsigned IdxAST = Idx.getASTIndex();
4038         if (IdxAST >= Args.size())
4039           continue;
4040         if (NonNullArgs.empty())
4041           NonNullArgs.resize(Args.size());
4042         NonNullArgs.set(IdxAST);
4043       }
4044     }
4045   }
4046 
4047   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4048     // Handle the nonnull attribute on the parameters of the
4049     // function/method.
4050     ArrayRef<ParmVarDecl*> parms;
4051     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4052       parms = FD->parameters();
4053     else
4054       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4055 
4056     unsigned ParamIndex = 0;
4057     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4058          I != E; ++I, ++ParamIndex) {
4059       const ParmVarDecl *PVD = *I;
4060       if (PVD->hasAttr<NonNullAttr>() ||
4061           isNonNullType(S.Context, PVD->getType())) {
4062         if (NonNullArgs.empty())
4063           NonNullArgs.resize(Args.size());
4064 
4065         NonNullArgs.set(ParamIndex);
4066       }
4067     }
4068   } else {
4069     // If we have a non-function, non-method declaration but no
4070     // function prototype, try to dig out the function prototype.
4071     if (!Proto) {
4072       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4073         QualType type = VD->getType().getNonReferenceType();
4074         if (auto pointerType = type->getAs<PointerType>())
4075           type = pointerType->getPointeeType();
4076         else if (auto blockType = type->getAs<BlockPointerType>())
4077           type = blockType->getPointeeType();
4078         // FIXME: data member pointers?
4079 
4080         // Dig out the function prototype, if there is one.
4081         Proto = type->getAs<FunctionProtoType>();
4082       }
4083     }
4084 
4085     // Fill in non-null argument information from the nullability
4086     // information on the parameter types (if we have them).
4087     if (Proto) {
4088       unsigned Index = 0;
4089       for (auto paramType : Proto->getParamTypes()) {
4090         if (isNonNullType(S.Context, paramType)) {
4091           if (NonNullArgs.empty())
4092             NonNullArgs.resize(Args.size());
4093 
4094           NonNullArgs.set(Index);
4095         }
4096 
4097         ++Index;
4098       }
4099     }
4100   }
4101 
4102   // Check for non-null arguments.
4103   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4104        ArgIndex != ArgIndexEnd; ++ArgIndex) {
4105     if (NonNullArgs[ArgIndex])
4106       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4107   }
4108 }
4109 
4110 /// Handles the checks for format strings, non-POD arguments to vararg
4111 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4112 /// attributes.
4113 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4114                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
4115                      bool IsMemberFunction, SourceLocation Loc,
4116                      SourceRange Range, VariadicCallType CallType) {
4117   // FIXME: We should check as much as we can in the template definition.
4118   if (CurContext->isDependentContext())
4119     return;
4120 
4121   // Printf and scanf checking.
4122   llvm::SmallBitVector CheckedVarArgs;
4123   if (FDecl) {
4124     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4125       // Only create vector if there are format attributes.
4126       CheckedVarArgs.resize(Args.size());
4127 
4128       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4129                            CheckedVarArgs);
4130     }
4131   }
4132 
4133   // Refuse POD arguments that weren't caught by the format string
4134   // checks above.
4135   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4136   if (CallType != VariadicDoesNotApply &&
4137       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4138     unsigned NumParams = Proto ? Proto->getNumParams()
4139                        : FDecl && isa<FunctionDecl>(FDecl)
4140                            ? cast<FunctionDecl>(FDecl)->getNumParams()
4141                        : FDecl && isa<ObjCMethodDecl>(FDecl)
4142                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
4143                        : 0;
4144 
4145     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4146       // Args[ArgIdx] can be null in malformed code.
4147       if (const Expr *Arg = Args[ArgIdx]) {
4148         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4149           checkVariadicArgument(Arg, CallType);
4150       }
4151     }
4152   }
4153 
4154   if (FDecl || Proto) {
4155     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4156 
4157     // Type safety checking.
4158     if (FDecl) {
4159       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4160         CheckArgumentWithTypeTag(I, Args, Loc);
4161     }
4162   }
4163 
4164   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4165     auto *AA = FDecl->getAttr<AllocAlignAttr>();
4166     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4167     if (!Arg->isValueDependent()) {
4168       Expr::EvalResult Align;
4169       if (Arg->EvaluateAsInt(Align, Context)) {
4170         const llvm::APSInt &I = Align.Val.getInt();
4171         if (!I.isPowerOf2())
4172           Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
4173               << Arg->getSourceRange();
4174 
4175         if (I > Sema::MaximumAlignment)
4176           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
4177               << Arg->getSourceRange() << Sema::MaximumAlignment;
4178       }
4179     }
4180   }
4181 
4182   if (FD)
4183     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4184 }
4185 
4186 /// CheckConstructorCall - Check a constructor call for correctness and safety
4187 /// properties not enforced by the C type system.
4188 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
4189                                 ArrayRef<const Expr *> Args,
4190                                 const FunctionProtoType *Proto,
4191                                 SourceLocation Loc) {
4192   VariadicCallType CallType =
4193     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4194   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4195             Loc, SourceRange(), CallType);
4196 }
4197 
4198 /// CheckFunctionCall - Check a direct function call for various correctness
4199 /// and safety properties not strictly enforced by the C type system.
4200 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4201                              const FunctionProtoType *Proto) {
4202   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4203                               isa<CXXMethodDecl>(FDecl);
4204   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4205                           IsMemberOperatorCall;
4206   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4207                                                   TheCall->getCallee());
4208   Expr** Args = TheCall->getArgs();
4209   unsigned NumArgs = TheCall->getNumArgs();
4210 
4211   Expr *ImplicitThis = nullptr;
4212   if (IsMemberOperatorCall) {
4213     // If this is a call to a member operator, hide the first argument
4214     // from checkCall.
4215     // FIXME: Our choice of AST representation here is less than ideal.
4216     ImplicitThis = Args[0];
4217     ++Args;
4218     --NumArgs;
4219   } else if (IsMemberFunction)
4220     ImplicitThis =
4221         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4222 
4223   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
4224             IsMemberFunction, TheCall->getRParenLoc(),
4225             TheCall->getCallee()->getSourceRange(), CallType);
4226 
4227   IdentifierInfo *FnInfo = FDecl->getIdentifier();
4228   // None of the checks below are needed for functions that don't have
4229   // simple names (e.g., C++ conversion functions).
4230   if (!FnInfo)
4231     return false;
4232 
4233   CheckAbsoluteValueFunction(TheCall, FDecl);
4234   CheckMaxUnsignedZero(TheCall, FDecl);
4235 
4236   if (getLangOpts().ObjC)
4237     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
4238 
4239   unsigned CMId = FDecl->getMemoryFunctionKind();
4240   if (CMId == 0)
4241     return false;
4242 
4243   // Handle memory setting and copying functions.
4244   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
4245     CheckStrlcpycatArguments(TheCall, FnInfo);
4246   else if (CMId == Builtin::BIstrncat)
4247     CheckStrncatArguments(TheCall, FnInfo);
4248   else
4249     CheckMemaccessArguments(TheCall, CMId, FnInfo);
4250 
4251   return false;
4252 }
4253 
4254 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
4255                                ArrayRef<const Expr *> Args) {
4256   VariadicCallType CallType =
4257       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
4258 
4259   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
4260             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
4261             CallType);
4262 
4263   return false;
4264 }
4265 
4266 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4267                             const FunctionProtoType *Proto) {
4268   QualType Ty;
4269   if (const auto *V = dyn_cast<VarDecl>(NDecl))
4270     Ty = V->getType().getNonReferenceType();
4271   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4272     Ty = F->getType().getNonReferenceType();
4273   else
4274     return false;
4275 
4276   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4277       !Ty->isFunctionProtoType())
4278     return false;
4279 
4280   VariadicCallType CallType;
4281   if (!Proto || !Proto->isVariadic()) {
4282     CallType = VariadicDoesNotApply;
4283   } else if (Ty->isBlockPointerType()) {
4284     CallType = VariadicBlock;
4285   } else { // Ty->isFunctionPointerType()
4286     CallType = VariadicFunction;
4287   }
4288 
4289   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4290             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4291             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4292             TheCall->getCallee()->getSourceRange(), CallType);
4293 
4294   return false;
4295 }
4296 
4297 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
4298 /// such as function pointers returned from functions.
4299 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4300   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4301                                                   TheCall->getCallee());
4302   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4303             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4304             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4305             TheCall->getCallee()->getSourceRange(), CallType);
4306 
4307   return false;
4308 }
4309 
4310 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4311   if (!llvm::isValidAtomicOrderingCABI(Ordering))
4312     return false;
4313 
4314   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4315   switch (Op) {
4316   case AtomicExpr::AO__c11_atomic_init:
4317   case AtomicExpr::AO__opencl_atomic_init:
4318     llvm_unreachable("There is no ordering argument for an init");
4319 
4320   case AtomicExpr::AO__c11_atomic_load:
4321   case AtomicExpr::AO__opencl_atomic_load:
4322   case AtomicExpr::AO__atomic_load_n:
4323   case AtomicExpr::AO__atomic_load:
4324     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4325            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4326 
4327   case AtomicExpr::AO__c11_atomic_store:
4328   case AtomicExpr::AO__opencl_atomic_store:
4329   case AtomicExpr::AO__atomic_store:
4330   case AtomicExpr::AO__atomic_store_n:
4331     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4332            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4333            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4334 
4335   default:
4336     return true;
4337   }
4338 }
4339 
4340 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
4341                                          AtomicExpr::AtomicOp Op) {
4342   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4343   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4344   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4345   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
4346                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
4347                          Op);
4348 }
4349 
4350 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
4351                                  SourceLocation RParenLoc, MultiExprArg Args,
4352                                  AtomicExpr::AtomicOp Op,
4353                                  AtomicArgumentOrder ArgOrder) {
4354   // All the non-OpenCL operations take one of the following forms.
4355   // The OpenCL operations take the __c11 forms with one extra argument for
4356   // synchronization scope.
4357   enum {
4358     // C    __c11_atomic_init(A *, C)
4359     Init,
4360 
4361     // C    __c11_atomic_load(A *, int)
4362     Load,
4363 
4364     // void __atomic_load(A *, CP, int)
4365     LoadCopy,
4366 
4367     // void __atomic_store(A *, CP, int)
4368     Copy,
4369 
4370     // C    __c11_atomic_add(A *, M, int)
4371     Arithmetic,
4372 
4373     // C    __atomic_exchange_n(A *, CP, int)
4374     Xchg,
4375 
4376     // void __atomic_exchange(A *, C *, CP, int)
4377     GNUXchg,
4378 
4379     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4380     C11CmpXchg,
4381 
4382     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4383     GNUCmpXchg
4384   } Form = Init;
4385 
4386   const unsigned NumForm = GNUCmpXchg + 1;
4387   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
4388   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
4389   // where:
4390   //   C is an appropriate type,
4391   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4392   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4393   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4394   //   the int parameters are for orderings.
4395 
4396   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4397       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4398       "need to update code for modified forms");
4399   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
4400                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
4401                         AtomicExpr::AO__atomic_load,
4402                 "need to update code for modified C11 atomics");
4403   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
4404                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
4405   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
4406                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
4407                IsOpenCL;
4408   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4409              Op == AtomicExpr::AO__atomic_store_n ||
4410              Op == AtomicExpr::AO__atomic_exchange_n ||
4411              Op == AtomicExpr::AO__atomic_compare_exchange_n;
4412   bool IsAddSub = false;
4413 
4414   switch (Op) {
4415   case AtomicExpr::AO__c11_atomic_init:
4416   case AtomicExpr::AO__opencl_atomic_init:
4417     Form = Init;
4418     break;
4419 
4420   case AtomicExpr::AO__c11_atomic_load:
4421   case AtomicExpr::AO__opencl_atomic_load:
4422   case AtomicExpr::AO__atomic_load_n:
4423     Form = Load;
4424     break;
4425 
4426   case AtomicExpr::AO__atomic_load:
4427     Form = LoadCopy;
4428     break;
4429 
4430   case AtomicExpr::AO__c11_atomic_store:
4431   case AtomicExpr::AO__opencl_atomic_store:
4432   case AtomicExpr::AO__atomic_store:
4433   case AtomicExpr::AO__atomic_store_n:
4434     Form = Copy;
4435     break;
4436 
4437   case AtomicExpr::AO__c11_atomic_fetch_add:
4438   case AtomicExpr::AO__c11_atomic_fetch_sub:
4439   case AtomicExpr::AO__opencl_atomic_fetch_add:
4440   case AtomicExpr::AO__opencl_atomic_fetch_sub:
4441   case AtomicExpr::AO__atomic_fetch_add:
4442   case AtomicExpr::AO__atomic_fetch_sub:
4443   case AtomicExpr::AO__atomic_add_fetch:
4444   case AtomicExpr::AO__atomic_sub_fetch:
4445     IsAddSub = true;
4446     LLVM_FALLTHROUGH;
4447   case AtomicExpr::AO__c11_atomic_fetch_and:
4448   case AtomicExpr::AO__c11_atomic_fetch_or:
4449   case AtomicExpr::AO__c11_atomic_fetch_xor:
4450   case AtomicExpr::AO__opencl_atomic_fetch_and:
4451   case AtomicExpr::AO__opencl_atomic_fetch_or:
4452   case AtomicExpr::AO__opencl_atomic_fetch_xor:
4453   case AtomicExpr::AO__atomic_fetch_and:
4454   case AtomicExpr::AO__atomic_fetch_or:
4455   case AtomicExpr::AO__atomic_fetch_xor:
4456   case AtomicExpr::AO__atomic_fetch_nand:
4457   case AtomicExpr::AO__atomic_and_fetch:
4458   case AtomicExpr::AO__atomic_or_fetch:
4459   case AtomicExpr::AO__atomic_xor_fetch:
4460   case AtomicExpr::AO__atomic_nand_fetch:
4461   case AtomicExpr::AO__c11_atomic_fetch_min:
4462   case AtomicExpr::AO__c11_atomic_fetch_max:
4463   case AtomicExpr::AO__opencl_atomic_fetch_min:
4464   case AtomicExpr::AO__opencl_atomic_fetch_max:
4465   case AtomicExpr::AO__atomic_min_fetch:
4466   case AtomicExpr::AO__atomic_max_fetch:
4467   case AtomicExpr::AO__atomic_fetch_min:
4468   case AtomicExpr::AO__atomic_fetch_max:
4469     Form = Arithmetic;
4470     break;
4471 
4472   case AtomicExpr::AO__c11_atomic_exchange:
4473   case AtomicExpr::AO__opencl_atomic_exchange:
4474   case AtomicExpr::AO__atomic_exchange_n:
4475     Form = Xchg;
4476     break;
4477 
4478   case AtomicExpr::AO__atomic_exchange:
4479     Form = GNUXchg;
4480     break;
4481 
4482   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4483   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4484   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4485   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4486     Form = C11CmpXchg;
4487     break;
4488 
4489   case AtomicExpr::AO__atomic_compare_exchange:
4490   case AtomicExpr::AO__atomic_compare_exchange_n:
4491     Form = GNUCmpXchg;
4492     break;
4493   }
4494 
4495   unsigned AdjustedNumArgs = NumArgs[Form];
4496   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
4497     ++AdjustedNumArgs;
4498   // Check we have the right number of arguments.
4499   if (Args.size() < AdjustedNumArgs) {
4500     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
4501         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4502         << ExprRange;
4503     return ExprError();
4504   } else if (Args.size() > AdjustedNumArgs) {
4505     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
4506          diag::err_typecheck_call_too_many_args)
4507         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4508         << ExprRange;
4509     return ExprError();
4510   }
4511 
4512   // Inspect the first argument of the atomic operation.
4513   Expr *Ptr = Args[0];
4514   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
4515   if (ConvertedPtr.isInvalid())
4516     return ExprError();
4517 
4518   Ptr = ConvertedPtr.get();
4519   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4520   if (!pointerType) {
4521     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
4522         << Ptr->getType() << Ptr->getSourceRange();
4523     return ExprError();
4524   }
4525 
4526   // For a __c11 builtin, this should be a pointer to an _Atomic type.
4527   QualType AtomTy = pointerType->getPointeeType(); // 'A'
4528   QualType ValType = AtomTy; // 'C'
4529   if (IsC11) {
4530     if (!AtomTy->isAtomicType()) {
4531       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
4532           << Ptr->getType() << Ptr->getSourceRange();
4533       return ExprError();
4534     }
4535     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
4536         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
4537       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
4538           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4539           << Ptr->getSourceRange();
4540       return ExprError();
4541     }
4542     ValType = AtomTy->castAs<AtomicType>()->getValueType();
4543   } else if (Form != Load && Form != LoadCopy) {
4544     if (ValType.isConstQualified()) {
4545       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
4546           << Ptr->getType() << Ptr->getSourceRange();
4547       return ExprError();
4548     }
4549   }
4550 
4551   // For an arithmetic operation, the implied arithmetic must be well-formed.
4552   if (Form == Arithmetic) {
4553     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
4554     if (IsAddSub && !ValType->isIntegerType()
4555         && !ValType->isPointerType()) {
4556       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4557           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4558       return ExprError();
4559     }
4560     if (!IsAddSub && !ValType->isIntegerType()) {
4561       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
4562           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4563       return ExprError();
4564     }
4565     if (IsC11 && ValType->isPointerType() &&
4566         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
4567                             diag::err_incomplete_type)) {
4568       return ExprError();
4569     }
4570   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
4571     // For __atomic_*_n operations, the value type must be a scalar integral or
4572     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
4573     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4574         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4575     return ExprError();
4576   }
4577 
4578   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4579       !AtomTy->isScalarType()) {
4580     // For GNU atomics, require a trivially-copyable type. This is not part of
4581     // the GNU atomics specification, but we enforce it for sanity.
4582     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
4583         << Ptr->getType() << Ptr->getSourceRange();
4584     return ExprError();
4585   }
4586 
4587   switch (ValType.getObjCLifetime()) {
4588   case Qualifiers::OCL_None:
4589   case Qualifiers::OCL_ExplicitNone:
4590     // okay
4591     break;
4592 
4593   case Qualifiers::OCL_Weak:
4594   case Qualifiers::OCL_Strong:
4595   case Qualifiers::OCL_Autoreleasing:
4596     // FIXME: Can this happen? By this point, ValType should be known
4597     // to be trivially copyable.
4598     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
4599         << ValType << Ptr->getSourceRange();
4600     return ExprError();
4601   }
4602 
4603   // All atomic operations have an overload which takes a pointer to a volatile
4604   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
4605   // into the result or the other operands. Similarly atomic_load takes a
4606   // pointer to a const 'A'.
4607   ValType.removeLocalVolatile();
4608   ValType.removeLocalConst();
4609   QualType ResultType = ValType;
4610   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
4611       Form == Init)
4612     ResultType = Context.VoidTy;
4613   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
4614     ResultType = Context.BoolTy;
4615 
4616   // The type of a parameter passed 'by value'. In the GNU atomics, such
4617   // arguments are actually passed as pointers.
4618   QualType ByValType = ValType; // 'CP'
4619   bool IsPassedByAddress = false;
4620   if (!IsC11 && !IsN) {
4621     ByValType = Ptr->getType();
4622     IsPassedByAddress = true;
4623   }
4624 
4625   SmallVector<Expr *, 5> APIOrderedArgs;
4626   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
4627     APIOrderedArgs.push_back(Args[0]);
4628     switch (Form) {
4629     case Init:
4630     case Load:
4631       APIOrderedArgs.push_back(Args[1]); // Val1/Order
4632       break;
4633     case LoadCopy:
4634     case Copy:
4635     case Arithmetic:
4636     case Xchg:
4637       APIOrderedArgs.push_back(Args[2]); // Val1
4638       APIOrderedArgs.push_back(Args[1]); // Order
4639       break;
4640     case GNUXchg:
4641       APIOrderedArgs.push_back(Args[2]); // Val1
4642       APIOrderedArgs.push_back(Args[3]); // Val2
4643       APIOrderedArgs.push_back(Args[1]); // Order
4644       break;
4645     case C11CmpXchg:
4646       APIOrderedArgs.push_back(Args[2]); // Val1
4647       APIOrderedArgs.push_back(Args[4]); // Val2
4648       APIOrderedArgs.push_back(Args[1]); // Order
4649       APIOrderedArgs.push_back(Args[3]); // OrderFail
4650       break;
4651     case GNUCmpXchg:
4652       APIOrderedArgs.push_back(Args[2]); // Val1
4653       APIOrderedArgs.push_back(Args[4]); // Val2
4654       APIOrderedArgs.push_back(Args[5]); // Weak
4655       APIOrderedArgs.push_back(Args[1]); // Order
4656       APIOrderedArgs.push_back(Args[3]); // OrderFail
4657       break;
4658     }
4659   } else
4660     APIOrderedArgs.append(Args.begin(), Args.end());
4661 
4662   // The first argument's non-CV pointer type is used to deduce the type of
4663   // subsequent arguments, except for:
4664   //  - weak flag (always converted to bool)
4665   //  - memory order (always converted to int)
4666   //  - scope  (always converted to int)
4667   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
4668     QualType Ty;
4669     if (i < NumVals[Form] + 1) {
4670       switch (i) {
4671       case 0:
4672         // The first argument is always a pointer. It has a fixed type.
4673         // It is always dereferenced, a nullptr is undefined.
4674         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4675         // Nothing else to do: we already know all we want about this pointer.
4676         continue;
4677       case 1:
4678         // The second argument is the non-atomic operand. For arithmetic, this
4679         // is always passed by value, and for a compare_exchange it is always
4680         // passed by address. For the rest, GNU uses by-address and C11 uses
4681         // by-value.
4682         assert(Form != Load);
4683         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
4684           Ty = ValType;
4685         else if (Form == Copy || Form == Xchg) {
4686           if (IsPassedByAddress) {
4687             // The value pointer is always dereferenced, a nullptr is undefined.
4688             CheckNonNullArgument(*this, APIOrderedArgs[i],
4689                                  ExprRange.getBegin());
4690           }
4691           Ty = ByValType;
4692         } else if (Form == Arithmetic)
4693           Ty = Context.getPointerDiffType();
4694         else {
4695           Expr *ValArg = APIOrderedArgs[i];
4696           // The value pointer is always dereferenced, a nullptr is undefined.
4697           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
4698           LangAS AS = LangAS::Default;
4699           // Keep address space of non-atomic pointer type.
4700           if (const PointerType *PtrTy =
4701                   ValArg->getType()->getAs<PointerType>()) {
4702             AS = PtrTy->getPointeeType().getAddressSpace();
4703           }
4704           Ty = Context.getPointerType(
4705               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
4706         }
4707         break;
4708       case 2:
4709         // The third argument to compare_exchange / GNU exchange is the desired
4710         // value, either by-value (for the C11 and *_n variant) or as a pointer.
4711         if (IsPassedByAddress)
4712           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4713         Ty = ByValType;
4714         break;
4715       case 3:
4716         // The fourth argument to GNU compare_exchange is a 'weak' flag.
4717         Ty = Context.BoolTy;
4718         break;
4719       }
4720     } else {
4721       // The order(s) and scope are always converted to int.
4722       Ty = Context.IntTy;
4723     }
4724 
4725     InitializedEntity Entity =
4726         InitializedEntity::InitializeParameter(Context, Ty, false);
4727     ExprResult Arg = APIOrderedArgs[i];
4728     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4729     if (Arg.isInvalid())
4730       return true;
4731     APIOrderedArgs[i] = Arg.get();
4732   }
4733 
4734   // Permute the arguments into a 'consistent' order.
4735   SmallVector<Expr*, 5> SubExprs;
4736   SubExprs.push_back(Ptr);
4737   switch (Form) {
4738   case Init:
4739     // Note, AtomicExpr::getVal1() has a special case for this atomic.
4740     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4741     break;
4742   case Load:
4743     SubExprs.push_back(APIOrderedArgs[1]); // Order
4744     break;
4745   case LoadCopy:
4746   case Copy:
4747   case Arithmetic:
4748   case Xchg:
4749     SubExprs.push_back(APIOrderedArgs[2]); // Order
4750     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4751     break;
4752   case GNUXchg:
4753     // Note, AtomicExpr::getVal2() has a special case for this atomic.
4754     SubExprs.push_back(APIOrderedArgs[3]); // Order
4755     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4756     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4757     break;
4758   case C11CmpXchg:
4759     SubExprs.push_back(APIOrderedArgs[3]); // Order
4760     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4761     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
4762     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4763     break;
4764   case GNUCmpXchg:
4765     SubExprs.push_back(APIOrderedArgs[4]); // Order
4766     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4767     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
4768     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4769     SubExprs.push_back(APIOrderedArgs[3]); // Weak
4770     break;
4771   }
4772 
4773   if (SubExprs.size() >= 2 && Form != Init) {
4774     llvm::APSInt Result(32);
4775     if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
4776         !isValidOrderingForOp(Result.getSExtValue(), Op))
4777       Diag(SubExprs[1]->getBeginLoc(),
4778            diag::warn_atomic_op_has_invalid_memory_order)
4779           << SubExprs[1]->getSourceRange();
4780   }
4781 
4782   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
4783     auto *Scope = Args[Args.size() - 1];
4784     llvm::APSInt Result(32);
4785     if (Scope->isIntegerConstantExpr(Result, Context) &&
4786         !ScopeModel->isValid(Result.getZExtValue())) {
4787       Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
4788           << Scope->getSourceRange();
4789     }
4790     SubExprs.push_back(Scope);
4791   }
4792 
4793   AtomicExpr *AE = new (Context)
4794       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
4795 
4796   if ((Op == AtomicExpr::AO__c11_atomic_load ||
4797        Op == AtomicExpr::AO__c11_atomic_store ||
4798        Op == AtomicExpr::AO__opencl_atomic_load ||
4799        Op == AtomicExpr::AO__opencl_atomic_store ) &&
4800       Context.AtomicUsesUnsupportedLibcall(AE))
4801     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
4802         << ((Op == AtomicExpr::AO__c11_atomic_load ||
4803              Op == AtomicExpr::AO__opencl_atomic_load)
4804                 ? 0
4805                 : 1);
4806 
4807   return AE;
4808 }
4809 
4810 /// checkBuiltinArgument - Given a call to a builtin function, perform
4811 /// normal type-checking on the given argument, updating the call in
4812 /// place.  This is useful when a builtin function requires custom
4813 /// type-checking for some of its arguments but not necessarily all of
4814 /// them.
4815 ///
4816 /// Returns true on error.
4817 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
4818   FunctionDecl *Fn = E->getDirectCallee();
4819   assert(Fn && "builtin call without direct callee!");
4820 
4821   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
4822   InitializedEntity Entity =
4823     InitializedEntity::InitializeParameter(S.Context, Param);
4824 
4825   ExprResult Arg = E->getArg(0);
4826   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
4827   if (Arg.isInvalid())
4828     return true;
4829 
4830   E->setArg(ArgIndex, Arg.get());
4831   return false;
4832 }
4833 
4834 /// We have a call to a function like __sync_fetch_and_add, which is an
4835 /// overloaded function based on the pointer type of its first argument.
4836 /// The main BuildCallExpr routines have already promoted the types of
4837 /// arguments because all of these calls are prototyped as void(...).
4838 ///
4839 /// This function goes through and does final semantic checking for these
4840 /// builtins, as well as generating any warnings.
4841 ExprResult
4842 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
4843   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
4844   Expr *Callee = TheCall->getCallee();
4845   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
4846   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4847 
4848   // Ensure that we have at least one argument to do type inference from.
4849   if (TheCall->getNumArgs() < 1) {
4850     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
4851         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
4852     return ExprError();
4853   }
4854 
4855   // Inspect the first argument of the atomic builtin.  This should always be
4856   // a pointer type, whose element is an integral scalar or pointer type.
4857   // Because it is a pointer type, we don't have to worry about any implicit
4858   // casts here.
4859   // FIXME: We don't allow floating point scalars as input.
4860   Expr *FirstArg = TheCall->getArg(0);
4861   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
4862   if (FirstArgResult.isInvalid())
4863     return ExprError();
4864   FirstArg = FirstArgResult.get();
4865   TheCall->setArg(0, FirstArg);
4866 
4867   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
4868   if (!pointerType) {
4869     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
4870         << FirstArg->getType() << FirstArg->getSourceRange();
4871     return ExprError();
4872   }
4873 
4874   QualType ValType = pointerType->getPointeeType();
4875   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
4876       !ValType->isBlockPointerType()) {
4877     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
4878         << FirstArg->getType() << FirstArg->getSourceRange();
4879     return ExprError();
4880   }
4881 
4882   if (ValType.isConstQualified()) {
4883     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
4884         << FirstArg->getType() << FirstArg->getSourceRange();
4885     return ExprError();
4886   }
4887 
4888   switch (ValType.getObjCLifetime()) {
4889   case Qualifiers::OCL_None:
4890   case Qualifiers::OCL_ExplicitNone:
4891     // okay
4892     break;
4893 
4894   case Qualifiers::OCL_Weak:
4895   case Qualifiers::OCL_Strong:
4896   case Qualifiers::OCL_Autoreleasing:
4897     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
4898         << ValType << FirstArg->getSourceRange();
4899     return ExprError();
4900   }
4901 
4902   // Strip any qualifiers off ValType.
4903   ValType = ValType.getUnqualifiedType();
4904 
4905   // The majority of builtins return a value, but a few have special return
4906   // types, so allow them to override appropriately below.
4907   QualType ResultType = ValType;
4908 
4909   // We need to figure out which concrete builtin this maps onto.  For example,
4910   // __sync_fetch_and_add with a 2 byte object turns into
4911   // __sync_fetch_and_add_2.
4912 #define BUILTIN_ROW(x) \
4913   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
4914     Builtin::BI##x##_8, Builtin::BI##x##_16 }
4915 
4916   static const unsigned BuiltinIndices[][5] = {
4917     BUILTIN_ROW(__sync_fetch_and_add),
4918     BUILTIN_ROW(__sync_fetch_and_sub),
4919     BUILTIN_ROW(__sync_fetch_and_or),
4920     BUILTIN_ROW(__sync_fetch_and_and),
4921     BUILTIN_ROW(__sync_fetch_and_xor),
4922     BUILTIN_ROW(__sync_fetch_and_nand),
4923 
4924     BUILTIN_ROW(__sync_add_and_fetch),
4925     BUILTIN_ROW(__sync_sub_and_fetch),
4926     BUILTIN_ROW(__sync_and_and_fetch),
4927     BUILTIN_ROW(__sync_or_and_fetch),
4928     BUILTIN_ROW(__sync_xor_and_fetch),
4929     BUILTIN_ROW(__sync_nand_and_fetch),
4930 
4931     BUILTIN_ROW(__sync_val_compare_and_swap),
4932     BUILTIN_ROW(__sync_bool_compare_and_swap),
4933     BUILTIN_ROW(__sync_lock_test_and_set),
4934     BUILTIN_ROW(__sync_lock_release),
4935     BUILTIN_ROW(__sync_swap)
4936   };
4937 #undef BUILTIN_ROW
4938 
4939   // Determine the index of the size.
4940   unsigned SizeIndex;
4941   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
4942   case 1: SizeIndex = 0; break;
4943   case 2: SizeIndex = 1; break;
4944   case 4: SizeIndex = 2; break;
4945   case 8: SizeIndex = 3; break;
4946   case 16: SizeIndex = 4; break;
4947   default:
4948     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
4949         << FirstArg->getType() << FirstArg->getSourceRange();
4950     return ExprError();
4951   }
4952 
4953   // Each of these builtins has one pointer argument, followed by some number of
4954   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
4955   // that we ignore.  Find out which row of BuiltinIndices to read from as well
4956   // as the number of fixed args.
4957   unsigned BuiltinID = FDecl->getBuiltinID();
4958   unsigned BuiltinIndex, NumFixed = 1;
4959   bool WarnAboutSemanticsChange = false;
4960   switch (BuiltinID) {
4961   default: llvm_unreachable("Unknown overloaded atomic builtin!");
4962   case Builtin::BI__sync_fetch_and_add:
4963   case Builtin::BI__sync_fetch_and_add_1:
4964   case Builtin::BI__sync_fetch_and_add_2:
4965   case Builtin::BI__sync_fetch_and_add_4:
4966   case Builtin::BI__sync_fetch_and_add_8:
4967   case Builtin::BI__sync_fetch_and_add_16:
4968     BuiltinIndex = 0;
4969     break;
4970 
4971   case Builtin::BI__sync_fetch_and_sub:
4972   case Builtin::BI__sync_fetch_and_sub_1:
4973   case Builtin::BI__sync_fetch_and_sub_2:
4974   case Builtin::BI__sync_fetch_and_sub_4:
4975   case Builtin::BI__sync_fetch_and_sub_8:
4976   case Builtin::BI__sync_fetch_and_sub_16:
4977     BuiltinIndex = 1;
4978     break;
4979 
4980   case Builtin::BI__sync_fetch_and_or:
4981   case Builtin::BI__sync_fetch_and_or_1:
4982   case Builtin::BI__sync_fetch_and_or_2:
4983   case Builtin::BI__sync_fetch_and_or_4:
4984   case Builtin::BI__sync_fetch_and_or_8:
4985   case Builtin::BI__sync_fetch_and_or_16:
4986     BuiltinIndex = 2;
4987     break;
4988 
4989   case Builtin::BI__sync_fetch_and_and:
4990   case Builtin::BI__sync_fetch_and_and_1:
4991   case Builtin::BI__sync_fetch_and_and_2:
4992   case Builtin::BI__sync_fetch_and_and_4:
4993   case Builtin::BI__sync_fetch_and_and_8:
4994   case Builtin::BI__sync_fetch_and_and_16:
4995     BuiltinIndex = 3;
4996     break;
4997 
4998   case Builtin::BI__sync_fetch_and_xor:
4999   case Builtin::BI__sync_fetch_and_xor_1:
5000   case Builtin::BI__sync_fetch_and_xor_2:
5001   case Builtin::BI__sync_fetch_and_xor_4:
5002   case Builtin::BI__sync_fetch_and_xor_8:
5003   case Builtin::BI__sync_fetch_and_xor_16:
5004     BuiltinIndex = 4;
5005     break;
5006 
5007   case Builtin::BI__sync_fetch_and_nand:
5008   case Builtin::BI__sync_fetch_and_nand_1:
5009   case Builtin::BI__sync_fetch_and_nand_2:
5010   case Builtin::BI__sync_fetch_and_nand_4:
5011   case Builtin::BI__sync_fetch_and_nand_8:
5012   case Builtin::BI__sync_fetch_and_nand_16:
5013     BuiltinIndex = 5;
5014     WarnAboutSemanticsChange = true;
5015     break;
5016 
5017   case Builtin::BI__sync_add_and_fetch:
5018   case Builtin::BI__sync_add_and_fetch_1:
5019   case Builtin::BI__sync_add_and_fetch_2:
5020   case Builtin::BI__sync_add_and_fetch_4:
5021   case Builtin::BI__sync_add_and_fetch_8:
5022   case Builtin::BI__sync_add_and_fetch_16:
5023     BuiltinIndex = 6;
5024     break;
5025 
5026   case Builtin::BI__sync_sub_and_fetch:
5027   case Builtin::BI__sync_sub_and_fetch_1:
5028   case Builtin::BI__sync_sub_and_fetch_2:
5029   case Builtin::BI__sync_sub_and_fetch_4:
5030   case Builtin::BI__sync_sub_and_fetch_8:
5031   case Builtin::BI__sync_sub_and_fetch_16:
5032     BuiltinIndex = 7;
5033     break;
5034 
5035   case Builtin::BI__sync_and_and_fetch:
5036   case Builtin::BI__sync_and_and_fetch_1:
5037   case Builtin::BI__sync_and_and_fetch_2:
5038   case Builtin::BI__sync_and_and_fetch_4:
5039   case Builtin::BI__sync_and_and_fetch_8:
5040   case Builtin::BI__sync_and_and_fetch_16:
5041     BuiltinIndex = 8;
5042     break;
5043 
5044   case Builtin::BI__sync_or_and_fetch:
5045   case Builtin::BI__sync_or_and_fetch_1:
5046   case Builtin::BI__sync_or_and_fetch_2:
5047   case Builtin::BI__sync_or_and_fetch_4:
5048   case Builtin::BI__sync_or_and_fetch_8:
5049   case Builtin::BI__sync_or_and_fetch_16:
5050     BuiltinIndex = 9;
5051     break;
5052 
5053   case Builtin::BI__sync_xor_and_fetch:
5054   case Builtin::BI__sync_xor_and_fetch_1:
5055   case Builtin::BI__sync_xor_and_fetch_2:
5056   case Builtin::BI__sync_xor_and_fetch_4:
5057   case Builtin::BI__sync_xor_and_fetch_8:
5058   case Builtin::BI__sync_xor_and_fetch_16:
5059     BuiltinIndex = 10;
5060     break;
5061 
5062   case Builtin::BI__sync_nand_and_fetch:
5063   case Builtin::BI__sync_nand_and_fetch_1:
5064   case Builtin::BI__sync_nand_and_fetch_2:
5065   case Builtin::BI__sync_nand_and_fetch_4:
5066   case Builtin::BI__sync_nand_and_fetch_8:
5067   case Builtin::BI__sync_nand_and_fetch_16:
5068     BuiltinIndex = 11;
5069     WarnAboutSemanticsChange = true;
5070     break;
5071 
5072   case Builtin::BI__sync_val_compare_and_swap:
5073   case Builtin::BI__sync_val_compare_and_swap_1:
5074   case Builtin::BI__sync_val_compare_and_swap_2:
5075   case Builtin::BI__sync_val_compare_and_swap_4:
5076   case Builtin::BI__sync_val_compare_and_swap_8:
5077   case Builtin::BI__sync_val_compare_and_swap_16:
5078     BuiltinIndex = 12;
5079     NumFixed = 2;
5080     break;
5081 
5082   case Builtin::BI__sync_bool_compare_and_swap:
5083   case Builtin::BI__sync_bool_compare_and_swap_1:
5084   case Builtin::BI__sync_bool_compare_and_swap_2:
5085   case Builtin::BI__sync_bool_compare_and_swap_4:
5086   case Builtin::BI__sync_bool_compare_and_swap_8:
5087   case Builtin::BI__sync_bool_compare_and_swap_16:
5088     BuiltinIndex = 13;
5089     NumFixed = 2;
5090     ResultType = Context.BoolTy;
5091     break;
5092 
5093   case Builtin::BI__sync_lock_test_and_set:
5094   case Builtin::BI__sync_lock_test_and_set_1:
5095   case Builtin::BI__sync_lock_test_and_set_2:
5096   case Builtin::BI__sync_lock_test_and_set_4:
5097   case Builtin::BI__sync_lock_test_and_set_8:
5098   case Builtin::BI__sync_lock_test_and_set_16:
5099     BuiltinIndex = 14;
5100     break;
5101 
5102   case Builtin::BI__sync_lock_release:
5103   case Builtin::BI__sync_lock_release_1:
5104   case Builtin::BI__sync_lock_release_2:
5105   case Builtin::BI__sync_lock_release_4:
5106   case Builtin::BI__sync_lock_release_8:
5107   case Builtin::BI__sync_lock_release_16:
5108     BuiltinIndex = 15;
5109     NumFixed = 0;
5110     ResultType = Context.VoidTy;
5111     break;
5112 
5113   case Builtin::BI__sync_swap:
5114   case Builtin::BI__sync_swap_1:
5115   case Builtin::BI__sync_swap_2:
5116   case Builtin::BI__sync_swap_4:
5117   case Builtin::BI__sync_swap_8:
5118   case Builtin::BI__sync_swap_16:
5119     BuiltinIndex = 16;
5120     break;
5121   }
5122 
5123   // Now that we know how many fixed arguments we expect, first check that we
5124   // have at least that many.
5125   if (TheCall->getNumArgs() < 1+NumFixed) {
5126     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5127         << 0 << 1 + NumFixed << TheCall->getNumArgs()
5128         << Callee->getSourceRange();
5129     return ExprError();
5130   }
5131 
5132   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5133       << Callee->getSourceRange();
5134 
5135   if (WarnAboutSemanticsChange) {
5136     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5137         << Callee->getSourceRange();
5138   }
5139 
5140   // Get the decl for the concrete builtin from this, we can tell what the
5141   // concrete integer type we should convert to is.
5142   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5143   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5144   FunctionDecl *NewBuiltinDecl;
5145   if (NewBuiltinID == BuiltinID)
5146     NewBuiltinDecl = FDecl;
5147   else {
5148     // Perform builtin lookup to avoid redeclaring it.
5149     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5150     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5151     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5152     assert(Res.getFoundDecl());
5153     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5154     if (!NewBuiltinDecl)
5155       return ExprError();
5156   }
5157 
5158   // The first argument --- the pointer --- has a fixed type; we
5159   // deduce the types of the rest of the arguments accordingly.  Walk
5160   // the remaining arguments, converting them to the deduced value type.
5161   for (unsigned i = 0; i != NumFixed; ++i) {
5162     ExprResult Arg = TheCall->getArg(i+1);
5163 
5164     // GCC does an implicit conversion to the pointer or integer ValType.  This
5165     // can fail in some cases (1i -> int**), check for this error case now.
5166     // Initialize the argument.
5167     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5168                                                    ValType, /*consume*/ false);
5169     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5170     if (Arg.isInvalid())
5171       return ExprError();
5172 
5173     // Okay, we have something that *can* be converted to the right type.  Check
5174     // to see if there is a potentially weird extension going on here.  This can
5175     // happen when you do an atomic operation on something like an char* and
5176     // pass in 42.  The 42 gets converted to char.  This is even more strange
5177     // for things like 45.123 -> char, etc.
5178     // FIXME: Do this check.
5179     TheCall->setArg(i+1, Arg.get());
5180   }
5181 
5182   // Create a new DeclRefExpr to refer to the new decl.
5183   DeclRefExpr *NewDRE = DeclRefExpr::Create(
5184       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5185       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5186       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
5187 
5188   // Set the callee in the CallExpr.
5189   // FIXME: This loses syntactic information.
5190   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5191   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5192                                               CK_BuiltinFnToFnPtr);
5193   TheCall->setCallee(PromotedCall.get());
5194 
5195   // Change the result type of the call to match the original value type. This
5196   // is arbitrary, but the codegen for these builtins ins design to handle it
5197   // gracefully.
5198   TheCall->setType(ResultType);
5199 
5200   return TheCallResult;
5201 }
5202 
5203 /// SemaBuiltinNontemporalOverloaded - We have a call to
5204 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
5205 /// overloaded function based on the pointer type of its last argument.
5206 ///
5207 /// This function goes through and does final semantic checking for these
5208 /// builtins.
5209 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5210   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5211   DeclRefExpr *DRE =
5212       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5213   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5214   unsigned BuiltinID = FDecl->getBuiltinID();
5215   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5216           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5217          "Unexpected nontemporal load/store builtin!");
5218   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5219   unsigned numArgs = isStore ? 2 : 1;
5220 
5221   // Ensure that we have the proper number of arguments.
5222   if (checkArgCount(*this, TheCall, numArgs))
5223     return ExprError();
5224 
5225   // Inspect the last argument of the nontemporal builtin.  This should always
5226   // be a pointer type, from which we imply the type of the memory access.
5227   // Because it is a pointer type, we don't have to worry about any implicit
5228   // casts here.
5229   Expr *PointerArg = TheCall->getArg(numArgs - 1);
5230   ExprResult PointerArgResult =
5231       DefaultFunctionArrayLvalueConversion(PointerArg);
5232 
5233   if (PointerArgResult.isInvalid())
5234     return ExprError();
5235   PointerArg = PointerArgResult.get();
5236   TheCall->setArg(numArgs - 1, PointerArg);
5237 
5238   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5239   if (!pointerType) {
5240     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5241         << PointerArg->getType() << PointerArg->getSourceRange();
5242     return ExprError();
5243   }
5244 
5245   QualType ValType = pointerType->getPointeeType();
5246 
5247   // Strip any qualifiers off ValType.
5248   ValType = ValType.getUnqualifiedType();
5249   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5250       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5251       !ValType->isVectorType()) {
5252     Diag(DRE->getBeginLoc(),
5253          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5254         << PointerArg->getType() << PointerArg->getSourceRange();
5255     return ExprError();
5256   }
5257 
5258   if (!isStore) {
5259     TheCall->setType(ValType);
5260     return TheCallResult;
5261   }
5262 
5263   ExprResult ValArg = TheCall->getArg(0);
5264   InitializedEntity Entity = InitializedEntity::InitializeParameter(
5265       Context, ValType, /*consume*/ false);
5266   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5267   if (ValArg.isInvalid())
5268     return ExprError();
5269 
5270   TheCall->setArg(0, ValArg.get());
5271   TheCall->setType(Context.VoidTy);
5272   return TheCallResult;
5273 }
5274 
5275 /// CheckObjCString - Checks that the argument to the builtin
5276 /// CFString constructor is correct
5277 /// Note: It might also make sense to do the UTF-16 conversion here (would
5278 /// simplify the backend).
5279 bool Sema::CheckObjCString(Expr *Arg) {
5280   Arg = Arg->IgnoreParenCasts();
5281   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
5282 
5283   if (!Literal || !Literal->isAscii()) {
5284     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
5285         << Arg->getSourceRange();
5286     return true;
5287   }
5288 
5289   if (Literal->containsNonAsciiOrNull()) {
5290     StringRef String = Literal->getString();
5291     unsigned NumBytes = String.size();
5292     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
5293     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5294     llvm::UTF16 *ToPtr = &ToBuf[0];
5295 
5296     llvm::ConversionResult Result =
5297         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5298                                  ToPtr + NumBytes, llvm::strictConversion);
5299     // Check for conversion failure.
5300     if (Result != llvm::conversionOK)
5301       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
5302           << Arg->getSourceRange();
5303   }
5304   return false;
5305 }
5306 
5307 /// CheckObjCString - Checks that the format string argument to the os_log()
5308 /// and os_trace() functions is correct, and converts it to const char *.
5309 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5310   Arg = Arg->IgnoreParenCasts();
5311   auto *Literal = dyn_cast<StringLiteral>(Arg);
5312   if (!Literal) {
5313     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5314       Literal = ObjcLiteral->getString();
5315     }
5316   }
5317 
5318   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
5319     return ExprError(
5320         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5321         << Arg->getSourceRange());
5322   }
5323 
5324   ExprResult Result(Literal);
5325   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5326   InitializedEntity Entity =
5327       InitializedEntity::InitializeParameter(Context, ResultTy, false);
5328   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5329   return Result;
5330 }
5331 
5332 /// Check that the user is calling the appropriate va_start builtin for the
5333 /// target and calling convention.
5334 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5335   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5336   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5337   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
5338                     TT.getArch() == llvm::Triple::aarch64_32);
5339   bool IsWindows = TT.isOSWindows();
5340   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5341   if (IsX64 || IsAArch64) {
5342     CallingConv CC = CC_C;
5343     if (const FunctionDecl *FD = S.getCurFunctionDecl())
5344       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
5345     if (IsMSVAStart) {
5346       // Don't allow this in System V ABI functions.
5347       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
5348         return S.Diag(Fn->getBeginLoc(),
5349                       diag::err_ms_va_start_used_in_sysv_function);
5350     } else {
5351       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5352       // On x64 Windows, don't allow this in System V ABI functions.
5353       // (Yes, that means there's no corresponding way to support variadic
5354       // System V ABI functions on Windows.)
5355       if ((IsWindows && CC == CC_X86_64SysV) ||
5356           (!IsWindows && CC == CC_Win64))
5357         return S.Diag(Fn->getBeginLoc(),
5358                       diag::err_va_start_used_in_wrong_abi_function)
5359                << !IsWindows;
5360     }
5361     return false;
5362   }
5363 
5364   if (IsMSVAStart)
5365     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5366   return false;
5367 }
5368 
5369 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
5370                                              ParmVarDecl **LastParam = nullptr) {
5371   // Determine whether the current function, block, or obj-c method is variadic
5372   // and get its parameter list.
5373   bool IsVariadic = false;
5374   ArrayRef<ParmVarDecl *> Params;
5375   DeclContext *Caller = S.CurContext;
5376   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5377     IsVariadic = Block->isVariadic();
5378     Params = Block->parameters();
5379   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5380     IsVariadic = FD->isVariadic();
5381     Params = FD->parameters();
5382   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5383     IsVariadic = MD->isVariadic();
5384     // FIXME: This isn't correct for methods (results in bogus warning).
5385     Params = MD->parameters();
5386   } else if (isa<CapturedDecl>(Caller)) {
5387     // We don't support va_start in a CapturedDecl.
5388     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5389     return true;
5390   } else {
5391     // This must be some other declcontext that parses exprs.
5392     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5393     return true;
5394   }
5395 
5396   if (!IsVariadic) {
5397     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
5398     return true;
5399   }
5400 
5401   if (LastParam)
5402     *LastParam = Params.empty() ? nullptr : Params.back();
5403 
5404   return false;
5405 }
5406 
5407 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
5408 /// for validity.  Emit an error and return true on failure; return false
5409 /// on success.
5410 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5411   Expr *Fn = TheCall->getCallee();
5412 
5413   if (checkVAStartABI(*this, BuiltinID, Fn))
5414     return true;
5415 
5416   if (TheCall->getNumArgs() > 2) {
5417     Diag(TheCall->getArg(2)->getBeginLoc(),
5418          diag::err_typecheck_call_too_many_args)
5419         << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5420         << Fn->getSourceRange()
5421         << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5422                        (*(TheCall->arg_end() - 1))->getEndLoc());
5423     return true;
5424   }
5425 
5426   if (TheCall->getNumArgs() < 2) {
5427     return Diag(TheCall->getEndLoc(),
5428                 diag::err_typecheck_call_too_few_args_at_least)
5429            << 0 /*function call*/ << 2 << TheCall->getNumArgs();
5430   }
5431 
5432   // Type-check the first argument normally.
5433   if (checkBuiltinArgument(*this, TheCall, 0))
5434     return true;
5435 
5436   // Check that the current function is variadic, and get its last parameter.
5437   ParmVarDecl *LastParam;
5438   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5439     return true;
5440 
5441   // Verify that the second argument to the builtin is the last argument of the
5442   // current function or method.
5443   bool SecondArgIsLastNamedArgument = false;
5444   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5445 
5446   // These are valid if SecondArgIsLastNamedArgument is false after the next
5447   // block.
5448   QualType Type;
5449   SourceLocation ParamLoc;
5450   bool IsCRegister = false;
5451 
5452   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5453     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5454       SecondArgIsLastNamedArgument = PV == LastParam;
5455 
5456       Type = PV->getType();
5457       ParamLoc = PV->getLocation();
5458       IsCRegister =
5459           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5460     }
5461   }
5462 
5463   if (!SecondArgIsLastNamedArgument)
5464     Diag(TheCall->getArg(1)->getBeginLoc(),
5465          diag::warn_second_arg_of_va_start_not_last_named_param);
5466   else if (IsCRegister || Type->isReferenceType() ||
5467            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5468              // Promotable integers are UB, but enumerations need a bit of
5469              // extra checking to see what their promotable type actually is.
5470              if (!Type->isPromotableIntegerType())
5471                return false;
5472              if (!Type->isEnumeralType())
5473                return true;
5474              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
5475              return !(ED &&
5476                       Context.typesAreCompatible(ED->getPromotionType(), Type));
5477            }()) {
5478     unsigned Reason = 0;
5479     if (Type->isReferenceType())  Reason = 1;
5480     else if (IsCRegister)         Reason = 2;
5481     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
5482     Diag(ParamLoc, diag::note_parameter_type) << Type;
5483   }
5484 
5485   TheCall->setType(Context.VoidTy);
5486   return false;
5487 }
5488 
5489 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
5490   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5491   //                 const char *named_addr);
5492 
5493   Expr *Func = Call->getCallee();
5494 
5495   if (Call->getNumArgs() < 3)
5496     return Diag(Call->getEndLoc(),
5497                 diag::err_typecheck_call_too_few_args_at_least)
5498            << 0 /*function call*/ << 3 << Call->getNumArgs();
5499 
5500   // Type-check the first argument normally.
5501   if (checkBuiltinArgument(*this, Call, 0))
5502     return true;
5503 
5504   // Check that the current function is variadic.
5505   if (checkVAStartIsInVariadicFunction(*this, Func))
5506     return true;
5507 
5508   // __va_start on Windows does not validate the parameter qualifiers
5509 
5510   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5511   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5512 
5513   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5514   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5515 
5516   const QualType &ConstCharPtrTy =
5517       Context.getPointerType(Context.CharTy.withConst());
5518   if (!Arg1Ty->isPointerType() ||
5519       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
5520     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5521         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5522         << 0                                      /* qualifier difference */
5523         << 3                                      /* parameter mismatch */
5524         << 2 << Arg1->getType() << ConstCharPtrTy;
5525 
5526   const QualType SizeTy = Context.getSizeType();
5527   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
5528     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5529         << Arg2->getType() << SizeTy << 1 /* different class */
5530         << 0                              /* qualifier difference */
5531         << 3                              /* parameter mismatch */
5532         << 3 << Arg2->getType() << SizeTy;
5533 
5534   return false;
5535 }
5536 
5537 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
5538 /// friends.  This is declared to take (...), so we have to check everything.
5539 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
5540   if (TheCall->getNumArgs() < 2)
5541     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5542            << 0 << 2 << TheCall->getNumArgs() /*function call*/;
5543   if (TheCall->getNumArgs() > 2)
5544     return Diag(TheCall->getArg(2)->getBeginLoc(),
5545                 diag::err_typecheck_call_too_many_args)
5546            << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5547            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5548                           (*(TheCall->arg_end() - 1))->getEndLoc());
5549 
5550   ExprResult OrigArg0 = TheCall->getArg(0);
5551   ExprResult OrigArg1 = TheCall->getArg(1);
5552 
5553   // Do standard promotions between the two arguments, returning their common
5554   // type.
5555   QualType Res = UsualArithmeticConversions(
5556       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
5557   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5558     return true;
5559 
5560   // Make sure any conversions are pushed back into the call; this is
5561   // type safe since unordered compare builtins are declared as "_Bool
5562   // foo(...)".
5563   TheCall->setArg(0, OrigArg0.get());
5564   TheCall->setArg(1, OrigArg1.get());
5565 
5566   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5567     return false;
5568 
5569   // If the common type isn't a real floating type, then the arguments were
5570   // invalid for this operation.
5571   if (Res.isNull() || !Res->isRealFloatingType())
5572     return Diag(OrigArg0.get()->getBeginLoc(),
5573                 diag::err_typecheck_call_invalid_ordered_compare)
5574            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5575            << SourceRange(OrigArg0.get()->getBeginLoc(),
5576                           OrigArg1.get()->getEndLoc());
5577 
5578   return false;
5579 }
5580 
5581 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
5582 /// __builtin_isnan and friends.  This is declared to take (...), so we have
5583 /// to check everything. We expect the last argument to be a floating point
5584 /// value.
5585 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
5586   if (TheCall->getNumArgs() < NumArgs)
5587     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5588            << 0 << NumArgs << TheCall->getNumArgs() /*function call*/;
5589   if (TheCall->getNumArgs() > NumArgs)
5590     return Diag(TheCall->getArg(NumArgs)->getBeginLoc(),
5591                 diag::err_typecheck_call_too_many_args)
5592            << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
5593            << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(),
5594                           (*(TheCall->arg_end() - 1))->getEndLoc());
5595 
5596   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
5597   // on all preceding parameters just being int.  Try all of those.
5598   for (unsigned i = 0; i < NumArgs - 1; ++i) {
5599     Expr *Arg = TheCall->getArg(i);
5600 
5601     if (Arg->isTypeDependent())
5602       return false;
5603 
5604     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
5605 
5606     if (Res.isInvalid())
5607       return true;
5608     TheCall->setArg(i, Res.get());
5609   }
5610 
5611   Expr *OrigArg = TheCall->getArg(NumArgs-1);
5612 
5613   if (OrigArg->isTypeDependent())
5614     return false;
5615 
5616   // Usual Unary Conversions will convert half to float, which we want for
5617   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
5618   // type how it is, but do normal L->Rvalue conversions.
5619   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
5620     OrigArg = UsualUnaryConversions(OrigArg).get();
5621   else
5622     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
5623   TheCall->setArg(NumArgs - 1, OrigArg);
5624 
5625   // This operation requires a non-_Complex floating-point number.
5626   if (!OrigArg->getType()->isRealFloatingType())
5627     return Diag(OrigArg->getBeginLoc(),
5628                 diag::err_typecheck_call_invalid_unary_fp)
5629            << OrigArg->getType() << OrigArg->getSourceRange();
5630 
5631   return false;
5632 }
5633 
5634 // Customized Sema Checking for VSX builtins that have the following signature:
5635 // vector [...] builtinName(vector [...], vector [...], const int);
5636 // Which takes the same type of vectors (any legal vector type) for the first
5637 // two arguments and takes compile time constant for the third argument.
5638 // Example builtins are :
5639 // vector double vec_xxpermdi(vector double, vector double, int);
5640 // vector short vec_xxsldwi(vector short, vector short, int);
5641 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
5642   unsigned ExpectedNumArgs = 3;
5643   if (TheCall->getNumArgs() < ExpectedNumArgs)
5644     return Diag(TheCall->getEndLoc(),
5645                 diag::err_typecheck_call_too_few_args_at_least)
5646            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5647            << TheCall->getSourceRange();
5648 
5649   if (TheCall->getNumArgs() > ExpectedNumArgs)
5650     return Diag(TheCall->getEndLoc(),
5651                 diag::err_typecheck_call_too_many_args_at_most)
5652            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5653            << TheCall->getSourceRange();
5654 
5655   // Check the third argument is a compile time constant
5656   llvm::APSInt Value;
5657   if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
5658     return Diag(TheCall->getBeginLoc(),
5659                 diag::err_vsx_builtin_nonconstant_argument)
5660            << 3 /* argument index */ << TheCall->getDirectCallee()
5661            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5662                           TheCall->getArg(2)->getEndLoc());
5663 
5664   QualType Arg1Ty = TheCall->getArg(0)->getType();
5665   QualType Arg2Ty = TheCall->getArg(1)->getType();
5666 
5667   // Check the type of argument 1 and argument 2 are vectors.
5668   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
5669   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
5670       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
5671     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
5672            << TheCall->getDirectCallee()
5673            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5674                           TheCall->getArg(1)->getEndLoc());
5675   }
5676 
5677   // Check the first two arguments are the same type.
5678   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
5679     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
5680            << TheCall->getDirectCallee()
5681            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5682                           TheCall->getArg(1)->getEndLoc());
5683   }
5684 
5685   // When default clang type checking is turned off and the customized type
5686   // checking is used, the returning type of the function must be explicitly
5687   // set. Otherwise it is _Bool by default.
5688   TheCall->setType(Arg1Ty);
5689 
5690   return false;
5691 }
5692 
5693 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
5694 // This is declared to take (...), so we have to check everything.
5695 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
5696   if (TheCall->getNumArgs() < 2)
5697     return ExprError(Diag(TheCall->getEndLoc(),
5698                           diag::err_typecheck_call_too_few_args_at_least)
5699                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5700                      << TheCall->getSourceRange());
5701 
5702   // Determine which of the following types of shufflevector we're checking:
5703   // 1) unary, vector mask: (lhs, mask)
5704   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
5705   QualType resType = TheCall->getArg(0)->getType();
5706   unsigned numElements = 0;
5707 
5708   if (!TheCall->getArg(0)->isTypeDependent() &&
5709       !TheCall->getArg(1)->isTypeDependent()) {
5710     QualType LHSType = TheCall->getArg(0)->getType();
5711     QualType RHSType = TheCall->getArg(1)->getType();
5712 
5713     if (!LHSType->isVectorType() || !RHSType->isVectorType())
5714       return ExprError(
5715           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
5716           << TheCall->getDirectCallee()
5717           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5718                          TheCall->getArg(1)->getEndLoc()));
5719 
5720     numElements = LHSType->castAs<VectorType>()->getNumElements();
5721     unsigned numResElements = TheCall->getNumArgs() - 2;
5722 
5723     // Check to see if we have a call with 2 vector arguments, the unary shuffle
5724     // with mask.  If so, verify that RHS is an integer vector type with the
5725     // same number of elts as lhs.
5726     if (TheCall->getNumArgs() == 2) {
5727       if (!RHSType->hasIntegerRepresentation() ||
5728           RHSType->castAs<VectorType>()->getNumElements() != numElements)
5729         return ExprError(Diag(TheCall->getBeginLoc(),
5730                               diag::err_vec_builtin_incompatible_vector)
5731                          << TheCall->getDirectCallee()
5732                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
5733                                         TheCall->getArg(1)->getEndLoc()));
5734     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
5735       return ExprError(Diag(TheCall->getBeginLoc(),
5736                             diag::err_vec_builtin_incompatible_vector)
5737                        << TheCall->getDirectCallee()
5738                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5739                                       TheCall->getArg(1)->getEndLoc()));
5740     } else if (numElements != numResElements) {
5741       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
5742       resType = Context.getVectorType(eltType, numResElements,
5743                                       VectorType::GenericVector);
5744     }
5745   }
5746 
5747   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
5748     if (TheCall->getArg(i)->isTypeDependent() ||
5749         TheCall->getArg(i)->isValueDependent())
5750       continue;
5751 
5752     llvm::APSInt Result(32);
5753     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
5754       return ExprError(Diag(TheCall->getBeginLoc(),
5755                             diag::err_shufflevector_nonconstant_argument)
5756                        << TheCall->getArg(i)->getSourceRange());
5757 
5758     // Allow -1 which will be translated to undef in the IR.
5759     if (Result.isSigned() && Result.isAllOnesValue())
5760       continue;
5761 
5762     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
5763       return ExprError(Diag(TheCall->getBeginLoc(),
5764                             diag::err_shufflevector_argument_too_large)
5765                        << TheCall->getArg(i)->getSourceRange());
5766   }
5767 
5768   SmallVector<Expr*, 32> exprs;
5769 
5770   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
5771     exprs.push_back(TheCall->getArg(i));
5772     TheCall->setArg(i, nullptr);
5773   }
5774 
5775   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
5776                                          TheCall->getCallee()->getBeginLoc(),
5777                                          TheCall->getRParenLoc());
5778 }
5779 
5780 /// SemaConvertVectorExpr - Handle __builtin_convertvector
5781 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
5782                                        SourceLocation BuiltinLoc,
5783                                        SourceLocation RParenLoc) {
5784   ExprValueKind VK = VK_RValue;
5785   ExprObjectKind OK = OK_Ordinary;
5786   QualType DstTy = TInfo->getType();
5787   QualType SrcTy = E->getType();
5788 
5789   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
5790     return ExprError(Diag(BuiltinLoc,
5791                           diag::err_convertvector_non_vector)
5792                      << E->getSourceRange());
5793   if (!DstTy->isVectorType() && !DstTy->isDependentType())
5794     return ExprError(Diag(BuiltinLoc,
5795                           diag::err_convertvector_non_vector_type));
5796 
5797   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
5798     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
5799     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
5800     if (SrcElts != DstElts)
5801       return ExprError(Diag(BuiltinLoc,
5802                             diag::err_convertvector_incompatible_vector)
5803                        << E->getSourceRange());
5804   }
5805 
5806   return new (Context)
5807       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5808 }
5809 
5810 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
5811 // This is declared to take (const void*, ...) and can take two
5812 // optional constant int args.
5813 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
5814   unsigned NumArgs = TheCall->getNumArgs();
5815 
5816   if (NumArgs > 3)
5817     return Diag(TheCall->getEndLoc(),
5818                 diag::err_typecheck_call_too_many_args_at_most)
5819            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
5820 
5821   // Argument 0 is checked for us and the remaining arguments must be
5822   // constant integers.
5823   for (unsigned i = 1; i != NumArgs; ++i)
5824     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
5825       return true;
5826 
5827   return false;
5828 }
5829 
5830 /// SemaBuiltinAssume - Handle __assume (MS Extension).
5831 // __assume does not evaluate its arguments, and should warn if its argument
5832 // has side effects.
5833 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
5834   Expr *Arg = TheCall->getArg(0);
5835   if (Arg->isInstantiationDependent()) return false;
5836 
5837   if (Arg->HasSideEffects(Context))
5838     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
5839         << Arg->getSourceRange()
5840         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
5841 
5842   return false;
5843 }
5844 
5845 /// Handle __builtin_alloca_with_align. This is declared
5846 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
5847 /// than 8.
5848 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
5849   // The alignment must be a constant integer.
5850   Expr *Arg = TheCall->getArg(1);
5851 
5852   // We can't check the value of a dependent argument.
5853   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5854     if (const auto *UE =
5855             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
5856       if (UE->getKind() == UETT_AlignOf ||
5857           UE->getKind() == UETT_PreferredAlignOf)
5858         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
5859             << Arg->getSourceRange();
5860 
5861     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
5862 
5863     if (!Result.isPowerOf2())
5864       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5865              << Arg->getSourceRange();
5866 
5867     if (Result < Context.getCharWidth())
5868       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
5869              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
5870 
5871     if (Result > std::numeric_limits<int32_t>::max())
5872       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
5873              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
5874   }
5875 
5876   return false;
5877 }
5878 
5879 /// Handle __builtin_assume_aligned. This is declared
5880 /// as (const void*, size_t, ...) and can take one optional constant int arg.
5881 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
5882   unsigned NumArgs = TheCall->getNumArgs();
5883 
5884   if (NumArgs > 3)
5885     return Diag(TheCall->getEndLoc(),
5886                 diag::err_typecheck_call_too_many_args_at_most)
5887            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
5888 
5889   // The alignment must be a constant integer.
5890   Expr *Arg = TheCall->getArg(1);
5891 
5892   // We can't check the value of a dependent argument.
5893   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5894     llvm::APSInt Result;
5895     if (SemaBuiltinConstantArg(TheCall, 1, Result))
5896       return true;
5897 
5898     if (!Result.isPowerOf2())
5899       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5900              << Arg->getSourceRange();
5901 
5902     if (Result > Sema::MaximumAlignment)
5903       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
5904           << Arg->getSourceRange() << Sema::MaximumAlignment;
5905   }
5906 
5907   if (NumArgs > 2) {
5908     ExprResult Arg(TheCall->getArg(2));
5909     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5910       Context.getSizeType(), false);
5911     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5912     if (Arg.isInvalid()) return true;
5913     TheCall->setArg(2, Arg.get());
5914   }
5915 
5916   return false;
5917 }
5918 
5919 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
5920   unsigned BuiltinID =
5921       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
5922   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
5923 
5924   unsigned NumArgs = TheCall->getNumArgs();
5925   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
5926   if (NumArgs < NumRequiredArgs) {
5927     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5928            << 0 /* function call */ << NumRequiredArgs << NumArgs
5929            << TheCall->getSourceRange();
5930   }
5931   if (NumArgs >= NumRequiredArgs + 0x100) {
5932     return Diag(TheCall->getEndLoc(),
5933                 diag::err_typecheck_call_too_many_args_at_most)
5934            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
5935            << TheCall->getSourceRange();
5936   }
5937   unsigned i = 0;
5938 
5939   // For formatting call, check buffer arg.
5940   if (!IsSizeCall) {
5941     ExprResult Arg(TheCall->getArg(i));
5942     InitializedEntity Entity = InitializedEntity::InitializeParameter(
5943         Context, Context.VoidPtrTy, false);
5944     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5945     if (Arg.isInvalid())
5946       return true;
5947     TheCall->setArg(i, Arg.get());
5948     i++;
5949   }
5950 
5951   // Check string literal arg.
5952   unsigned FormatIdx = i;
5953   {
5954     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
5955     if (Arg.isInvalid())
5956       return true;
5957     TheCall->setArg(i, Arg.get());
5958     i++;
5959   }
5960 
5961   // Make sure variadic args are scalar.
5962   unsigned FirstDataArg = i;
5963   while (i < NumArgs) {
5964     ExprResult Arg = DefaultVariadicArgumentPromotion(
5965         TheCall->getArg(i), VariadicFunction, nullptr);
5966     if (Arg.isInvalid())
5967       return true;
5968     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
5969     if (ArgSize.getQuantity() >= 0x100) {
5970       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
5971              << i << (int)ArgSize.getQuantity() << 0xff
5972              << TheCall->getSourceRange();
5973     }
5974     TheCall->setArg(i, Arg.get());
5975     i++;
5976   }
5977 
5978   // Check formatting specifiers. NOTE: We're only doing this for the non-size
5979   // call to avoid duplicate diagnostics.
5980   if (!IsSizeCall) {
5981     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
5982     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
5983     bool Success = CheckFormatArguments(
5984         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
5985         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
5986         CheckedVarArgs);
5987     if (!Success)
5988       return true;
5989   }
5990 
5991   if (IsSizeCall) {
5992     TheCall->setType(Context.getSizeType());
5993   } else {
5994     TheCall->setType(Context.VoidPtrTy);
5995   }
5996   return false;
5997 }
5998 
5999 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
6000 /// TheCall is a constant expression.
6001 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
6002                                   llvm::APSInt &Result) {
6003   Expr *Arg = TheCall->getArg(ArgNum);
6004   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6005   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6006 
6007   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
6008 
6009   if (!Arg->isIntegerConstantExpr(Result, Context))
6010     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6011            << FDecl->getDeclName() << Arg->getSourceRange();
6012 
6013   return false;
6014 }
6015 
6016 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
6017 /// TheCall is a constant expression in the range [Low, High].
6018 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
6019                                        int Low, int High, bool RangeIsError) {
6020   if (isConstantEvaluated())
6021     return false;
6022   llvm::APSInt Result;
6023 
6024   // We can't check the value of a dependent argument.
6025   Expr *Arg = TheCall->getArg(ArgNum);
6026   if (Arg->isTypeDependent() || Arg->isValueDependent())
6027     return false;
6028 
6029   // Check constant-ness first.
6030   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6031     return true;
6032 
6033   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6034     if (RangeIsError)
6035       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6036              << Result.toString(10) << Low << High << Arg->getSourceRange();
6037     else
6038       // Defer the warning until we know if the code will be emitted so that
6039       // dead code can ignore this.
6040       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6041                           PDiag(diag::warn_argument_invalid_range)
6042                               << Result.toString(10) << Low << High
6043                               << Arg->getSourceRange());
6044   }
6045 
6046   return false;
6047 }
6048 
6049 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
6050 /// TheCall is a constant expression is a multiple of Num..
6051 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
6052                                           unsigned Num) {
6053   llvm::APSInt Result;
6054 
6055   // We can't check the value of a dependent argument.
6056   Expr *Arg = TheCall->getArg(ArgNum);
6057   if (Arg->isTypeDependent() || Arg->isValueDependent())
6058     return false;
6059 
6060   // Check constant-ness first.
6061   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6062     return true;
6063 
6064   if (Result.getSExtValue() % Num != 0)
6065     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6066            << Num << Arg->getSourceRange();
6067 
6068   return false;
6069 }
6070 
6071 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
6072 /// constant expression representing a power of 2.
6073 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
6074   llvm::APSInt Result;
6075 
6076   // We can't check the value of a dependent argument.
6077   Expr *Arg = TheCall->getArg(ArgNum);
6078   if (Arg->isTypeDependent() || Arg->isValueDependent())
6079     return false;
6080 
6081   // Check constant-ness first.
6082   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6083     return true;
6084 
6085   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
6086   // and only if x is a power of 2.
6087   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
6088     return false;
6089 
6090   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
6091          << Arg->getSourceRange();
6092 }
6093 
6094 static bool IsShiftedByte(llvm::APSInt Value) {
6095   if (Value.isNegative())
6096     return false;
6097 
6098   // Check if it's a shifted byte, by shifting it down
6099   while (true) {
6100     // If the value fits in the bottom byte, the check passes.
6101     if (Value < 0x100)
6102       return true;
6103 
6104     // Otherwise, if the value has _any_ bits in the bottom byte, the check
6105     // fails.
6106     if ((Value & 0xFF) != 0)
6107       return false;
6108 
6109     // If the bottom 8 bits are all 0, but something above that is nonzero,
6110     // then shifting the value right by 8 bits won't affect whether it's a
6111     // shifted byte or not. So do that, and go round again.
6112     Value >>= 8;
6113   }
6114 }
6115 
6116 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
6117 /// a constant expression representing an arbitrary byte value shifted left by
6118 /// a multiple of 8 bits.
6119 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
6120                                              unsigned ArgBits) {
6121   llvm::APSInt Result;
6122 
6123   // We can't check the value of a dependent argument.
6124   Expr *Arg = TheCall->getArg(ArgNum);
6125   if (Arg->isTypeDependent() || Arg->isValueDependent())
6126     return false;
6127 
6128   // Check constant-ness first.
6129   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6130     return true;
6131 
6132   // Truncate to the given size.
6133   Result = Result.getLoBits(ArgBits);
6134   Result.setIsUnsigned(true);
6135 
6136   if (IsShiftedByte(Result))
6137     return false;
6138 
6139   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
6140          << Arg->getSourceRange();
6141 }
6142 
6143 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
6144 /// TheCall is a constant expression representing either a shifted byte value,
6145 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
6146 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
6147 /// Arm MVE intrinsics.
6148 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
6149                                                    int ArgNum,
6150                                                    unsigned ArgBits) {
6151   llvm::APSInt Result;
6152 
6153   // We can't check the value of a dependent argument.
6154   Expr *Arg = TheCall->getArg(ArgNum);
6155   if (Arg->isTypeDependent() || Arg->isValueDependent())
6156     return false;
6157 
6158   // Check constant-ness first.
6159   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6160     return true;
6161 
6162   // Truncate to the given size.
6163   Result = Result.getLoBits(ArgBits);
6164   Result.setIsUnsigned(true);
6165 
6166   // Check to see if it's in either of the required forms.
6167   if (IsShiftedByte(Result) ||
6168       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
6169     return false;
6170 
6171   return Diag(TheCall->getBeginLoc(),
6172               diag::err_argument_not_shifted_byte_or_xxff)
6173          << Arg->getSourceRange();
6174 }
6175 
6176 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
6177 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
6178   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
6179     if (checkArgCount(*this, TheCall, 2))
6180       return true;
6181     Expr *Arg0 = TheCall->getArg(0);
6182     Expr *Arg1 = TheCall->getArg(1);
6183 
6184     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6185     if (FirstArg.isInvalid())
6186       return true;
6187     QualType FirstArgType = FirstArg.get()->getType();
6188     if (!FirstArgType->isAnyPointerType())
6189       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6190                << "first" << FirstArgType << Arg0->getSourceRange();
6191     TheCall->setArg(0, FirstArg.get());
6192 
6193     ExprResult SecArg = DefaultLvalueConversion(Arg1);
6194     if (SecArg.isInvalid())
6195       return true;
6196     QualType SecArgType = SecArg.get()->getType();
6197     if (!SecArgType->isIntegerType())
6198       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6199                << "second" << SecArgType << Arg1->getSourceRange();
6200 
6201     // Derive the return type from the pointer argument.
6202     TheCall->setType(FirstArgType);
6203     return false;
6204   }
6205 
6206   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
6207     if (checkArgCount(*this, TheCall, 2))
6208       return true;
6209 
6210     Expr *Arg0 = TheCall->getArg(0);
6211     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6212     if (FirstArg.isInvalid())
6213       return true;
6214     QualType FirstArgType = FirstArg.get()->getType();
6215     if (!FirstArgType->isAnyPointerType())
6216       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6217                << "first" << FirstArgType << Arg0->getSourceRange();
6218     TheCall->setArg(0, FirstArg.get());
6219 
6220     // Derive the return type from the pointer argument.
6221     TheCall->setType(FirstArgType);
6222 
6223     // Second arg must be an constant in range [0,15]
6224     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6225   }
6226 
6227   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
6228     if (checkArgCount(*this, TheCall, 2))
6229       return true;
6230     Expr *Arg0 = TheCall->getArg(0);
6231     Expr *Arg1 = TheCall->getArg(1);
6232 
6233     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6234     if (FirstArg.isInvalid())
6235       return true;
6236     QualType FirstArgType = FirstArg.get()->getType();
6237     if (!FirstArgType->isAnyPointerType())
6238       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6239                << "first" << FirstArgType << Arg0->getSourceRange();
6240 
6241     QualType SecArgType = Arg1->getType();
6242     if (!SecArgType->isIntegerType())
6243       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6244                << "second" << SecArgType << Arg1->getSourceRange();
6245     TheCall->setType(Context.IntTy);
6246     return false;
6247   }
6248 
6249   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
6250       BuiltinID == AArch64::BI__builtin_arm_stg) {
6251     if (checkArgCount(*this, TheCall, 1))
6252       return true;
6253     Expr *Arg0 = TheCall->getArg(0);
6254     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6255     if (FirstArg.isInvalid())
6256       return true;
6257 
6258     QualType FirstArgType = FirstArg.get()->getType();
6259     if (!FirstArgType->isAnyPointerType())
6260       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6261                << "first" << FirstArgType << Arg0->getSourceRange();
6262     TheCall->setArg(0, FirstArg.get());
6263 
6264     // Derive the return type from the pointer argument.
6265     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
6266       TheCall->setType(FirstArgType);
6267     return false;
6268   }
6269 
6270   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
6271     Expr *ArgA = TheCall->getArg(0);
6272     Expr *ArgB = TheCall->getArg(1);
6273 
6274     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
6275     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
6276 
6277     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
6278       return true;
6279 
6280     QualType ArgTypeA = ArgExprA.get()->getType();
6281     QualType ArgTypeB = ArgExprB.get()->getType();
6282 
6283     auto isNull = [&] (Expr *E) -> bool {
6284       return E->isNullPointerConstant(
6285                         Context, Expr::NPC_ValueDependentIsNotNull); };
6286 
6287     // argument should be either a pointer or null
6288     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
6289       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6290         << "first" << ArgTypeA << ArgA->getSourceRange();
6291 
6292     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
6293       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6294         << "second" << ArgTypeB << ArgB->getSourceRange();
6295 
6296     // Ensure Pointee types are compatible
6297     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
6298         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
6299       QualType pointeeA = ArgTypeA->getPointeeType();
6300       QualType pointeeB = ArgTypeB->getPointeeType();
6301       if (!Context.typesAreCompatible(
6302              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
6303              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
6304         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
6305           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
6306           << ArgB->getSourceRange();
6307       }
6308     }
6309 
6310     // at least one argument should be pointer type
6311     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
6312       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
6313         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
6314 
6315     if (isNull(ArgA)) // adopt type of the other pointer
6316       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
6317 
6318     if (isNull(ArgB))
6319       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
6320 
6321     TheCall->setArg(0, ArgExprA.get());
6322     TheCall->setArg(1, ArgExprB.get());
6323     TheCall->setType(Context.LongLongTy);
6324     return false;
6325   }
6326   assert(false && "Unhandled ARM MTE intrinsic");
6327   return true;
6328 }
6329 
6330 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
6331 /// TheCall is an ARM/AArch64 special register string literal.
6332 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
6333                                     int ArgNum, unsigned ExpectedFieldNum,
6334                                     bool AllowName) {
6335   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
6336                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
6337                       BuiltinID == ARM::BI__builtin_arm_rsr ||
6338                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
6339                       BuiltinID == ARM::BI__builtin_arm_wsr ||
6340                       BuiltinID == ARM::BI__builtin_arm_wsrp;
6341   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
6342                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
6343                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
6344                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
6345                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
6346                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
6347   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
6348 
6349   // We can't check the value of a dependent argument.
6350   Expr *Arg = TheCall->getArg(ArgNum);
6351   if (Arg->isTypeDependent() || Arg->isValueDependent())
6352     return false;
6353 
6354   // Check if the argument is a string literal.
6355   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
6356     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
6357            << Arg->getSourceRange();
6358 
6359   // Check the type of special register given.
6360   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
6361   SmallVector<StringRef, 6> Fields;
6362   Reg.split(Fields, ":");
6363 
6364   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
6365     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6366            << Arg->getSourceRange();
6367 
6368   // If the string is the name of a register then we cannot check that it is
6369   // valid here but if the string is of one the forms described in ACLE then we
6370   // can check that the supplied fields are integers and within the valid
6371   // ranges.
6372   if (Fields.size() > 1) {
6373     bool FiveFields = Fields.size() == 5;
6374 
6375     bool ValidString = true;
6376     if (IsARMBuiltin) {
6377       ValidString &= Fields[0].startswith_lower("cp") ||
6378                      Fields[0].startswith_lower("p");
6379       if (ValidString)
6380         Fields[0] =
6381           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
6382 
6383       ValidString &= Fields[2].startswith_lower("c");
6384       if (ValidString)
6385         Fields[2] = Fields[2].drop_front(1);
6386 
6387       if (FiveFields) {
6388         ValidString &= Fields[3].startswith_lower("c");
6389         if (ValidString)
6390           Fields[3] = Fields[3].drop_front(1);
6391       }
6392     }
6393 
6394     SmallVector<int, 5> Ranges;
6395     if (FiveFields)
6396       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
6397     else
6398       Ranges.append({15, 7, 15});
6399 
6400     for (unsigned i=0; i<Fields.size(); ++i) {
6401       int IntField;
6402       ValidString &= !Fields[i].getAsInteger(10, IntField);
6403       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
6404     }
6405 
6406     if (!ValidString)
6407       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6408              << Arg->getSourceRange();
6409   } else if (IsAArch64Builtin && Fields.size() == 1) {
6410     // If the register name is one of those that appear in the condition below
6411     // and the special register builtin being used is one of the write builtins,
6412     // then we require that the argument provided for writing to the register
6413     // is an integer constant expression. This is because it will be lowered to
6414     // an MSR (immediate) instruction, so we need to know the immediate at
6415     // compile time.
6416     if (TheCall->getNumArgs() != 2)
6417       return false;
6418 
6419     std::string RegLower = Reg.lower();
6420     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
6421         RegLower != "pan" && RegLower != "uao")
6422       return false;
6423 
6424     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6425   }
6426 
6427   return false;
6428 }
6429 
6430 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
6431 /// This checks that the target supports __builtin_longjmp and
6432 /// that val is a constant 1.
6433 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
6434   if (!Context.getTargetInfo().hasSjLjLowering())
6435     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
6436            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6437 
6438   Expr *Arg = TheCall->getArg(1);
6439   llvm::APSInt Result;
6440 
6441   // TODO: This is less than ideal. Overload this to take a value.
6442   if (SemaBuiltinConstantArg(TheCall, 1, Result))
6443     return true;
6444 
6445   if (Result != 1)
6446     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
6447            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6448 
6449   return false;
6450 }
6451 
6452 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
6453 /// This checks that the target supports __builtin_setjmp.
6454 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
6455   if (!Context.getTargetInfo().hasSjLjLowering())
6456     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
6457            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6458   return false;
6459 }
6460 
6461 namespace {
6462 
6463 class UncoveredArgHandler {
6464   enum { Unknown = -1, AllCovered = -2 };
6465 
6466   signed FirstUncoveredArg = Unknown;
6467   SmallVector<const Expr *, 4> DiagnosticExprs;
6468 
6469 public:
6470   UncoveredArgHandler() = default;
6471 
6472   bool hasUncoveredArg() const {
6473     return (FirstUncoveredArg >= 0);
6474   }
6475 
6476   unsigned getUncoveredArg() const {
6477     assert(hasUncoveredArg() && "no uncovered argument");
6478     return FirstUncoveredArg;
6479   }
6480 
6481   void setAllCovered() {
6482     // A string has been found with all arguments covered, so clear out
6483     // the diagnostics.
6484     DiagnosticExprs.clear();
6485     FirstUncoveredArg = AllCovered;
6486   }
6487 
6488   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6489     assert(NewFirstUncoveredArg >= 0 && "Outside range");
6490 
6491     // Don't update if a previous string covers all arguments.
6492     if (FirstUncoveredArg == AllCovered)
6493       return;
6494 
6495     // UncoveredArgHandler tracks the highest uncovered argument index
6496     // and with it all the strings that match this index.
6497     if (NewFirstUncoveredArg == FirstUncoveredArg)
6498       DiagnosticExprs.push_back(StrExpr);
6499     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6500       DiagnosticExprs.clear();
6501       DiagnosticExprs.push_back(StrExpr);
6502       FirstUncoveredArg = NewFirstUncoveredArg;
6503     }
6504   }
6505 
6506   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6507 };
6508 
6509 enum StringLiteralCheckType {
6510   SLCT_NotALiteral,
6511   SLCT_UncheckedLiteral,
6512   SLCT_CheckedLiteral
6513 };
6514 
6515 } // namespace
6516 
6517 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6518                                      BinaryOperatorKind BinOpKind,
6519                                      bool AddendIsRight) {
6520   unsigned BitWidth = Offset.getBitWidth();
6521   unsigned AddendBitWidth = Addend.getBitWidth();
6522   // There might be negative interim results.
6523   if (Addend.isUnsigned()) {
6524     Addend = Addend.zext(++AddendBitWidth);
6525     Addend.setIsSigned(true);
6526   }
6527   // Adjust the bit width of the APSInts.
6528   if (AddendBitWidth > BitWidth) {
6529     Offset = Offset.sext(AddendBitWidth);
6530     BitWidth = AddendBitWidth;
6531   } else if (BitWidth > AddendBitWidth) {
6532     Addend = Addend.sext(BitWidth);
6533   }
6534 
6535   bool Ov = false;
6536   llvm::APSInt ResOffset = Offset;
6537   if (BinOpKind == BO_Add)
6538     ResOffset = Offset.sadd_ov(Addend, Ov);
6539   else {
6540     assert(AddendIsRight && BinOpKind == BO_Sub &&
6541            "operator must be add or sub with addend on the right");
6542     ResOffset = Offset.ssub_ov(Addend, Ov);
6543   }
6544 
6545   // We add an offset to a pointer here so we should support an offset as big as
6546   // possible.
6547   if (Ov) {
6548     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6549            "index (intermediate) result too big");
6550     Offset = Offset.sext(2 * BitWidth);
6551     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6552     return;
6553   }
6554 
6555   Offset = ResOffset;
6556 }
6557 
6558 namespace {
6559 
6560 // This is a wrapper class around StringLiteral to support offsetted string
6561 // literals as format strings. It takes the offset into account when returning
6562 // the string and its length or the source locations to display notes correctly.
6563 class FormatStringLiteral {
6564   const StringLiteral *FExpr;
6565   int64_t Offset;
6566 
6567  public:
6568   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
6569       : FExpr(fexpr), Offset(Offset) {}
6570 
6571   StringRef getString() const {
6572     return FExpr->getString().drop_front(Offset);
6573   }
6574 
6575   unsigned getByteLength() const {
6576     return FExpr->getByteLength() - getCharByteWidth() * Offset;
6577   }
6578 
6579   unsigned getLength() const { return FExpr->getLength() - Offset; }
6580   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
6581 
6582   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
6583 
6584   QualType getType() const { return FExpr->getType(); }
6585 
6586   bool isAscii() const { return FExpr->isAscii(); }
6587   bool isWide() const { return FExpr->isWide(); }
6588   bool isUTF8() const { return FExpr->isUTF8(); }
6589   bool isUTF16() const { return FExpr->isUTF16(); }
6590   bool isUTF32() const { return FExpr->isUTF32(); }
6591   bool isPascal() const { return FExpr->isPascal(); }
6592 
6593   SourceLocation getLocationOfByte(
6594       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
6595       const TargetInfo &Target, unsigned *StartToken = nullptr,
6596       unsigned *StartTokenByteOffset = nullptr) const {
6597     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
6598                                     StartToken, StartTokenByteOffset);
6599   }
6600 
6601   SourceLocation getBeginLoc() const LLVM_READONLY {
6602     return FExpr->getBeginLoc().getLocWithOffset(Offset);
6603   }
6604 
6605   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
6606 };
6607 
6608 }  // namespace
6609 
6610 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
6611                               const Expr *OrigFormatExpr,
6612                               ArrayRef<const Expr *> Args,
6613                               bool HasVAListArg, unsigned format_idx,
6614                               unsigned firstDataArg,
6615                               Sema::FormatStringType Type,
6616                               bool inFunctionCall,
6617                               Sema::VariadicCallType CallType,
6618                               llvm::SmallBitVector &CheckedVarArgs,
6619                               UncoveredArgHandler &UncoveredArg,
6620                               bool IgnoreStringsWithoutSpecifiers);
6621 
6622 // Determine if an expression is a string literal or constant string.
6623 // If this function returns false on the arguments to a function expecting a
6624 // format string, we will usually need to emit a warning.
6625 // True string literals are then checked by CheckFormatString.
6626 static StringLiteralCheckType
6627 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
6628                       bool HasVAListArg, unsigned format_idx,
6629                       unsigned firstDataArg, Sema::FormatStringType Type,
6630                       Sema::VariadicCallType CallType, bool InFunctionCall,
6631                       llvm::SmallBitVector &CheckedVarArgs,
6632                       UncoveredArgHandler &UncoveredArg,
6633                       llvm::APSInt Offset,
6634                       bool IgnoreStringsWithoutSpecifiers = false) {
6635   if (S.isConstantEvaluated())
6636     return SLCT_NotALiteral;
6637  tryAgain:
6638   assert(Offset.isSigned() && "invalid offset");
6639 
6640   if (E->isTypeDependent() || E->isValueDependent())
6641     return SLCT_NotALiteral;
6642 
6643   E = E->IgnoreParenCasts();
6644 
6645   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
6646     // Technically -Wformat-nonliteral does not warn about this case.
6647     // The behavior of printf and friends in this case is implementation
6648     // dependent.  Ideally if the format string cannot be null then
6649     // it should have a 'nonnull' attribute in the function prototype.
6650     return SLCT_UncheckedLiteral;
6651 
6652   switch (E->getStmtClass()) {
6653   case Stmt::BinaryConditionalOperatorClass:
6654   case Stmt::ConditionalOperatorClass: {
6655     // The expression is a literal if both sub-expressions were, and it was
6656     // completely checked only if both sub-expressions were checked.
6657     const AbstractConditionalOperator *C =
6658         cast<AbstractConditionalOperator>(E);
6659 
6660     // Determine whether it is necessary to check both sub-expressions, for
6661     // example, because the condition expression is a constant that can be
6662     // evaluated at compile time.
6663     bool CheckLeft = true, CheckRight = true;
6664 
6665     bool Cond;
6666     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
6667                                                  S.isConstantEvaluated())) {
6668       if (Cond)
6669         CheckRight = false;
6670       else
6671         CheckLeft = false;
6672     }
6673 
6674     // We need to maintain the offsets for the right and the left hand side
6675     // separately to check if every possible indexed expression is a valid
6676     // string literal. They might have different offsets for different string
6677     // literals in the end.
6678     StringLiteralCheckType Left;
6679     if (!CheckLeft)
6680       Left = SLCT_UncheckedLiteral;
6681     else {
6682       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
6683                                    HasVAListArg, format_idx, firstDataArg,
6684                                    Type, CallType, InFunctionCall,
6685                                    CheckedVarArgs, UncoveredArg, Offset,
6686                                    IgnoreStringsWithoutSpecifiers);
6687       if (Left == SLCT_NotALiteral || !CheckRight) {
6688         return Left;
6689       }
6690     }
6691 
6692     StringLiteralCheckType Right = checkFormatStringExpr(
6693         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
6694         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6695         IgnoreStringsWithoutSpecifiers);
6696 
6697     return (CheckLeft && Left < Right) ? Left : Right;
6698   }
6699 
6700   case Stmt::ImplicitCastExprClass:
6701     E = cast<ImplicitCastExpr>(E)->getSubExpr();
6702     goto tryAgain;
6703 
6704   case Stmt::OpaqueValueExprClass:
6705     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
6706       E = src;
6707       goto tryAgain;
6708     }
6709     return SLCT_NotALiteral;
6710 
6711   case Stmt::PredefinedExprClass:
6712     // While __func__, etc., are technically not string literals, they
6713     // cannot contain format specifiers and thus are not a security
6714     // liability.
6715     return SLCT_UncheckedLiteral;
6716 
6717   case Stmt::DeclRefExprClass: {
6718     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6719 
6720     // As an exception, do not flag errors for variables binding to
6721     // const string literals.
6722     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
6723       bool isConstant = false;
6724       QualType T = DR->getType();
6725 
6726       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
6727         isConstant = AT->getElementType().isConstant(S.Context);
6728       } else if (const PointerType *PT = T->getAs<PointerType>()) {
6729         isConstant = T.isConstant(S.Context) &&
6730                      PT->getPointeeType().isConstant(S.Context);
6731       } else if (T->isObjCObjectPointerType()) {
6732         // In ObjC, there is usually no "const ObjectPointer" type,
6733         // so don't check if the pointee type is constant.
6734         isConstant = T.isConstant(S.Context);
6735       }
6736 
6737       if (isConstant) {
6738         if (const Expr *Init = VD->getAnyInitializer()) {
6739           // Look through initializers like const char c[] = { "foo" }
6740           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
6741             if (InitList->isStringLiteralInit())
6742               Init = InitList->getInit(0)->IgnoreParenImpCasts();
6743           }
6744           return checkFormatStringExpr(S, Init, Args,
6745                                        HasVAListArg, format_idx,
6746                                        firstDataArg, Type, CallType,
6747                                        /*InFunctionCall*/ false, CheckedVarArgs,
6748                                        UncoveredArg, Offset);
6749         }
6750       }
6751 
6752       // For vprintf* functions (i.e., HasVAListArg==true), we add a
6753       // special check to see if the format string is a function parameter
6754       // of the function calling the printf function.  If the function
6755       // has an attribute indicating it is a printf-like function, then we
6756       // should suppress warnings concerning non-literals being used in a call
6757       // to a vprintf function.  For example:
6758       //
6759       // void
6760       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
6761       //      va_list ap;
6762       //      va_start(ap, fmt);
6763       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
6764       //      ...
6765       // }
6766       if (HasVAListArg) {
6767         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
6768           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
6769             int PVIndex = PV->getFunctionScopeIndex() + 1;
6770             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
6771               // adjust for implicit parameter
6772               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6773                 if (MD->isInstance())
6774                   ++PVIndex;
6775               // We also check if the formats are compatible.
6776               // We can't pass a 'scanf' string to a 'printf' function.
6777               if (PVIndex == PVFormat->getFormatIdx() &&
6778                   Type == S.GetFormatStringType(PVFormat))
6779                 return SLCT_UncheckedLiteral;
6780             }
6781           }
6782         }
6783       }
6784     }
6785 
6786     return SLCT_NotALiteral;
6787   }
6788 
6789   case Stmt::CallExprClass:
6790   case Stmt::CXXMemberCallExprClass: {
6791     const CallExpr *CE = cast<CallExpr>(E);
6792     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
6793       bool IsFirst = true;
6794       StringLiteralCheckType CommonResult;
6795       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
6796         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
6797         StringLiteralCheckType Result = checkFormatStringExpr(
6798             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6799             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6800             IgnoreStringsWithoutSpecifiers);
6801         if (IsFirst) {
6802           CommonResult = Result;
6803           IsFirst = false;
6804         }
6805       }
6806       if (!IsFirst)
6807         return CommonResult;
6808 
6809       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
6810         unsigned BuiltinID = FD->getBuiltinID();
6811         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
6812             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
6813           const Expr *Arg = CE->getArg(0);
6814           return checkFormatStringExpr(S, Arg, Args,
6815                                        HasVAListArg, format_idx,
6816                                        firstDataArg, Type, CallType,
6817                                        InFunctionCall, CheckedVarArgs,
6818                                        UncoveredArg, Offset,
6819                                        IgnoreStringsWithoutSpecifiers);
6820         }
6821       }
6822     }
6823 
6824     return SLCT_NotALiteral;
6825   }
6826   case Stmt::ObjCMessageExprClass: {
6827     const auto *ME = cast<ObjCMessageExpr>(E);
6828     if (const auto *MD = ME->getMethodDecl()) {
6829       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
6830         // As a special case heuristic, if we're using the method -[NSBundle
6831         // localizedStringForKey:value:table:], ignore any key strings that lack
6832         // format specifiers. The idea is that if the key doesn't have any
6833         // format specifiers then its probably just a key to map to the
6834         // localized strings. If it does have format specifiers though, then its
6835         // likely that the text of the key is the format string in the
6836         // programmer's language, and should be checked.
6837         const ObjCInterfaceDecl *IFace;
6838         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
6839             IFace->getIdentifier()->isStr("NSBundle") &&
6840             MD->getSelector().isKeywordSelector(
6841                 {"localizedStringForKey", "value", "table"})) {
6842           IgnoreStringsWithoutSpecifiers = true;
6843         }
6844 
6845         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
6846         return checkFormatStringExpr(
6847             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6848             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6849             IgnoreStringsWithoutSpecifiers);
6850       }
6851     }
6852 
6853     return SLCT_NotALiteral;
6854   }
6855   case Stmt::ObjCStringLiteralClass:
6856   case Stmt::StringLiteralClass: {
6857     const StringLiteral *StrE = nullptr;
6858 
6859     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
6860       StrE = ObjCFExpr->getString();
6861     else
6862       StrE = cast<StringLiteral>(E);
6863 
6864     if (StrE) {
6865       if (Offset.isNegative() || Offset > StrE->getLength()) {
6866         // TODO: It would be better to have an explicit warning for out of
6867         // bounds literals.
6868         return SLCT_NotALiteral;
6869       }
6870       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
6871       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
6872                         firstDataArg, Type, InFunctionCall, CallType,
6873                         CheckedVarArgs, UncoveredArg,
6874                         IgnoreStringsWithoutSpecifiers);
6875       return SLCT_CheckedLiteral;
6876     }
6877 
6878     return SLCT_NotALiteral;
6879   }
6880   case Stmt::BinaryOperatorClass: {
6881     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
6882 
6883     // A string literal + an int offset is still a string literal.
6884     if (BinOp->isAdditiveOp()) {
6885       Expr::EvalResult LResult, RResult;
6886 
6887       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
6888           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
6889       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
6890           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
6891 
6892       if (LIsInt != RIsInt) {
6893         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
6894 
6895         if (LIsInt) {
6896           if (BinOpKind == BO_Add) {
6897             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
6898             E = BinOp->getRHS();
6899             goto tryAgain;
6900           }
6901         } else {
6902           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
6903           E = BinOp->getLHS();
6904           goto tryAgain;
6905         }
6906       }
6907     }
6908 
6909     return SLCT_NotALiteral;
6910   }
6911   case Stmt::UnaryOperatorClass: {
6912     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
6913     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
6914     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
6915       Expr::EvalResult IndexResult;
6916       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
6917                                        Expr::SE_NoSideEffects,
6918                                        S.isConstantEvaluated())) {
6919         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
6920                    /*RHS is int*/ true);
6921         E = ASE->getBase();
6922         goto tryAgain;
6923       }
6924     }
6925 
6926     return SLCT_NotALiteral;
6927   }
6928 
6929   default:
6930     return SLCT_NotALiteral;
6931   }
6932 }
6933 
6934 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
6935   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
6936       .Case("scanf", FST_Scanf)
6937       .Cases("printf", "printf0", FST_Printf)
6938       .Cases("NSString", "CFString", FST_NSString)
6939       .Case("strftime", FST_Strftime)
6940       .Case("strfmon", FST_Strfmon)
6941       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
6942       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
6943       .Case("os_trace", FST_OSLog)
6944       .Case("os_log", FST_OSLog)
6945       .Default(FST_Unknown);
6946 }
6947 
6948 /// CheckFormatArguments - Check calls to printf and scanf (and similar
6949 /// functions) for correct use of format strings.
6950 /// Returns true if a format string has been fully checked.
6951 bool Sema::CheckFormatArguments(const FormatAttr *Format,
6952                                 ArrayRef<const Expr *> Args,
6953                                 bool IsCXXMember,
6954                                 VariadicCallType CallType,
6955                                 SourceLocation Loc, SourceRange Range,
6956                                 llvm::SmallBitVector &CheckedVarArgs) {
6957   FormatStringInfo FSI;
6958   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
6959     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
6960                                 FSI.FirstDataArg, GetFormatStringType(Format),
6961                                 CallType, Loc, Range, CheckedVarArgs);
6962   return false;
6963 }
6964 
6965 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
6966                                 bool HasVAListArg, unsigned format_idx,
6967                                 unsigned firstDataArg, FormatStringType Type,
6968                                 VariadicCallType CallType,
6969                                 SourceLocation Loc, SourceRange Range,
6970                                 llvm::SmallBitVector &CheckedVarArgs) {
6971   // CHECK: printf/scanf-like function is called with no format string.
6972   if (format_idx >= Args.size()) {
6973     Diag(Loc, diag::warn_missing_format_string) << Range;
6974     return false;
6975   }
6976 
6977   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
6978 
6979   // CHECK: format string is not a string literal.
6980   //
6981   // Dynamically generated format strings are difficult to
6982   // automatically vet at compile time.  Requiring that format strings
6983   // are string literals: (1) permits the checking of format strings by
6984   // the compiler and thereby (2) can practically remove the source of
6985   // many format string exploits.
6986 
6987   // Format string can be either ObjC string (e.g. @"%d") or
6988   // C string (e.g. "%d")
6989   // ObjC string uses the same format specifiers as C string, so we can use
6990   // the same format string checking logic for both ObjC and C strings.
6991   UncoveredArgHandler UncoveredArg;
6992   StringLiteralCheckType CT =
6993       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
6994                             format_idx, firstDataArg, Type, CallType,
6995                             /*IsFunctionCall*/ true, CheckedVarArgs,
6996                             UncoveredArg,
6997                             /*no string offset*/ llvm::APSInt(64, false) = 0);
6998 
6999   // Generate a diagnostic where an uncovered argument is detected.
7000   if (UncoveredArg.hasUncoveredArg()) {
7001     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
7002     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
7003     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
7004   }
7005 
7006   if (CT != SLCT_NotALiteral)
7007     // Literal format string found, check done!
7008     return CT == SLCT_CheckedLiteral;
7009 
7010   // Strftime is particular as it always uses a single 'time' argument,
7011   // so it is safe to pass a non-literal string.
7012   if (Type == FST_Strftime)
7013     return false;
7014 
7015   // Do not emit diag when the string param is a macro expansion and the
7016   // format is either NSString or CFString. This is a hack to prevent
7017   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
7018   // which are usually used in place of NS and CF string literals.
7019   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
7020   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
7021     return false;
7022 
7023   // If there are no arguments specified, warn with -Wformat-security, otherwise
7024   // warn only with -Wformat-nonliteral.
7025   if (Args.size() == firstDataArg) {
7026     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
7027       << OrigFormatExpr->getSourceRange();
7028     switch (Type) {
7029     default:
7030       break;
7031     case FST_Kprintf:
7032     case FST_FreeBSDKPrintf:
7033     case FST_Printf:
7034       Diag(FormatLoc, diag::note_format_security_fixit)
7035         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
7036       break;
7037     case FST_NSString:
7038       Diag(FormatLoc, diag::note_format_security_fixit)
7039         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
7040       break;
7041     }
7042   } else {
7043     Diag(FormatLoc, diag::warn_format_nonliteral)
7044       << OrigFormatExpr->getSourceRange();
7045   }
7046   return false;
7047 }
7048 
7049 namespace {
7050 
7051 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7052 protected:
7053   Sema &S;
7054   const FormatStringLiteral *FExpr;
7055   const Expr *OrigFormatExpr;
7056   const Sema::FormatStringType FSType;
7057   const unsigned FirstDataArg;
7058   const unsigned NumDataArgs;
7059   const char *Beg; // Start of format string.
7060   const bool HasVAListArg;
7061   ArrayRef<const Expr *> Args;
7062   unsigned FormatIdx;
7063   llvm::SmallBitVector CoveredArgs;
7064   bool usesPositionalArgs = false;
7065   bool atFirstArg = true;
7066   bool inFunctionCall;
7067   Sema::VariadicCallType CallType;
7068   llvm::SmallBitVector &CheckedVarArgs;
7069   UncoveredArgHandler &UncoveredArg;
7070 
7071 public:
7072   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
7073                      const Expr *origFormatExpr,
7074                      const Sema::FormatStringType type, unsigned firstDataArg,
7075                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
7076                      ArrayRef<const Expr *> Args, unsigned formatIdx,
7077                      bool inFunctionCall, Sema::VariadicCallType callType,
7078                      llvm::SmallBitVector &CheckedVarArgs,
7079                      UncoveredArgHandler &UncoveredArg)
7080       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7081         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7082         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
7083         inFunctionCall(inFunctionCall), CallType(callType),
7084         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
7085     CoveredArgs.resize(numDataArgs);
7086     CoveredArgs.reset();
7087   }
7088 
7089   void DoneProcessing();
7090 
7091   void HandleIncompleteSpecifier(const char *startSpecifier,
7092                                  unsigned specifierLen) override;
7093 
7094   void HandleInvalidLengthModifier(
7095                            const analyze_format_string::FormatSpecifier &FS,
7096                            const analyze_format_string::ConversionSpecifier &CS,
7097                            const char *startSpecifier, unsigned specifierLen,
7098                            unsigned DiagID);
7099 
7100   void HandleNonStandardLengthModifier(
7101                     const analyze_format_string::FormatSpecifier &FS,
7102                     const char *startSpecifier, unsigned specifierLen);
7103 
7104   void HandleNonStandardConversionSpecifier(
7105                     const analyze_format_string::ConversionSpecifier &CS,
7106                     const char *startSpecifier, unsigned specifierLen);
7107 
7108   void HandlePosition(const char *startPos, unsigned posLen) override;
7109 
7110   void HandleInvalidPosition(const char *startSpecifier,
7111                              unsigned specifierLen,
7112                              analyze_format_string::PositionContext p) override;
7113 
7114   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
7115 
7116   void HandleNullChar(const char *nullCharacter) override;
7117 
7118   template <typename Range>
7119   static void
7120   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
7121                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
7122                        bool IsStringLocation, Range StringRange,
7123                        ArrayRef<FixItHint> Fixit = None);
7124 
7125 protected:
7126   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
7127                                         const char *startSpec,
7128                                         unsigned specifierLen,
7129                                         const char *csStart, unsigned csLen);
7130 
7131   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7132                                          const char *startSpec,
7133                                          unsigned specifierLen);
7134 
7135   SourceRange getFormatStringRange();
7136   CharSourceRange getSpecifierRange(const char *startSpecifier,
7137                                     unsigned specifierLen);
7138   SourceLocation getLocationOfByte(const char *x);
7139 
7140   const Expr *getDataArg(unsigned i) const;
7141 
7142   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7143                     const analyze_format_string::ConversionSpecifier &CS,
7144                     const char *startSpecifier, unsigned specifierLen,
7145                     unsigned argIndex);
7146 
7147   template <typename Range>
7148   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7149                             bool IsStringLocation, Range StringRange,
7150                             ArrayRef<FixItHint> Fixit = None);
7151 };
7152 
7153 } // namespace
7154 
7155 SourceRange CheckFormatHandler::getFormatStringRange() {
7156   return OrigFormatExpr->getSourceRange();
7157 }
7158 
7159 CharSourceRange CheckFormatHandler::
7160 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
7161   SourceLocation Start = getLocationOfByte(startSpecifier);
7162   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
7163 
7164   // Advance the end SourceLocation by one due to half-open ranges.
7165   End = End.getLocWithOffset(1);
7166 
7167   return CharSourceRange::getCharRange(Start, End);
7168 }
7169 
7170 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
7171   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
7172                                   S.getLangOpts(), S.Context.getTargetInfo());
7173 }
7174 
7175 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7176                                                    unsigned specifierLen){
7177   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
7178                        getLocationOfByte(startSpecifier),
7179                        /*IsStringLocation*/true,
7180                        getSpecifierRange(startSpecifier, specifierLen));
7181 }
7182 
7183 void CheckFormatHandler::HandleInvalidLengthModifier(
7184     const analyze_format_string::FormatSpecifier &FS,
7185     const analyze_format_string::ConversionSpecifier &CS,
7186     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
7187   using namespace analyze_format_string;
7188 
7189   const LengthModifier &LM = FS.getLengthModifier();
7190   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7191 
7192   // See if we know how to fix this length modifier.
7193   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7194   if (FixedLM) {
7195     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7196                          getLocationOfByte(LM.getStart()),
7197                          /*IsStringLocation*/true,
7198                          getSpecifierRange(startSpecifier, specifierLen));
7199 
7200     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7201       << FixedLM->toString()
7202       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7203 
7204   } else {
7205     FixItHint Hint;
7206     if (DiagID == diag::warn_format_nonsensical_length)
7207       Hint = FixItHint::CreateRemoval(LMRange);
7208 
7209     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7210                          getLocationOfByte(LM.getStart()),
7211                          /*IsStringLocation*/true,
7212                          getSpecifierRange(startSpecifier, specifierLen),
7213                          Hint);
7214   }
7215 }
7216 
7217 void CheckFormatHandler::HandleNonStandardLengthModifier(
7218     const analyze_format_string::FormatSpecifier &FS,
7219     const char *startSpecifier, unsigned specifierLen) {
7220   using namespace analyze_format_string;
7221 
7222   const LengthModifier &LM = FS.getLengthModifier();
7223   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7224 
7225   // See if we know how to fix this length modifier.
7226   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7227   if (FixedLM) {
7228     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7229                            << LM.toString() << 0,
7230                          getLocationOfByte(LM.getStart()),
7231                          /*IsStringLocation*/true,
7232                          getSpecifierRange(startSpecifier, specifierLen));
7233 
7234     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7235       << FixedLM->toString()
7236       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7237 
7238   } else {
7239     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7240                            << LM.toString() << 0,
7241                          getLocationOfByte(LM.getStart()),
7242                          /*IsStringLocation*/true,
7243                          getSpecifierRange(startSpecifier, specifierLen));
7244   }
7245 }
7246 
7247 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
7248     const analyze_format_string::ConversionSpecifier &CS,
7249     const char *startSpecifier, unsigned specifierLen) {
7250   using namespace analyze_format_string;
7251 
7252   // See if we know how to fix this conversion specifier.
7253   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
7254   if (FixedCS) {
7255     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7256                           << CS.toString() << /*conversion specifier*/1,
7257                          getLocationOfByte(CS.getStart()),
7258                          /*IsStringLocation*/true,
7259                          getSpecifierRange(startSpecifier, specifierLen));
7260 
7261     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
7262     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
7263       << FixedCS->toString()
7264       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
7265   } else {
7266     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7267                           << CS.toString() << /*conversion specifier*/1,
7268                          getLocationOfByte(CS.getStart()),
7269                          /*IsStringLocation*/true,
7270                          getSpecifierRange(startSpecifier, specifierLen));
7271   }
7272 }
7273 
7274 void CheckFormatHandler::HandlePosition(const char *startPos,
7275                                         unsigned posLen) {
7276   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
7277                                getLocationOfByte(startPos),
7278                                /*IsStringLocation*/true,
7279                                getSpecifierRange(startPos, posLen));
7280 }
7281 
7282 void
7283 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
7284                                      analyze_format_string::PositionContext p) {
7285   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
7286                          << (unsigned) p,
7287                        getLocationOfByte(startPos), /*IsStringLocation*/true,
7288                        getSpecifierRange(startPos, posLen));
7289 }
7290 
7291 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
7292                                             unsigned posLen) {
7293   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
7294                                getLocationOfByte(startPos),
7295                                /*IsStringLocation*/true,
7296                                getSpecifierRange(startPos, posLen));
7297 }
7298 
7299 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
7300   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
7301     // The presence of a null character is likely an error.
7302     EmitFormatDiagnostic(
7303       S.PDiag(diag::warn_printf_format_string_contains_null_char),
7304       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
7305       getFormatStringRange());
7306   }
7307 }
7308 
7309 // Note that this may return NULL if there was an error parsing or building
7310 // one of the argument expressions.
7311 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
7312   return Args[FirstDataArg + i];
7313 }
7314 
7315 void CheckFormatHandler::DoneProcessing() {
7316   // Does the number of data arguments exceed the number of
7317   // format conversions in the format string?
7318   if (!HasVAListArg) {
7319       // Find any arguments that weren't covered.
7320     CoveredArgs.flip();
7321     signed notCoveredArg = CoveredArgs.find_first();
7322     if (notCoveredArg >= 0) {
7323       assert((unsigned)notCoveredArg < NumDataArgs);
7324       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
7325     } else {
7326       UncoveredArg.setAllCovered();
7327     }
7328   }
7329 }
7330 
7331 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7332                                    const Expr *ArgExpr) {
7333   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
7334          "Invalid state");
7335 
7336   if (!ArgExpr)
7337     return;
7338 
7339   SourceLocation Loc = ArgExpr->getBeginLoc();
7340 
7341   if (S.getSourceManager().isInSystemMacro(Loc))
7342     return;
7343 
7344   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
7345   for (auto E : DiagnosticExprs)
7346     PDiag << E->getSourceRange();
7347 
7348   CheckFormatHandler::EmitFormatDiagnostic(
7349                                   S, IsFunctionCall, DiagnosticExprs[0],
7350                                   PDiag, Loc, /*IsStringLocation*/false,
7351                                   DiagnosticExprs[0]->getSourceRange());
7352 }
7353 
7354 bool
7355 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7356                                                      SourceLocation Loc,
7357                                                      const char *startSpec,
7358                                                      unsigned specifierLen,
7359                                                      const char *csStart,
7360                                                      unsigned csLen) {
7361   bool keepGoing = true;
7362   if (argIndex < NumDataArgs) {
7363     // Consider the argument coverered, even though the specifier doesn't
7364     // make sense.
7365     CoveredArgs.set(argIndex);
7366   }
7367   else {
7368     // If argIndex exceeds the number of data arguments we
7369     // don't issue a warning because that is just a cascade of warnings (and
7370     // they may have intended '%%' anyway). We don't want to continue processing
7371     // the format string after this point, however, as we will like just get
7372     // gibberish when trying to match arguments.
7373     keepGoing = false;
7374   }
7375 
7376   StringRef Specifier(csStart, csLen);
7377 
7378   // If the specifier in non-printable, it could be the first byte of a UTF-8
7379   // sequence. In that case, print the UTF-8 code point. If not, print the byte
7380   // hex value.
7381   std::string CodePointStr;
7382   if (!llvm::sys::locale::isPrint(*csStart)) {
7383     llvm::UTF32 CodePoint;
7384     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7385     const llvm::UTF8 *E =
7386         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7387     llvm::ConversionResult Result =
7388         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
7389 
7390     if (Result != llvm::conversionOK) {
7391       unsigned char FirstChar = *csStart;
7392       CodePoint = (llvm::UTF32)FirstChar;
7393     }
7394 
7395     llvm::raw_string_ostream OS(CodePointStr);
7396     if (CodePoint < 256)
7397       OS << "\\x" << llvm::format("%02x", CodePoint);
7398     else if (CodePoint <= 0xFFFF)
7399       OS << "\\u" << llvm::format("%04x", CodePoint);
7400     else
7401       OS << "\\U" << llvm::format("%08x", CodePoint);
7402     OS.flush();
7403     Specifier = CodePointStr;
7404   }
7405 
7406   EmitFormatDiagnostic(
7407       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
7408       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
7409 
7410   return keepGoing;
7411 }
7412 
7413 void
7414 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7415                                                       const char *startSpec,
7416                                                       unsigned specifierLen) {
7417   EmitFormatDiagnostic(
7418     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
7419     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
7420 }
7421 
7422 bool
7423 CheckFormatHandler::CheckNumArgs(
7424   const analyze_format_string::FormatSpecifier &FS,
7425   const analyze_format_string::ConversionSpecifier &CS,
7426   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7427 
7428   if (argIndex >= NumDataArgs) {
7429     PartialDiagnostic PDiag = FS.usesPositionalArg()
7430       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
7431            << (argIndex+1) << NumDataArgs)
7432       : S.PDiag(diag::warn_printf_insufficient_data_args);
7433     EmitFormatDiagnostic(
7434       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
7435       getSpecifierRange(startSpecifier, specifierLen));
7436 
7437     // Since more arguments than conversion tokens are given, by extension
7438     // all arguments are covered, so mark this as so.
7439     UncoveredArg.setAllCovered();
7440     return false;
7441   }
7442   return true;
7443 }
7444 
7445 template<typename Range>
7446 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
7447                                               SourceLocation Loc,
7448                                               bool IsStringLocation,
7449                                               Range StringRange,
7450                                               ArrayRef<FixItHint> FixIt) {
7451   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
7452                        Loc, IsStringLocation, StringRange, FixIt);
7453 }
7454 
7455 /// If the format string is not within the function call, emit a note
7456 /// so that the function call and string are in diagnostic messages.
7457 ///
7458 /// \param InFunctionCall if true, the format string is within the function
7459 /// call and only one diagnostic message will be produced.  Otherwise, an
7460 /// extra note will be emitted pointing to location of the format string.
7461 ///
7462 /// \param ArgumentExpr the expression that is passed as the format string
7463 /// argument in the function call.  Used for getting locations when two
7464 /// diagnostics are emitted.
7465 ///
7466 /// \param PDiag the callee should already have provided any strings for the
7467 /// diagnostic message.  This function only adds locations and fixits
7468 /// to diagnostics.
7469 ///
7470 /// \param Loc primary location for diagnostic.  If two diagnostics are
7471 /// required, one will be at Loc and a new SourceLocation will be created for
7472 /// the other one.
7473 ///
7474 /// \param IsStringLocation if true, Loc points to the format string should be
7475 /// used for the note.  Otherwise, Loc points to the argument list and will
7476 /// be used with PDiag.
7477 ///
7478 /// \param StringRange some or all of the string to highlight.  This is
7479 /// templated so it can accept either a CharSourceRange or a SourceRange.
7480 ///
7481 /// \param FixIt optional fix it hint for the format string.
7482 template <typename Range>
7483 void CheckFormatHandler::EmitFormatDiagnostic(
7484     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
7485     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
7486     Range StringRange, ArrayRef<FixItHint> FixIt) {
7487   if (InFunctionCall) {
7488     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
7489     D << StringRange;
7490     D << FixIt;
7491   } else {
7492     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
7493       << ArgumentExpr->getSourceRange();
7494 
7495     const Sema::SemaDiagnosticBuilder &Note =
7496       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
7497              diag::note_format_string_defined);
7498 
7499     Note << StringRange;
7500     Note << FixIt;
7501   }
7502 }
7503 
7504 //===--- CHECK: Printf format string checking ------------------------------===//
7505 
7506 namespace {
7507 
7508 class CheckPrintfHandler : public CheckFormatHandler {
7509 public:
7510   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7511                      const Expr *origFormatExpr,
7512                      const Sema::FormatStringType type, unsigned firstDataArg,
7513                      unsigned numDataArgs, bool isObjC, const char *beg,
7514                      bool hasVAListArg, ArrayRef<const Expr *> Args,
7515                      unsigned formatIdx, bool inFunctionCall,
7516                      Sema::VariadicCallType CallType,
7517                      llvm::SmallBitVector &CheckedVarArgs,
7518                      UncoveredArgHandler &UncoveredArg)
7519       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7520                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
7521                            inFunctionCall, CallType, CheckedVarArgs,
7522                            UncoveredArg) {}
7523 
7524   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
7525 
7526   /// Returns true if '%@' specifiers are allowed in the format string.
7527   bool allowsObjCArg() const {
7528     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
7529            FSType == Sema::FST_OSTrace;
7530   }
7531 
7532   bool HandleInvalidPrintfConversionSpecifier(
7533                                       const analyze_printf::PrintfSpecifier &FS,
7534                                       const char *startSpecifier,
7535                                       unsigned specifierLen) override;
7536 
7537   void handleInvalidMaskType(StringRef MaskType) override;
7538 
7539   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7540                              const char *startSpecifier,
7541                              unsigned specifierLen) override;
7542   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7543                        const char *StartSpecifier,
7544                        unsigned SpecifierLen,
7545                        const Expr *E);
7546 
7547   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
7548                     const char *startSpecifier, unsigned specifierLen);
7549   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
7550                            const analyze_printf::OptionalAmount &Amt,
7551                            unsigned type,
7552                            const char *startSpecifier, unsigned specifierLen);
7553   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7554                   const analyze_printf::OptionalFlag &flag,
7555                   const char *startSpecifier, unsigned specifierLen);
7556   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
7557                          const analyze_printf::OptionalFlag &ignoredFlag,
7558                          const analyze_printf::OptionalFlag &flag,
7559                          const char *startSpecifier, unsigned specifierLen);
7560   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
7561                            const Expr *E);
7562 
7563   void HandleEmptyObjCModifierFlag(const char *startFlag,
7564                                    unsigned flagLen) override;
7565 
7566   void HandleInvalidObjCModifierFlag(const char *startFlag,
7567                                             unsigned flagLen) override;
7568 
7569   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
7570                                            const char *flagsEnd,
7571                                            const char *conversionPosition)
7572                                              override;
7573 };
7574 
7575 } // namespace
7576 
7577 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
7578                                       const analyze_printf::PrintfSpecifier &FS,
7579                                       const char *startSpecifier,
7580                                       unsigned specifierLen) {
7581   const analyze_printf::PrintfConversionSpecifier &CS =
7582     FS.getConversionSpecifier();
7583 
7584   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7585                                           getLocationOfByte(CS.getStart()),
7586                                           startSpecifier, specifierLen,
7587                                           CS.getStart(), CS.getLength());
7588 }
7589 
7590 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
7591   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
7592 }
7593 
7594 bool CheckPrintfHandler::HandleAmount(
7595                                const analyze_format_string::OptionalAmount &Amt,
7596                                unsigned k, const char *startSpecifier,
7597                                unsigned specifierLen) {
7598   if (Amt.hasDataArgument()) {
7599     if (!HasVAListArg) {
7600       unsigned argIndex = Amt.getArgIndex();
7601       if (argIndex >= NumDataArgs) {
7602         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
7603                                << k,
7604                              getLocationOfByte(Amt.getStart()),
7605                              /*IsStringLocation*/true,
7606                              getSpecifierRange(startSpecifier, specifierLen));
7607         // Don't do any more checking.  We will just emit
7608         // spurious errors.
7609         return false;
7610       }
7611 
7612       // Type check the data argument.  It should be an 'int'.
7613       // Although not in conformance with C99, we also allow the argument to be
7614       // an 'unsigned int' as that is a reasonably safe case.  GCC also
7615       // doesn't emit a warning for that case.
7616       CoveredArgs.set(argIndex);
7617       const Expr *Arg = getDataArg(argIndex);
7618       if (!Arg)
7619         return false;
7620 
7621       QualType T = Arg->getType();
7622 
7623       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
7624       assert(AT.isValid());
7625 
7626       if (!AT.matchesType(S.Context, T)) {
7627         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
7628                                << k << AT.getRepresentativeTypeName(S.Context)
7629                                << T << Arg->getSourceRange(),
7630                              getLocationOfByte(Amt.getStart()),
7631                              /*IsStringLocation*/true,
7632                              getSpecifierRange(startSpecifier, specifierLen));
7633         // Don't do any more checking.  We will just emit
7634         // spurious errors.
7635         return false;
7636       }
7637     }
7638   }
7639   return true;
7640 }
7641 
7642 void CheckPrintfHandler::HandleInvalidAmount(
7643                                       const analyze_printf::PrintfSpecifier &FS,
7644                                       const analyze_printf::OptionalAmount &Amt,
7645                                       unsigned type,
7646                                       const char *startSpecifier,
7647                                       unsigned specifierLen) {
7648   const analyze_printf::PrintfConversionSpecifier &CS =
7649     FS.getConversionSpecifier();
7650 
7651   FixItHint fixit =
7652     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
7653       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
7654                                  Amt.getConstantLength()))
7655       : FixItHint();
7656 
7657   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
7658                          << type << CS.toString(),
7659                        getLocationOfByte(Amt.getStart()),
7660                        /*IsStringLocation*/true,
7661                        getSpecifierRange(startSpecifier, specifierLen),
7662                        fixit);
7663 }
7664 
7665 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7666                                     const analyze_printf::OptionalFlag &flag,
7667                                     const char *startSpecifier,
7668                                     unsigned specifierLen) {
7669   // Warn about pointless flag with a fixit removal.
7670   const analyze_printf::PrintfConversionSpecifier &CS =
7671     FS.getConversionSpecifier();
7672   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
7673                          << flag.toString() << CS.toString(),
7674                        getLocationOfByte(flag.getPosition()),
7675                        /*IsStringLocation*/true,
7676                        getSpecifierRange(startSpecifier, specifierLen),
7677                        FixItHint::CreateRemoval(
7678                          getSpecifierRange(flag.getPosition(), 1)));
7679 }
7680 
7681 void CheckPrintfHandler::HandleIgnoredFlag(
7682                                 const analyze_printf::PrintfSpecifier &FS,
7683                                 const analyze_printf::OptionalFlag &ignoredFlag,
7684                                 const analyze_printf::OptionalFlag &flag,
7685                                 const char *startSpecifier,
7686                                 unsigned specifierLen) {
7687   // Warn about ignored flag with a fixit removal.
7688   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
7689                          << ignoredFlag.toString() << flag.toString(),
7690                        getLocationOfByte(ignoredFlag.getPosition()),
7691                        /*IsStringLocation*/true,
7692                        getSpecifierRange(startSpecifier, specifierLen),
7693                        FixItHint::CreateRemoval(
7694                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
7695 }
7696 
7697 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
7698                                                      unsigned flagLen) {
7699   // Warn about an empty flag.
7700   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
7701                        getLocationOfByte(startFlag),
7702                        /*IsStringLocation*/true,
7703                        getSpecifierRange(startFlag, flagLen));
7704 }
7705 
7706 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
7707                                                        unsigned flagLen) {
7708   // Warn about an invalid flag.
7709   auto Range = getSpecifierRange(startFlag, flagLen);
7710   StringRef flag(startFlag, flagLen);
7711   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
7712                       getLocationOfByte(startFlag),
7713                       /*IsStringLocation*/true,
7714                       Range, FixItHint::CreateRemoval(Range));
7715 }
7716 
7717 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
7718     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
7719     // Warn about using '[...]' without a '@' conversion.
7720     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
7721     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
7722     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
7723                          getLocationOfByte(conversionPosition),
7724                          /*IsStringLocation*/true,
7725                          Range, FixItHint::CreateRemoval(Range));
7726 }
7727 
7728 // Determines if the specified is a C++ class or struct containing
7729 // a member with the specified name and kind (e.g. a CXXMethodDecl named
7730 // "c_str()").
7731 template<typename MemberKind>
7732 static llvm::SmallPtrSet<MemberKind*, 1>
7733 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
7734   const RecordType *RT = Ty->getAs<RecordType>();
7735   llvm::SmallPtrSet<MemberKind*, 1> Results;
7736 
7737   if (!RT)
7738     return Results;
7739   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
7740   if (!RD || !RD->getDefinition())
7741     return Results;
7742 
7743   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
7744                  Sema::LookupMemberName);
7745   R.suppressDiagnostics();
7746 
7747   // We just need to include all members of the right kind turned up by the
7748   // filter, at this point.
7749   if (S.LookupQualifiedName(R, RT->getDecl()))
7750     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7751       NamedDecl *decl = (*I)->getUnderlyingDecl();
7752       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
7753         Results.insert(FK);
7754     }
7755   return Results;
7756 }
7757 
7758 /// Check if we could call '.c_str()' on an object.
7759 ///
7760 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
7761 /// allow the call, or if it would be ambiguous).
7762 bool Sema::hasCStrMethod(const Expr *E) {
7763   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7764 
7765   MethodSet Results =
7766       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
7767   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7768        MI != ME; ++MI)
7769     if ((*MI)->getMinRequiredArguments() == 0)
7770       return true;
7771   return false;
7772 }
7773 
7774 // Check if a (w)string was passed when a (w)char* was needed, and offer a
7775 // better diagnostic if so. AT is assumed to be valid.
7776 // Returns true when a c_str() conversion method is found.
7777 bool CheckPrintfHandler::checkForCStrMembers(
7778     const analyze_printf::ArgType &AT, const Expr *E) {
7779   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7780 
7781   MethodSet Results =
7782       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
7783 
7784   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7785        MI != ME; ++MI) {
7786     const CXXMethodDecl *Method = *MI;
7787     if (Method->getMinRequiredArguments() == 0 &&
7788         AT.matchesType(S.Context, Method->getReturnType())) {
7789       // FIXME: Suggest parens if the expression needs them.
7790       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
7791       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
7792           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
7793       return true;
7794     }
7795   }
7796 
7797   return false;
7798 }
7799 
7800 bool
7801 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
7802                                             &FS,
7803                                           const char *startSpecifier,
7804                                           unsigned specifierLen) {
7805   using namespace analyze_format_string;
7806   using namespace analyze_printf;
7807 
7808   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
7809 
7810   if (FS.consumesDataArgument()) {
7811     if (atFirstArg) {
7812         atFirstArg = false;
7813         usesPositionalArgs = FS.usesPositionalArg();
7814     }
7815     else if (usesPositionalArgs != FS.usesPositionalArg()) {
7816       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
7817                                         startSpecifier, specifierLen);
7818       return false;
7819     }
7820   }
7821 
7822   // First check if the field width, precision, and conversion specifier
7823   // have matching data arguments.
7824   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
7825                     startSpecifier, specifierLen)) {
7826     return false;
7827   }
7828 
7829   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
7830                     startSpecifier, specifierLen)) {
7831     return false;
7832   }
7833 
7834   if (!CS.consumesDataArgument()) {
7835     // FIXME: Technically specifying a precision or field width here
7836     // makes no sense.  Worth issuing a warning at some point.
7837     return true;
7838   }
7839 
7840   // Consume the argument.
7841   unsigned argIndex = FS.getArgIndex();
7842   if (argIndex < NumDataArgs) {
7843     // The check to see if the argIndex is valid will come later.
7844     // We set the bit here because we may exit early from this
7845     // function if we encounter some other error.
7846     CoveredArgs.set(argIndex);
7847   }
7848 
7849   // FreeBSD kernel extensions.
7850   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
7851       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
7852     // We need at least two arguments.
7853     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
7854       return false;
7855 
7856     // Claim the second argument.
7857     CoveredArgs.set(argIndex + 1);
7858 
7859     // Type check the first argument (int for %b, pointer for %D)
7860     const Expr *Ex = getDataArg(argIndex);
7861     const analyze_printf::ArgType &AT =
7862       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
7863         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
7864     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
7865       EmitFormatDiagnostic(
7866           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7867               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
7868               << false << Ex->getSourceRange(),
7869           Ex->getBeginLoc(), /*IsStringLocation*/ false,
7870           getSpecifierRange(startSpecifier, specifierLen));
7871 
7872     // Type check the second argument (char * for both %b and %D)
7873     Ex = getDataArg(argIndex + 1);
7874     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
7875     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
7876       EmitFormatDiagnostic(
7877           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7878               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
7879               << false << Ex->getSourceRange(),
7880           Ex->getBeginLoc(), /*IsStringLocation*/ false,
7881           getSpecifierRange(startSpecifier, specifierLen));
7882 
7883      return true;
7884   }
7885 
7886   // Check for using an Objective-C specific conversion specifier
7887   // in a non-ObjC literal.
7888   if (!allowsObjCArg() && CS.isObjCArg()) {
7889     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7890                                                   specifierLen);
7891   }
7892 
7893   // %P can only be used with os_log.
7894   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
7895     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7896                                                   specifierLen);
7897   }
7898 
7899   // %n is not allowed with os_log.
7900   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
7901     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
7902                          getLocationOfByte(CS.getStart()),
7903                          /*IsStringLocation*/ false,
7904                          getSpecifierRange(startSpecifier, specifierLen));
7905 
7906     return true;
7907   }
7908 
7909   // Only scalars are allowed for os_trace.
7910   if (FSType == Sema::FST_OSTrace &&
7911       (CS.getKind() == ConversionSpecifier::PArg ||
7912        CS.getKind() == ConversionSpecifier::sArg ||
7913        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
7914     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7915                                                   specifierLen);
7916   }
7917 
7918   // Check for use of public/private annotation outside of os_log().
7919   if (FSType != Sema::FST_OSLog) {
7920     if (FS.isPublic().isSet()) {
7921       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7922                                << "public",
7923                            getLocationOfByte(FS.isPublic().getPosition()),
7924                            /*IsStringLocation*/ false,
7925                            getSpecifierRange(startSpecifier, specifierLen));
7926     }
7927     if (FS.isPrivate().isSet()) {
7928       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7929                                << "private",
7930                            getLocationOfByte(FS.isPrivate().getPosition()),
7931                            /*IsStringLocation*/ false,
7932                            getSpecifierRange(startSpecifier, specifierLen));
7933     }
7934   }
7935 
7936   // Check for invalid use of field width
7937   if (!FS.hasValidFieldWidth()) {
7938     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
7939         startSpecifier, specifierLen);
7940   }
7941 
7942   // Check for invalid use of precision
7943   if (!FS.hasValidPrecision()) {
7944     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
7945         startSpecifier, specifierLen);
7946   }
7947 
7948   // Precision is mandatory for %P specifier.
7949   if (CS.getKind() == ConversionSpecifier::PArg &&
7950       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
7951     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
7952                          getLocationOfByte(startSpecifier),
7953                          /*IsStringLocation*/ false,
7954                          getSpecifierRange(startSpecifier, specifierLen));
7955   }
7956 
7957   // Check each flag does not conflict with any other component.
7958   if (!FS.hasValidThousandsGroupingPrefix())
7959     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
7960   if (!FS.hasValidLeadingZeros())
7961     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
7962   if (!FS.hasValidPlusPrefix())
7963     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
7964   if (!FS.hasValidSpacePrefix())
7965     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
7966   if (!FS.hasValidAlternativeForm())
7967     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
7968   if (!FS.hasValidLeftJustified())
7969     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
7970 
7971   // Check that flags are not ignored by another flag
7972   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
7973     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
7974         startSpecifier, specifierLen);
7975   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
7976     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
7977             startSpecifier, specifierLen);
7978 
7979   // Check the length modifier is valid with the given conversion specifier.
7980   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
7981                                  S.getLangOpts()))
7982     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7983                                 diag::warn_format_nonsensical_length);
7984   else if (!FS.hasStandardLengthModifier())
7985     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
7986   else if (!FS.hasStandardLengthConversionCombination())
7987     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7988                                 diag::warn_format_non_standard_conversion_spec);
7989 
7990   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
7991     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
7992 
7993   // The remaining checks depend on the data arguments.
7994   if (HasVAListArg)
7995     return true;
7996 
7997   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
7998     return false;
7999 
8000   const Expr *Arg = getDataArg(argIndex);
8001   if (!Arg)
8002     return true;
8003 
8004   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
8005 }
8006 
8007 static bool requiresParensToAddCast(const Expr *E) {
8008   // FIXME: We should have a general way to reason about operator
8009   // precedence and whether parens are actually needed here.
8010   // Take care of a few common cases where they aren't.
8011   const Expr *Inside = E->IgnoreImpCasts();
8012   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
8013     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
8014 
8015   switch (Inside->getStmtClass()) {
8016   case Stmt::ArraySubscriptExprClass:
8017   case Stmt::CallExprClass:
8018   case Stmt::CharacterLiteralClass:
8019   case Stmt::CXXBoolLiteralExprClass:
8020   case Stmt::DeclRefExprClass:
8021   case Stmt::FloatingLiteralClass:
8022   case Stmt::IntegerLiteralClass:
8023   case Stmt::MemberExprClass:
8024   case Stmt::ObjCArrayLiteralClass:
8025   case Stmt::ObjCBoolLiteralExprClass:
8026   case Stmt::ObjCBoxedExprClass:
8027   case Stmt::ObjCDictionaryLiteralClass:
8028   case Stmt::ObjCEncodeExprClass:
8029   case Stmt::ObjCIvarRefExprClass:
8030   case Stmt::ObjCMessageExprClass:
8031   case Stmt::ObjCPropertyRefExprClass:
8032   case Stmt::ObjCStringLiteralClass:
8033   case Stmt::ObjCSubscriptRefExprClass:
8034   case Stmt::ParenExprClass:
8035   case Stmt::StringLiteralClass:
8036   case Stmt::UnaryOperatorClass:
8037     return false;
8038   default:
8039     return true;
8040   }
8041 }
8042 
8043 static std::pair<QualType, StringRef>
8044 shouldNotPrintDirectly(const ASTContext &Context,
8045                        QualType IntendedTy,
8046                        const Expr *E) {
8047   // Use a 'while' to peel off layers of typedefs.
8048   QualType TyTy = IntendedTy;
8049   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
8050     StringRef Name = UserTy->getDecl()->getName();
8051     QualType CastTy = llvm::StringSwitch<QualType>(Name)
8052       .Case("CFIndex", Context.getNSIntegerType())
8053       .Case("NSInteger", Context.getNSIntegerType())
8054       .Case("NSUInteger", Context.getNSUIntegerType())
8055       .Case("SInt32", Context.IntTy)
8056       .Case("UInt32", Context.UnsignedIntTy)
8057       .Default(QualType());
8058 
8059     if (!CastTy.isNull())
8060       return std::make_pair(CastTy, Name);
8061 
8062     TyTy = UserTy->desugar();
8063   }
8064 
8065   // Strip parens if necessary.
8066   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
8067     return shouldNotPrintDirectly(Context,
8068                                   PE->getSubExpr()->getType(),
8069                                   PE->getSubExpr());
8070 
8071   // If this is a conditional expression, then its result type is constructed
8072   // via usual arithmetic conversions and thus there might be no necessary
8073   // typedef sugar there.  Recurse to operands to check for NSInteger &
8074   // Co. usage condition.
8075   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8076     QualType TrueTy, FalseTy;
8077     StringRef TrueName, FalseName;
8078 
8079     std::tie(TrueTy, TrueName) =
8080       shouldNotPrintDirectly(Context,
8081                              CO->getTrueExpr()->getType(),
8082                              CO->getTrueExpr());
8083     std::tie(FalseTy, FalseName) =
8084       shouldNotPrintDirectly(Context,
8085                              CO->getFalseExpr()->getType(),
8086                              CO->getFalseExpr());
8087 
8088     if (TrueTy == FalseTy)
8089       return std::make_pair(TrueTy, TrueName);
8090     else if (TrueTy.isNull())
8091       return std::make_pair(FalseTy, FalseName);
8092     else if (FalseTy.isNull())
8093       return std::make_pair(TrueTy, TrueName);
8094   }
8095 
8096   return std::make_pair(QualType(), StringRef());
8097 }
8098 
8099 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
8100 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
8101 /// type do not count.
8102 static bool
8103 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
8104   QualType From = ICE->getSubExpr()->getType();
8105   QualType To = ICE->getType();
8106   // It's an integer promotion if the destination type is the promoted
8107   // source type.
8108   if (ICE->getCastKind() == CK_IntegralCast &&
8109       From->isPromotableIntegerType() &&
8110       S.Context.getPromotedIntegerType(From) == To)
8111     return true;
8112   // Look through vector types, since we do default argument promotion for
8113   // those in OpenCL.
8114   if (const auto *VecTy = From->getAs<ExtVectorType>())
8115     From = VecTy->getElementType();
8116   if (const auto *VecTy = To->getAs<ExtVectorType>())
8117     To = VecTy->getElementType();
8118   // It's a floating promotion if the source type is a lower rank.
8119   return ICE->getCastKind() == CK_FloatingCast &&
8120          S.Context.getFloatingTypeOrder(From, To) < 0;
8121 }
8122 
8123 bool
8124 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8125                                     const char *StartSpecifier,
8126                                     unsigned SpecifierLen,
8127                                     const Expr *E) {
8128   using namespace analyze_format_string;
8129   using namespace analyze_printf;
8130 
8131   // Now type check the data expression that matches the
8132   // format specifier.
8133   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
8134   if (!AT.isValid())
8135     return true;
8136 
8137   QualType ExprTy = E->getType();
8138   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
8139     ExprTy = TET->getUnderlyingExpr()->getType();
8140   }
8141 
8142   // Diagnose attempts to print a boolean value as a character. Unlike other
8143   // -Wformat diagnostics, this is fine from a type perspective, but it still
8144   // doesn't make sense.
8145   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
8146       E->isKnownToHaveBooleanValue()) {
8147     const CharSourceRange &CSR =
8148         getSpecifierRange(StartSpecifier, SpecifierLen);
8149     SmallString<4> FSString;
8150     llvm::raw_svector_ostream os(FSString);
8151     FS.toString(os);
8152     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
8153                              << FSString,
8154                          E->getExprLoc(), false, CSR);
8155     return true;
8156   }
8157 
8158   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
8159   if (Match == analyze_printf::ArgType::Match)
8160     return true;
8161 
8162   // Look through argument promotions for our error message's reported type.
8163   // This includes the integral and floating promotions, but excludes array
8164   // and function pointer decay (seeing that an argument intended to be a
8165   // string has type 'char [6]' is probably more confusing than 'char *') and
8166   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
8167   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8168     if (isArithmeticArgumentPromotion(S, ICE)) {
8169       E = ICE->getSubExpr();
8170       ExprTy = E->getType();
8171 
8172       // Check if we didn't match because of an implicit cast from a 'char'
8173       // or 'short' to an 'int'.  This is done because printf is a varargs
8174       // function.
8175       if (ICE->getType() == S.Context.IntTy ||
8176           ICE->getType() == S.Context.UnsignedIntTy) {
8177         // All further checking is done on the subexpression
8178         const analyze_printf::ArgType::MatchKind ImplicitMatch =
8179             AT.matchesType(S.Context, ExprTy);
8180         if (ImplicitMatch == analyze_printf::ArgType::Match)
8181           return true;
8182         if (ImplicitMatch == ArgType::NoMatchPedantic ||
8183             ImplicitMatch == ArgType::NoMatchTypeConfusion)
8184           Match = ImplicitMatch;
8185       }
8186     }
8187   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
8188     // Special case for 'a', which has type 'int' in C.
8189     // Note, however, that we do /not/ want to treat multibyte constants like
8190     // 'MooV' as characters! This form is deprecated but still exists.
8191     if (ExprTy == S.Context.IntTy)
8192       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
8193         ExprTy = S.Context.CharTy;
8194   }
8195 
8196   // Look through enums to their underlying type.
8197   bool IsEnum = false;
8198   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
8199     ExprTy = EnumTy->getDecl()->getIntegerType();
8200     IsEnum = true;
8201   }
8202 
8203   // %C in an Objective-C context prints a unichar, not a wchar_t.
8204   // If the argument is an integer of some kind, believe the %C and suggest
8205   // a cast instead of changing the conversion specifier.
8206   QualType IntendedTy = ExprTy;
8207   if (isObjCContext() &&
8208       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
8209     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
8210         !ExprTy->isCharType()) {
8211       // 'unichar' is defined as a typedef of unsigned short, but we should
8212       // prefer using the typedef if it is visible.
8213       IntendedTy = S.Context.UnsignedShortTy;
8214 
8215       // While we are here, check if the value is an IntegerLiteral that happens
8216       // to be within the valid range.
8217       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
8218         const llvm::APInt &V = IL->getValue();
8219         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
8220           return true;
8221       }
8222 
8223       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
8224                           Sema::LookupOrdinaryName);
8225       if (S.LookupName(Result, S.getCurScope())) {
8226         NamedDecl *ND = Result.getFoundDecl();
8227         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
8228           if (TD->getUnderlyingType() == IntendedTy)
8229             IntendedTy = S.Context.getTypedefType(TD);
8230       }
8231     }
8232   }
8233 
8234   // Special-case some of Darwin's platform-independence types by suggesting
8235   // casts to primitive types that are known to be large enough.
8236   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
8237   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
8238     QualType CastTy;
8239     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
8240     if (!CastTy.isNull()) {
8241       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
8242       // (long in ASTContext). Only complain to pedants.
8243       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
8244           (AT.isSizeT() || AT.isPtrdiffT()) &&
8245           AT.matchesType(S.Context, CastTy))
8246         Match = ArgType::NoMatchPedantic;
8247       IntendedTy = CastTy;
8248       ShouldNotPrintDirectly = true;
8249     }
8250   }
8251 
8252   // We may be able to offer a FixItHint if it is a supported type.
8253   PrintfSpecifier fixedFS = FS;
8254   bool Success =
8255       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
8256 
8257   if (Success) {
8258     // Get the fix string from the fixed format specifier
8259     SmallString<16> buf;
8260     llvm::raw_svector_ostream os(buf);
8261     fixedFS.toString(os);
8262 
8263     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
8264 
8265     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
8266       unsigned Diag;
8267       switch (Match) {
8268       case ArgType::Match: llvm_unreachable("expected non-matching");
8269       case ArgType::NoMatchPedantic:
8270         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8271         break;
8272       case ArgType::NoMatchTypeConfusion:
8273         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8274         break;
8275       case ArgType::NoMatch:
8276         Diag = diag::warn_format_conversion_argument_type_mismatch;
8277         break;
8278       }
8279 
8280       // In this case, the specifier is wrong and should be changed to match
8281       // the argument.
8282       EmitFormatDiagnostic(S.PDiag(Diag)
8283                                << AT.getRepresentativeTypeName(S.Context)
8284                                << IntendedTy << IsEnum << E->getSourceRange(),
8285                            E->getBeginLoc(),
8286                            /*IsStringLocation*/ false, SpecRange,
8287                            FixItHint::CreateReplacement(SpecRange, os.str()));
8288     } else {
8289       // The canonical type for formatting this value is different from the
8290       // actual type of the expression. (This occurs, for example, with Darwin's
8291       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
8292       // should be printed as 'long' for 64-bit compatibility.)
8293       // Rather than emitting a normal format/argument mismatch, we want to
8294       // add a cast to the recommended type (and correct the format string
8295       // if necessary).
8296       SmallString<16> CastBuf;
8297       llvm::raw_svector_ostream CastFix(CastBuf);
8298       CastFix << "(";
8299       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
8300       CastFix << ")";
8301 
8302       SmallVector<FixItHint,4> Hints;
8303       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
8304         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
8305 
8306       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
8307         // If there's already a cast present, just replace it.
8308         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
8309         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
8310 
8311       } else if (!requiresParensToAddCast(E)) {
8312         // If the expression has high enough precedence,
8313         // just write the C-style cast.
8314         Hints.push_back(
8315             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8316       } else {
8317         // Otherwise, add parens around the expression as well as the cast.
8318         CastFix << "(";
8319         Hints.push_back(
8320             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8321 
8322         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
8323         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
8324       }
8325 
8326       if (ShouldNotPrintDirectly) {
8327         // The expression has a type that should not be printed directly.
8328         // We extract the name from the typedef because we don't want to show
8329         // the underlying type in the diagnostic.
8330         StringRef Name;
8331         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
8332           Name = TypedefTy->getDecl()->getName();
8333         else
8334           Name = CastTyName;
8335         unsigned Diag = Match == ArgType::NoMatchPedantic
8336                             ? diag::warn_format_argument_needs_cast_pedantic
8337                             : diag::warn_format_argument_needs_cast;
8338         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
8339                                            << E->getSourceRange(),
8340                              E->getBeginLoc(), /*IsStringLocation=*/false,
8341                              SpecRange, Hints);
8342       } else {
8343         // In this case, the expression could be printed using a different
8344         // specifier, but we've decided that the specifier is probably correct
8345         // and we should cast instead. Just use the normal warning message.
8346         EmitFormatDiagnostic(
8347             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8348                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
8349                 << E->getSourceRange(),
8350             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
8351       }
8352     }
8353   } else {
8354     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
8355                                                    SpecifierLen);
8356     // Since the warning for passing non-POD types to variadic functions
8357     // was deferred until now, we emit a warning for non-POD
8358     // arguments here.
8359     switch (S.isValidVarArgType(ExprTy)) {
8360     case Sema::VAK_Valid:
8361     case Sema::VAK_ValidInCXX11: {
8362       unsigned Diag;
8363       switch (Match) {
8364       case ArgType::Match: llvm_unreachable("expected non-matching");
8365       case ArgType::NoMatchPedantic:
8366         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8367         break;
8368       case ArgType::NoMatchTypeConfusion:
8369         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8370         break;
8371       case ArgType::NoMatch:
8372         Diag = diag::warn_format_conversion_argument_type_mismatch;
8373         break;
8374       }
8375 
8376       EmitFormatDiagnostic(
8377           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
8378                         << IsEnum << CSR << E->getSourceRange(),
8379           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8380       break;
8381     }
8382     case Sema::VAK_Undefined:
8383     case Sema::VAK_MSVCUndefined:
8384       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
8385                                << S.getLangOpts().CPlusPlus11 << ExprTy
8386                                << CallType
8387                                << AT.getRepresentativeTypeName(S.Context) << CSR
8388                                << E->getSourceRange(),
8389                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8390       checkForCStrMembers(AT, E);
8391       break;
8392 
8393     case Sema::VAK_Invalid:
8394       if (ExprTy->isObjCObjectType())
8395         EmitFormatDiagnostic(
8396             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
8397                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
8398                 << AT.getRepresentativeTypeName(S.Context) << CSR
8399                 << E->getSourceRange(),
8400             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8401       else
8402         // FIXME: If this is an initializer list, suggest removing the braces
8403         // or inserting a cast to the target type.
8404         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
8405             << isa<InitListExpr>(E) << ExprTy << CallType
8406             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
8407       break;
8408     }
8409 
8410     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
8411            "format string specifier index out of range");
8412     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
8413   }
8414 
8415   return true;
8416 }
8417 
8418 //===--- CHECK: Scanf format string checking ------------------------------===//
8419 
8420 namespace {
8421 
8422 class CheckScanfHandler : public CheckFormatHandler {
8423 public:
8424   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
8425                     const Expr *origFormatExpr, Sema::FormatStringType type,
8426                     unsigned firstDataArg, unsigned numDataArgs,
8427                     const char *beg, bool hasVAListArg,
8428                     ArrayRef<const Expr *> Args, unsigned formatIdx,
8429                     bool inFunctionCall, Sema::VariadicCallType CallType,
8430                     llvm::SmallBitVector &CheckedVarArgs,
8431                     UncoveredArgHandler &UncoveredArg)
8432       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8433                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8434                            inFunctionCall, CallType, CheckedVarArgs,
8435                            UncoveredArg) {}
8436 
8437   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
8438                             const char *startSpecifier,
8439                             unsigned specifierLen) override;
8440 
8441   bool HandleInvalidScanfConversionSpecifier(
8442           const analyze_scanf::ScanfSpecifier &FS,
8443           const char *startSpecifier,
8444           unsigned specifierLen) override;
8445 
8446   void HandleIncompleteScanList(const char *start, const char *end) override;
8447 };
8448 
8449 } // namespace
8450 
8451 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
8452                                                  const char *end) {
8453   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
8454                        getLocationOfByte(end), /*IsStringLocation*/true,
8455                        getSpecifierRange(start, end - start));
8456 }
8457 
8458 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
8459                                         const analyze_scanf::ScanfSpecifier &FS,
8460                                         const char *startSpecifier,
8461                                         unsigned specifierLen) {
8462   const analyze_scanf::ScanfConversionSpecifier &CS =
8463     FS.getConversionSpecifier();
8464 
8465   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8466                                           getLocationOfByte(CS.getStart()),
8467                                           startSpecifier, specifierLen,
8468                                           CS.getStart(), CS.getLength());
8469 }
8470 
8471 bool CheckScanfHandler::HandleScanfSpecifier(
8472                                        const analyze_scanf::ScanfSpecifier &FS,
8473                                        const char *startSpecifier,
8474                                        unsigned specifierLen) {
8475   using namespace analyze_scanf;
8476   using namespace analyze_format_string;
8477 
8478   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
8479 
8480   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
8481   // be used to decide if we are using positional arguments consistently.
8482   if (FS.consumesDataArgument()) {
8483     if (atFirstArg) {
8484       atFirstArg = false;
8485       usesPositionalArgs = FS.usesPositionalArg();
8486     }
8487     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8488       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8489                                         startSpecifier, specifierLen);
8490       return false;
8491     }
8492   }
8493 
8494   // Check if the field with is non-zero.
8495   const OptionalAmount &Amt = FS.getFieldWidth();
8496   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
8497     if (Amt.getConstantAmount() == 0) {
8498       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
8499                                                    Amt.getConstantLength());
8500       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
8501                            getLocationOfByte(Amt.getStart()),
8502                            /*IsStringLocation*/true, R,
8503                            FixItHint::CreateRemoval(R));
8504     }
8505   }
8506 
8507   if (!FS.consumesDataArgument()) {
8508     // FIXME: Technically specifying a precision or field width here
8509     // makes no sense.  Worth issuing a warning at some point.
8510     return true;
8511   }
8512 
8513   // Consume the argument.
8514   unsigned argIndex = FS.getArgIndex();
8515   if (argIndex < NumDataArgs) {
8516       // The check to see if the argIndex is valid will come later.
8517       // We set the bit here because we may exit early from this
8518       // function if we encounter some other error.
8519     CoveredArgs.set(argIndex);
8520   }
8521 
8522   // Check the length modifier is valid with the given conversion specifier.
8523   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8524                                  S.getLangOpts()))
8525     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8526                                 diag::warn_format_nonsensical_length);
8527   else if (!FS.hasStandardLengthModifier())
8528     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8529   else if (!FS.hasStandardLengthConversionCombination())
8530     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8531                                 diag::warn_format_non_standard_conversion_spec);
8532 
8533   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8534     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8535 
8536   // The remaining checks depend on the data arguments.
8537   if (HasVAListArg)
8538     return true;
8539 
8540   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8541     return false;
8542 
8543   // Check that the argument type matches the format specifier.
8544   const Expr *Ex = getDataArg(argIndex);
8545   if (!Ex)
8546     return true;
8547 
8548   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
8549 
8550   if (!AT.isValid()) {
8551     return true;
8552   }
8553 
8554   analyze_format_string::ArgType::MatchKind Match =
8555       AT.matchesType(S.Context, Ex->getType());
8556   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
8557   if (Match == analyze_format_string::ArgType::Match)
8558     return true;
8559 
8560   ScanfSpecifier fixedFS = FS;
8561   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
8562                                  S.getLangOpts(), S.Context);
8563 
8564   unsigned Diag =
8565       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8566                : diag::warn_format_conversion_argument_type_mismatch;
8567 
8568   if (Success) {
8569     // Get the fix string from the fixed format specifier.
8570     SmallString<128> buf;
8571     llvm::raw_svector_ostream os(buf);
8572     fixedFS.toString(os);
8573 
8574     EmitFormatDiagnostic(
8575         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
8576                       << Ex->getType() << false << Ex->getSourceRange(),
8577         Ex->getBeginLoc(),
8578         /*IsStringLocation*/ false,
8579         getSpecifierRange(startSpecifier, specifierLen),
8580         FixItHint::CreateReplacement(
8581             getSpecifierRange(startSpecifier, specifierLen), os.str()));
8582   } else {
8583     EmitFormatDiagnostic(S.PDiag(Diag)
8584                              << AT.getRepresentativeTypeName(S.Context)
8585                              << Ex->getType() << false << Ex->getSourceRange(),
8586                          Ex->getBeginLoc(),
8587                          /*IsStringLocation*/ false,
8588                          getSpecifierRange(startSpecifier, specifierLen));
8589   }
8590 
8591   return true;
8592 }
8593 
8594 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
8595                               const Expr *OrigFormatExpr,
8596                               ArrayRef<const Expr *> Args,
8597                               bool HasVAListArg, unsigned format_idx,
8598                               unsigned firstDataArg,
8599                               Sema::FormatStringType Type,
8600                               bool inFunctionCall,
8601                               Sema::VariadicCallType CallType,
8602                               llvm::SmallBitVector &CheckedVarArgs,
8603                               UncoveredArgHandler &UncoveredArg,
8604                               bool IgnoreStringsWithoutSpecifiers) {
8605   // CHECK: is the format string a wide literal?
8606   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
8607     CheckFormatHandler::EmitFormatDiagnostic(
8608         S, inFunctionCall, Args[format_idx],
8609         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
8610         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8611     return;
8612   }
8613 
8614   // Str - The format string.  NOTE: this is NOT null-terminated!
8615   StringRef StrRef = FExpr->getString();
8616   const char *Str = StrRef.data();
8617   // Account for cases where the string literal is truncated in a declaration.
8618   const ConstantArrayType *T =
8619     S.Context.getAsConstantArrayType(FExpr->getType());
8620   assert(T && "String literal not of constant array type!");
8621   size_t TypeSize = T->getSize().getZExtValue();
8622   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8623   const unsigned numDataArgs = Args.size() - firstDataArg;
8624 
8625   if (IgnoreStringsWithoutSpecifiers &&
8626       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
8627           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
8628     return;
8629 
8630   // Emit a warning if the string literal is truncated and does not contain an
8631   // embedded null character.
8632   if (TypeSize <= StrRef.size() &&
8633       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
8634     CheckFormatHandler::EmitFormatDiagnostic(
8635         S, inFunctionCall, Args[format_idx],
8636         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
8637         FExpr->getBeginLoc(),
8638         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
8639     return;
8640   }
8641 
8642   // CHECK: empty format string?
8643   if (StrLen == 0 && numDataArgs > 0) {
8644     CheckFormatHandler::EmitFormatDiagnostic(
8645         S, inFunctionCall, Args[format_idx],
8646         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
8647         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8648     return;
8649   }
8650 
8651   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
8652       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
8653       Type == Sema::FST_OSTrace) {
8654     CheckPrintfHandler H(
8655         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
8656         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
8657         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
8658         CheckedVarArgs, UncoveredArg);
8659 
8660     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
8661                                                   S.getLangOpts(),
8662                                                   S.Context.getTargetInfo(),
8663                                             Type == Sema::FST_FreeBSDKPrintf))
8664       H.DoneProcessing();
8665   } else if (Type == Sema::FST_Scanf) {
8666     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
8667                         numDataArgs, Str, HasVAListArg, Args, format_idx,
8668                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
8669 
8670     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
8671                                                  S.getLangOpts(),
8672                                                  S.Context.getTargetInfo()))
8673       H.DoneProcessing();
8674   } // TODO: handle other formats
8675 }
8676 
8677 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
8678   // Str - The format string.  NOTE: this is NOT null-terminated!
8679   StringRef StrRef = FExpr->getString();
8680   const char *Str = StrRef.data();
8681   // Account for cases where the string literal is truncated in a declaration.
8682   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
8683   assert(T && "String literal not of constant array type!");
8684   size_t TypeSize = T->getSize().getZExtValue();
8685   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8686   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
8687                                                          getLangOpts(),
8688                                                          Context.getTargetInfo());
8689 }
8690 
8691 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
8692 
8693 // Returns the related absolute value function that is larger, of 0 if one
8694 // does not exist.
8695 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
8696   switch (AbsFunction) {
8697   default:
8698     return 0;
8699 
8700   case Builtin::BI__builtin_abs:
8701     return Builtin::BI__builtin_labs;
8702   case Builtin::BI__builtin_labs:
8703     return Builtin::BI__builtin_llabs;
8704   case Builtin::BI__builtin_llabs:
8705     return 0;
8706 
8707   case Builtin::BI__builtin_fabsf:
8708     return Builtin::BI__builtin_fabs;
8709   case Builtin::BI__builtin_fabs:
8710     return Builtin::BI__builtin_fabsl;
8711   case Builtin::BI__builtin_fabsl:
8712     return 0;
8713 
8714   case Builtin::BI__builtin_cabsf:
8715     return Builtin::BI__builtin_cabs;
8716   case Builtin::BI__builtin_cabs:
8717     return Builtin::BI__builtin_cabsl;
8718   case Builtin::BI__builtin_cabsl:
8719     return 0;
8720 
8721   case Builtin::BIabs:
8722     return Builtin::BIlabs;
8723   case Builtin::BIlabs:
8724     return Builtin::BIllabs;
8725   case Builtin::BIllabs:
8726     return 0;
8727 
8728   case Builtin::BIfabsf:
8729     return Builtin::BIfabs;
8730   case Builtin::BIfabs:
8731     return Builtin::BIfabsl;
8732   case Builtin::BIfabsl:
8733     return 0;
8734 
8735   case Builtin::BIcabsf:
8736    return Builtin::BIcabs;
8737   case Builtin::BIcabs:
8738     return Builtin::BIcabsl;
8739   case Builtin::BIcabsl:
8740     return 0;
8741   }
8742 }
8743 
8744 // Returns the argument type of the absolute value function.
8745 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
8746                                              unsigned AbsType) {
8747   if (AbsType == 0)
8748     return QualType();
8749 
8750   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
8751   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
8752   if (Error != ASTContext::GE_None)
8753     return QualType();
8754 
8755   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
8756   if (!FT)
8757     return QualType();
8758 
8759   if (FT->getNumParams() != 1)
8760     return QualType();
8761 
8762   return FT->getParamType(0);
8763 }
8764 
8765 // Returns the best absolute value function, or zero, based on type and
8766 // current absolute value function.
8767 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
8768                                    unsigned AbsFunctionKind) {
8769   unsigned BestKind = 0;
8770   uint64_t ArgSize = Context.getTypeSize(ArgType);
8771   for (unsigned Kind = AbsFunctionKind; Kind != 0;
8772        Kind = getLargerAbsoluteValueFunction(Kind)) {
8773     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
8774     if (Context.getTypeSize(ParamType) >= ArgSize) {
8775       if (BestKind == 0)
8776         BestKind = Kind;
8777       else if (Context.hasSameType(ParamType, ArgType)) {
8778         BestKind = Kind;
8779         break;
8780       }
8781     }
8782   }
8783   return BestKind;
8784 }
8785 
8786 enum AbsoluteValueKind {
8787   AVK_Integer,
8788   AVK_Floating,
8789   AVK_Complex
8790 };
8791 
8792 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
8793   if (T->isIntegralOrEnumerationType())
8794     return AVK_Integer;
8795   if (T->isRealFloatingType())
8796     return AVK_Floating;
8797   if (T->isAnyComplexType())
8798     return AVK_Complex;
8799 
8800   llvm_unreachable("Type not integer, floating, or complex");
8801 }
8802 
8803 // Changes the absolute value function to a different type.  Preserves whether
8804 // the function is a builtin.
8805 static unsigned changeAbsFunction(unsigned AbsKind,
8806                                   AbsoluteValueKind ValueKind) {
8807   switch (ValueKind) {
8808   case AVK_Integer:
8809     switch (AbsKind) {
8810     default:
8811       return 0;
8812     case Builtin::BI__builtin_fabsf:
8813     case Builtin::BI__builtin_fabs:
8814     case Builtin::BI__builtin_fabsl:
8815     case Builtin::BI__builtin_cabsf:
8816     case Builtin::BI__builtin_cabs:
8817     case Builtin::BI__builtin_cabsl:
8818       return Builtin::BI__builtin_abs;
8819     case Builtin::BIfabsf:
8820     case Builtin::BIfabs:
8821     case Builtin::BIfabsl:
8822     case Builtin::BIcabsf:
8823     case Builtin::BIcabs:
8824     case Builtin::BIcabsl:
8825       return Builtin::BIabs;
8826     }
8827   case AVK_Floating:
8828     switch (AbsKind) {
8829     default:
8830       return 0;
8831     case Builtin::BI__builtin_abs:
8832     case Builtin::BI__builtin_labs:
8833     case Builtin::BI__builtin_llabs:
8834     case Builtin::BI__builtin_cabsf:
8835     case Builtin::BI__builtin_cabs:
8836     case Builtin::BI__builtin_cabsl:
8837       return Builtin::BI__builtin_fabsf;
8838     case Builtin::BIabs:
8839     case Builtin::BIlabs:
8840     case Builtin::BIllabs:
8841     case Builtin::BIcabsf:
8842     case Builtin::BIcabs:
8843     case Builtin::BIcabsl:
8844       return Builtin::BIfabsf;
8845     }
8846   case AVK_Complex:
8847     switch (AbsKind) {
8848     default:
8849       return 0;
8850     case Builtin::BI__builtin_abs:
8851     case Builtin::BI__builtin_labs:
8852     case Builtin::BI__builtin_llabs:
8853     case Builtin::BI__builtin_fabsf:
8854     case Builtin::BI__builtin_fabs:
8855     case Builtin::BI__builtin_fabsl:
8856       return Builtin::BI__builtin_cabsf;
8857     case Builtin::BIabs:
8858     case Builtin::BIlabs:
8859     case Builtin::BIllabs:
8860     case Builtin::BIfabsf:
8861     case Builtin::BIfabs:
8862     case Builtin::BIfabsl:
8863       return Builtin::BIcabsf;
8864     }
8865   }
8866   llvm_unreachable("Unable to convert function");
8867 }
8868 
8869 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
8870   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
8871   if (!FnInfo)
8872     return 0;
8873 
8874   switch (FDecl->getBuiltinID()) {
8875   default:
8876     return 0;
8877   case Builtin::BI__builtin_abs:
8878   case Builtin::BI__builtin_fabs:
8879   case Builtin::BI__builtin_fabsf:
8880   case Builtin::BI__builtin_fabsl:
8881   case Builtin::BI__builtin_labs:
8882   case Builtin::BI__builtin_llabs:
8883   case Builtin::BI__builtin_cabs:
8884   case Builtin::BI__builtin_cabsf:
8885   case Builtin::BI__builtin_cabsl:
8886   case Builtin::BIabs:
8887   case Builtin::BIlabs:
8888   case Builtin::BIllabs:
8889   case Builtin::BIfabs:
8890   case Builtin::BIfabsf:
8891   case Builtin::BIfabsl:
8892   case Builtin::BIcabs:
8893   case Builtin::BIcabsf:
8894   case Builtin::BIcabsl:
8895     return FDecl->getBuiltinID();
8896   }
8897   llvm_unreachable("Unknown Builtin type");
8898 }
8899 
8900 // If the replacement is valid, emit a note with replacement function.
8901 // Additionally, suggest including the proper header if not already included.
8902 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
8903                             unsigned AbsKind, QualType ArgType) {
8904   bool EmitHeaderHint = true;
8905   const char *HeaderName = nullptr;
8906   const char *FunctionName = nullptr;
8907   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
8908     FunctionName = "std::abs";
8909     if (ArgType->isIntegralOrEnumerationType()) {
8910       HeaderName = "cstdlib";
8911     } else if (ArgType->isRealFloatingType()) {
8912       HeaderName = "cmath";
8913     } else {
8914       llvm_unreachable("Invalid Type");
8915     }
8916 
8917     // Lookup all std::abs
8918     if (NamespaceDecl *Std = S.getStdNamespace()) {
8919       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
8920       R.suppressDiagnostics();
8921       S.LookupQualifiedName(R, Std);
8922 
8923       for (const auto *I : R) {
8924         const FunctionDecl *FDecl = nullptr;
8925         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
8926           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
8927         } else {
8928           FDecl = dyn_cast<FunctionDecl>(I);
8929         }
8930         if (!FDecl)
8931           continue;
8932 
8933         // Found std::abs(), check that they are the right ones.
8934         if (FDecl->getNumParams() != 1)
8935           continue;
8936 
8937         // Check that the parameter type can handle the argument.
8938         QualType ParamType = FDecl->getParamDecl(0)->getType();
8939         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
8940             S.Context.getTypeSize(ArgType) <=
8941                 S.Context.getTypeSize(ParamType)) {
8942           // Found a function, don't need the header hint.
8943           EmitHeaderHint = false;
8944           break;
8945         }
8946       }
8947     }
8948   } else {
8949     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
8950     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
8951 
8952     if (HeaderName) {
8953       DeclarationName DN(&S.Context.Idents.get(FunctionName));
8954       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
8955       R.suppressDiagnostics();
8956       S.LookupName(R, S.getCurScope());
8957 
8958       if (R.isSingleResult()) {
8959         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
8960         if (FD && FD->getBuiltinID() == AbsKind) {
8961           EmitHeaderHint = false;
8962         } else {
8963           return;
8964         }
8965       } else if (!R.empty()) {
8966         return;
8967       }
8968     }
8969   }
8970 
8971   S.Diag(Loc, diag::note_replace_abs_function)
8972       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
8973 
8974   if (!HeaderName)
8975     return;
8976 
8977   if (!EmitHeaderHint)
8978     return;
8979 
8980   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
8981                                                     << FunctionName;
8982 }
8983 
8984 template <std::size_t StrLen>
8985 static bool IsStdFunction(const FunctionDecl *FDecl,
8986                           const char (&Str)[StrLen]) {
8987   if (!FDecl)
8988     return false;
8989   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
8990     return false;
8991   if (!FDecl->isInStdNamespace())
8992     return false;
8993 
8994   return true;
8995 }
8996 
8997 // Warn when using the wrong abs() function.
8998 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
8999                                       const FunctionDecl *FDecl) {
9000   if (Call->getNumArgs() != 1)
9001     return;
9002 
9003   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
9004   bool IsStdAbs = IsStdFunction(FDecl, "abs");
9005   if (AbsKind == 0 && !IsStdAbs)
9006     return;
9007 
9008   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9009   QualType ParamType = Call->getArg(0)->getType();
9010 
9011   // Unsigned types cannot be negative.  Suggest removing the absolute value
9012   // function call.
9013   if (ArgType->isUnsignedIntegerType()) {
9014     const char *FunctionName =
9015         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
9016     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
9017     Diag(Call->getExprLoc(), diag::note_remove_abs)
9018         << FunctionName
9019         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
9020     return;
9021   }
9022 
9023   // Taking the absolute value of a pointer is very suspicious, they probably
9024   // wanted to index into an array, dereference a pointer, call a function, etc.
9025   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
9026     unsigned DiagType = 0;
9027     if (ArgType->isFunctionType())
9028       DiagType = 1;
9029     else if (ArgType->isArrayType())
9030       DiagType = 2;
9031 
9032     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
9033     return;
9034   }
9035 
9036   // std::abs has overloads which prevent most of the absolute value problems
9037   // from occurring.
9038   if (IsStdAbs)
9039     return;
9040 
9041   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
9042   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
9043 
9044   // The argument and parameter are the same kind.  Check if they are the right
9045   // size.
9046   if (ArgValueKind == ParamValueKind) {
9047     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
9048       return;
9049 
9050     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
9051     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
9052         << FDecl << ArgType << ParamType;
9053 
9054     if (NewAbsKind == 0)
9055       return;
9056 
9057     emitReplacement(*this, Call->getExprLoc(),
9058                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9059     return;
9060   }
9061 
9062   // ArgValueKind != ParamValueKind
9063   // The wrong type of absolute value function was used.  Attempt to find the
9064   // proper one.
9065   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
9066   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
9067   if (NewAbsKind == 0)
9068     return;
9069 
9070   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
9071       << FDecl << ParamValueKind << ArgValueKind;
9072 
9073   emitReplacement(*this, Call->getExprLoc(),
9074                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9075 }
9076 
9077 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
9078 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
9079                                 const FunctionDecl *FDecl) {
9080   if (!Call || !FDecl) return;
9081 
9082   // Ignore template specializations and macros.
9083   if (inTemplateInstantiation()) return;
9084   if (Call->getExprLoc().isMacroID()) return;
9085 
9086   // Only care about the one template argument, two function parameter std::max
9087   if (Call->getNumArgs() != 2) return;
9088   if (!IsStdFunction(FDecl, "max")) return;
9089   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
9090   if (!ArgList) return;
9091   if (ArgList->size() != 1) return;
9092 
9093   // Check that template type argument is unsigned integer.
9094   const auto& TA = ArgList->get(0);
9095   if (TA.getKind() != TemplateArgument::Type) return;
9096   QualType ArgType = TA.getAsType();
9097   if (!ArgType->isUnsignedIntegerType()) return;
9098 
9099   // See if either argument is a literal zero.
9100   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
9101     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
9102     if (!MTE) return false;
9103     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
9104     if (!Num) return false;
9105     if (Num->getValue() != 0) return false;
9106     return true;
9107   };
9108 
9109   const Expr *FirstArg = Call->getArg(0);
9110   const Expr *SecondArg = Call->getArg(1);
9111   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
9112   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
9113 
9114   // Only warn when exactly one argument is zero.
9115   if (IsFirstArgZero == IsSecondArgZero) return;
9116 
9117   SourceRange FirstRange = FirstArg->getSourceRange();
9118   SourceRange SecondRange = SecondArg->getSourceRange();
9119 
9120   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
9121 
9122   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
9123       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
9124 
9125   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
9126   SourceRange RemovalRange;
9127   if (IsFirstArgZero) {
9128     RemovalRange = SourceRange(FirstRange.getBegin(),
9129                                SecondRange.getBegin().getLocWithOffset(-1));
9130   } else {
9131     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
9132                                SecondRange.getEnd());
9133   }
9134 
9135   Diag(Call->getExprLoc(), diag::note_remove_max_call)
9136         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
9137         << FixItHint::CreateRemoval(RemovalRange);
9138 }
9139 
9140 //===--- CHECK: Standard memory functions ---------------------------------===//
9141 
9142 /// Takes the expression passed to the size_t parameter of functions
9143 /// such as memcmp, strncat, etc and warns if it's a comparison.
9144 ///
9145 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
9146 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
9147                                            IdentifierInfo *FnName,
9148                                            SourceLocation FnLoc,
9149                                            SourceLocation RParenLoc) {
9150   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
9151   if (!Size)
9152     return false;
9153 
9154   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
9155   if (!Size->isComparisonOp() && !Size->isLogicalOp())
9156     return false;
9157 
9158   SourceRange SizeRange = Size->getSourceRange();
9159   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
9160       << SizeRange << FnName;
9161   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
9162       << FnName
9163       << FixItHint::CreateInsertion(
9164              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
9165       << FixItHint::CreateRemoval(RParenLoc);
9166   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
9167       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
9168       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
9169                                     ")");
9170 
9171   return true;
9172 }
9173 
9174 /// Determine whether the given type is or contains a dynamic class type
9175 /// (e.g., whether it has a vtable).
9176 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
9177                                                      bool &IsContained) {
9178   // Look through array types while ignoring qualifiers.
9179   const Type *Ty = T->getBaseElementTypeUnsafe();
9180   IsContained = false;
9181 
9182   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
9183   RD = RD ? RD->getDefinition() : nullptr;
9184   if (!RD || RD->isInvalidDecl())
9185     return nullptr;
9186 
9187   if (RD->isDynamicClass())
9188     return RD;
9189 
9190   // Check all the fields.  If any bases were dynamic, the class is dynamic.
9191   // It's impossible for a class to transitively contain itself by value, so
9192   // infinite recursion is impossible.
9193   for (auto *FD : RD->fields()) {
9194     bool SubContained;
9195     if (const CXXRecordDecl *ContainedRD =
9196             getContainedDynamicClass(FD->getType(), SubContained)) {
9197       IsContained = true;
9198       return ContainedRD;
9199     }
9200   }
9201 
9202   return nullptr;
9203 }
9204 
9205 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
9206   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
9207     if (Unary->getKind() == UETT_SizeOf)
9208       return Unary;
9209   return nullptr;
9210 }
9211 
9212 /// If E is a sizeof expression, returns its argument expression,
9213 /// otherwise returns NULL.
9214 static const Expr *getSizeOfExprArg(const Expr *E) {
9215   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9216     if (!SizeOf->isArgumentType())
9217       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
9218   return nullptr;
9219 }
9220 
9221 /// If E is a sizeof expression, returns its argument type.
9222 static QualType getSizeOfArgType(const Expr *E) {
9223   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9224     return SizeOf->getTypeOfArgument();
9225   return QualType();
9226 }
9227 
9228 namespace {
9229 
9230 struct SearchNonTrivialToInitializeField
9231     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
9232   using Super =
9233       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
9234 
9235   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
9236 
9237   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
9238                      SourceLocation SL) {
9239     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9240       asDerived().visitArray(PDIK, AT, SL);
9241       return;
9242     }
9243 
9244     Super::visitWithKind(PDIK, FT, SL);
9245   }
9246 
9247   void visitARCStrong(QualType FT, SourceLocation SL) {
9248     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9249   }
9250   void visitARCWeak(QualType FT, SourceLocation SL) {
9251     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9252   }
9253   void visitStruct(QualType FT, SourceLocation SL) {
9254     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9255       visit(FD->getType(), FD->getLocation());
9256   }
9257   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
9258                   const ArrayType *AT, SourceLocation SL) {
9259     visit(getContext().getBaseElementType(AT), SL);
9260   }
9261   void visitTrivial(QualType FT, SourceLocation SL) {}
9262 
9263   static void diag(QualType RT, const Expr *E, Sema &S) {
9264     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
9265   }
9266 
9267   ASTContext &getContext() { return S.getASTContext(); }
9268 
9269   const Expr *E;
9270   Sema &S;
9271 };
9272 
9273 struct SearchNonTrivialToCopyField
9274     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
9275   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
9276 
9277   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
9278 
9279   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
9280                      SourceLocation SL) {
9281     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9282       asDerived().visitArray(PCK, AT, SL);
9283       return;
9284     }
9285 
9286     Super::visitWithKind(PCK, FT, SL);
9287   }
9288 
9289   void visitARCStrong(QualType FT, SourceLocation SL) {
9290     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9291   }
9292   void visitARCWeak(QualType FT, SourceLocation SL) {
9293     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9294   }
9295   void visitStruct(QualType FT, SourceLocation SL) {
9296     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9297       visit(FD->getType(), FD->getLocation());
9298   }
9299   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
9300                   SourceLocation SL) {
9301     visit(getContext().getBaseElementType(AT), SL);
9302   }
9303   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
9304                 SourceLocation SL) {}
9305   void visitTrivial(QualType FT, SourceLocation SL) {}
9306   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
9307 
9308   static void diag(QualType RT, const Expr *E, Sema &S) {
9309     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
9310   }
9311 
9312   ASTContext &getContext() { return S.getASTContext(); }
9313 
9314   const Expr *E;
9315   Sema &S;
9316 };
9317 
9318 }
9319 
9320 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
9321 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
9322   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
9323 
9324   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
9325     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
9326       return false;
9327 
9328     return doesExprLikelyComputeSize(BO->getLHS()) ||
9329            doesExprLikelyComputeSize(BO->getRHS());
9330   }
9331 
9332   return getAsSizeOfExpr(SizeofExpr) != nullptr;
9333 }
9334 
9335 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
9336 ///
9337 /// \code
9338 ///   #define MACRO 0
9339 ///   foo(MACRO);
9340 ///   foo(0);
9341 /// \endcode
9342 ///
9343 /// This should return true for the first call to foo, but not for the second
9344 /// (regardless of whether foo is a macro or function).
9345 static bool isArgumentExpandedFromMacro(SourceManager &SM,
9346                                         SourceLocation CallLoc,
9347                                         SourceLocation ArgLoc) {
9348   if (!CallLoc.isMacroID())
9349     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
9350 
9351   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
9352          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
9353 }
9354 
9355 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
9356 /// last two arguments transposed.
9357 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
9358   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
9359     return;
9360 
9361   const Expr *SizeArg =
9362     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
9363 
9364   auto isLiteralZero = [](const Expr *E) {
9365     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
9366   };
9367 
9368   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
9369   SourceLocation CallLoc = Call->getRParenLoc();
9370   SourceManager &SM = S.getSourceManager();
9371   if (isLiteralZero(SizeArg) &&
9372       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
9373 
9374     SourceLocation DiagLoc = SizeArg->getExprLoc();
9375 
9376     // Some platforms #define bzero to __builtin_memset. See if this is the
9377     // case, and if so, emit a better diagnostic.
9378     if (BId == Builtin::BIbzero ||
9379         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
9380                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
9381       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
9382       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
9383     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
9384       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
9385       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
9386     }
9387     return;
9388   }
9389 
9390   // If the second argument to a memset is a sizeof expression and the third
9391   // isn't, this is also likely an error. This should catch
9392   // 'memset(buf, sizeof(buf), 0xff)'.
9393   if (BId == Builtin::BImemset &&
9394       doesExprLikelyComputeSize(Call->getArg(1)) &&
9395       !doesExprLikelyComputeSize(Call->getArg(2))) {
9396     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
9397     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
9398     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
9399     return;
9400   }
9401 }
9402 
9403 /// Check for dangerous or invalid arguments to memset().
9404 ///
9405 /// This issues warnings on known problematic, dangerous or unspecified
9406 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
9407 /// function calls.
9408 ///
9409 /// \param Call The call expression to diagnose.
9410 void Sema::CheckMemaccessArguments(const CallExpr *Call,
9411                                    unsigned BId,
9412                                    IdentifierInfo *FnName) {
9413   assert(BId != 0);
9414 
9415   // It is possible to have a non-standard definition of memset.  Validate
9416   // we have enough arguments, and if not, abort further checking.
9417   unsigned ExpectedNumArgs =
9418       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
9419   if (Call->getNumArgs() < ExpectedNumArgs)
9420     return;
9421 
9422   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
9423                       BId == Builtin::BIstrndup ? 1 : 2);
9424   unsigned LenArg =
9425       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
9426   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
9427 
9428   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
9429                                      Call->getBeginLoc(), Call->getRParenLoc()))
9430     return;
9431 
9432   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
9433   CheckMemaccessSize(*this, BId, Call);
9434 
9435   // We have special checking when the length is a sizeof expression.
9436   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
9437   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
9438   llvm::FoldingSetNodeID SizeOfArgID;
9439 
9440   // Although widely used, 'bzero' is not a standard function. Be more strict
9441   // with the argument types before allowing diagnostics and only allow the
9442   // form bzero(ptr, sizeof(...)).
9443   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9444   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
9445     return;
9446 
9447   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
9448     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
9449     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
9450 
9451     QualType DestTy = Dest->getType();
9452     QualType PointeeTy;
9453     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
9454       PointeeTy = DestPtrTy->getPointeeType();
9455 
9456       // Never warn about void type pointers. This can be used to suppress
9457       // false positives.
9458       if (PointeeTy->isVoidType())
9459         continue;
9460 
9461       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
9462       // actually comparing the expressions for equality. Because computing the
9463       // expression IDs can be expensive, we only do this if the diagnostic is
9464       // enabled.
9465       if (SizeOfArg &&
9466           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
9467                            SizeOfArg->getExprLoc())) {
9468         // We only compute IDs for expressions if the warning is enabled, and
9469         // cache the sizeof arg's ID.
9470         if (SizeOfArgID == llvm::FoldingSetNodeID())
9471           SizeOfArg->Profile(SizeOfArgID, Context, true);
9472         llvm::FoldingSetNodeID DestID;
9473         Dest->Profile(DestID, Context, true);
9474         if (DestID == SizeOfArgID) {
9475           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
9476           //       over sizeof(src) as well.
9477           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
9478           StringRef ReadableName = FnName->getName();
9479 
9480           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
9481             if (UnaryOp->getOpcode() == UO_AddrOf)
9482               ActionIdx = 1; // If its an address-of operator, just remove it.
9483           if (!PointeeTy->isIncompleteType() &&
9484               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
9485             ActionIdx = 2; // If the pointee's size is sizeof(char),
9486                            // suggest an explicit length.
9487 
9488           // If the function is defined as a builtin macro, do not show macro
9489           // expansion.
9490           SourceLocation SL = SizeOfArg->getExprLoc();
9491           SourceRange DSR = Dest->getSourceRange();
9492           SourceRange SSR = SizeOfArg->getSourceRange();
9493           SourceManager &SM = getSourceManager();
9494 
9495           if (SM.isMacroArgExpansion(SL)) {
9496             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
9497             SL = SM.getSpellingLoc(SL);
9498             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
9499                              SM.getSpellingLoc(DSR.getEnd()));
9500             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
9501                              SM.getSpellingLoc(SSR.getEnd()));
9502           }
9503 
9504           DiagRuntimeBehavior(SL, SizeOfArg,
9505                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
9506                                 << ReadableName
9507                                 << PointeeTy
9508                                 << DestTy
9509                                 << DSR
9510                                 << SSR);
9511           DiagRuntimeBehavior(SL, SizeOfArg,
9512                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
9513                                 << ActionIdx
9514                                 << SSR);
9515 
9516           break;
9517         }
9518       }
9519 
9520       // Also check for cases where the sizeof argument is the exact same
9521       // type as the memory argument, and where it points to a user-defined
9522       // record type.
9523       if (SizeOfArgTy != QualType()) {
9524         if (PointeeTy->isRecordType() &&
9525             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
9526           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
9527                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
9528                                 << FnName << SizeOfArgTy << ArgIdx
9529                                 << PointeeTy << Dest->getSourceRange()
9530                                 << LenExpr->getSourceRange());
9531           break;
9532         }
9533       }
9534     } else if (DestTy->isArrayType()) {
9535       PointeeTy = DestTy;
9536     }
9537 
9538     if (PointeeTy == QualType())
9539       continue;
9540 
9541     // Always complain about dynamic classes.
9542     bool IsContained;
9543     if (const CXXRecordDecl *ContainedRD =
9544             getContainedDynamicClass(PointeeTy, IsContained)) {
9545 
9546       unsigned OperationType = 0;
9547       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
9548       // "overwritten" if we're warning about the destination for any call
9549       // but memcmp; otherwise a verb appropriate to the call.
9550       if (ArgIdx != 0 || IsCmp) {
9551         if (BId == Builtin::BImemcpy)
9552           OperationType = 1;
9553         else if(BId == Builtin::BImemmove)
9554           OperationType = 2;
9555         else if (IsCmp)
9556           OperationType = 3;
9557       }
9558 
9559       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9560                           PDiag(diag::warn_dyn_class_memaccess)
9561                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
9562                               << IsContained << ContainedRD << OperationType
9563                               << Call->getCallee()->getSourceRange());
9564     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
9565              BId != Builtin::BImemset)
9566       DiagRuntimeBehavior(
9567         Dest->getExprLoc(), Dest,
9568         PDiag(diag::warn_arc_object_memaccess)
9569           << ArgIdx << FnName << PointeeTy
9570           << Call->getCallee()->getSourceRange());
9571     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
9572       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
9573           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
9574         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9575                             PDiag(diag::warn_cstruct_memaccess)
9576                                 << ArgIdx << FnName << PointeeTy << 0);
9577         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
9578       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
9579                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
9580         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9581                             PDiag(diag::warn_cstruct_memaccess)
9582                                 << ArgIdx << FnName << PointeeTy << 1);
9583         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
9584       } else {
9585         continue;
9586       }
9587     } else
9588       continue;
9589 
9590     DiagRuntimeBehavior(
9591       Dest->getExprLoc(), Dest,
9592       PDiag(diag::note_bad_memaccess_silence)
9593         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
9594     break;
9595   }
9596 }
9597 
9598 // A little helper routine: ignore addition and subtraction of integer literals.
9599 // This intentionally does not ignore all integer constant expressions because
9600 // we don't want to remove sizeof().
9601 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
9602   Ex = Ex->IgnoreParenCasts();
9603 
9604   while (true) {
9605     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
9606     if (!BO || !BO->isAdditiveOp())
9607       break;
9608 
9609     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
9610     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
9611 
9612     if (isa<IntegerLiteral>(RHS))
9613       Ex = LHS;
9614     else if (isa<IntegerLiteral>(LHS))
9615       Ex = RHS;
9616     else
9617       break;
9618   }
9619 
9620   return Ex;
9621 }
9622 
9623 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
9624                                                       ASTContext &Context) {
9625   // Only handle constant-sized or VLAs, but not flexible members.
9626   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
9627     // Only issue the FIXIT for arrays of size > 1.
9628     if (CAT->getSize().getSExtValue() <= 1)
9629       return false;
9630   } else if (!Ty->isVariableArrayType()) {
9631     return false;
9632   }
9633   return true;
9634 }
9635 
9636 // Warn if the user has made the 'size' argument to strlcpy or strlcat
9637 // be the size of the source, instead of the destination.
9638 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
9639                                     IdentifierInfo *FnName) {
9640 
9641   // Don't crash if the user has the wrong number of arguments
9642   unsigned NumArgs = Call->getNumArgs();
9643   if ((NumArgs != 3) && (NumArgs != 4))
9644     return;
9645 
9646   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
9647   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
9648   const Expr *CompareWithSrc = nullptr;
9649 
9650   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
9651                                      Call->getBeginLoc(), Call->getRParenLoc()))
9652     return;
9653 
9654   // Look for 'strlcpy(dst, x, sizeof(x))'
9655   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
9656     CompareWithSrc = Ex;
9657   else {
9658     // Look for 'strlcpy(dst, x, strlen(x))'
9659     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
9660       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
9661           SizeCall->getNumArgs() == 1)
9662         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
9663     }
9664   }
9665 
9666   if (!CompareWithSrc)
9667     return;
9668 
9669   // Determine if the argument to sizeof/strlen is equal to the source
9670   // argument.  In principle there's all kinds of things you could do
9671   // here, for instance creating an == expression and evaluating it with
9672   // EvaluateAsBooleanCondition, but this uses a more direct technique:
9673   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
9674   if (!SrcArgDRE)
9675     return;
9676 
9677   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
9678   if (!CompareWithSrcDRE ||
9679       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
9680     return;
9681 
9682   const Expr *OriginalSizeArg = Call->getArg(2);
9683   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
9684       << OriginalSizeArg->getSourceRange() << FnName;
9685 
9686   // Output a FIXIT hint if the destination is an array (rather than a
9687   // pointer to an array).  This could be enhanced to handle some
9688   // pointers if we know the actual size, like if DstArg is 'array+2'
9689   // we could say 'sizeof(array)-2'.
9690   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
9691   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
9692     return;
9693 
9694   SmallString<128> sizeString;
9695   llvm::raw_svector_ostream OS(sizeString);
9696   OS << "sizeof(";
9697   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9698   OS << ")";
9699 
9700   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
9701       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
9702                                       OS.str());
9703 }
9704 
9705 /// Check if two expressions refer to the same declaration.
9706 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
9707   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
9708     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
9709       return D1->getDecl() == D2->getDecl();
9710   return false;
9711 }
9712 
9713 static const Expr *getStrlenExprArg(const Expr *E) {
9714   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9715     const FunctionDecl *FD = CE->getDirectCallee();
9716     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
9717       return nullptr;
9718     return CE->getArg(0)->IgnoreParenCasts();
9719   }
9720   return nullptr;
9721 }
9722 
9723 // Warn on anti-patterns as the 'size' argument to strncat.
9724 // The correct size argument should look like following:
9725 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
9726 void Sema::CheckStrncatArguments(const CallExpr *CE,
9727                                  IdentifierInfo *FnName) {
9728   // Don't crash if the user has the wrong number of arguments.
9729   if (CE->getNumArgs() < 3)
9730     return;
9731   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
9732   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
9733   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
9734 
9735   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
9736                                      CE->getRParenLoc()))
9737     return;
9738 
9739   // Identify common expressions, which are wrongly used as the size argument
9740   // to strncat and may lead to buffer overflows.
9741   unsigned PatternType = 0;
9742   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
9743     // - sizeof(dst)
9744     if (referToTheSameDecl(SizeOfArg, DstArg))
9745       PatternType = 1;
9746     // - sizeof(src)
9747     else if (referToTheSameDecl(SizeOfArg, SrcArg))
9748       PatternType = 2;
9749   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
9750     if (BE->getOpcode() == BO_Sub) {
9751       const Expr *L = BE->getLHS()->IgnoreParenCasts();
9752       const Expr *R = BE->getRHS()->IgnoreParenCasts();
9753       // - sizeof(dst) - strlen(dst)
9754       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
9755           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
9756         PatternType = 1;
9757       // - sizeof(src) - (anything)
9758       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
9759         PatternType = 2;
9760     }
9761   }
9762 
9763   if (PatternType == 0)
9764     return;
9765 
9766   // Generate the diagnostic.
9767   SourceLocation SL = LenArg->getBeginLoc();
9768   SourceRange SR = LenArg->getSourceRange();
9769   SourceManager &SM = getSourceManager();
9770 
9771   // If the function is defined as a builtin macro, do not show macro expansion.
9772   if (SM.isMacroArgExpansion(SL)) {
9773     SL = SM.getSpellingLoc(SL);
9774     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
9775                      SM.getSpellingLoc(SR.getEnd()));
9776   }
9777 
9778   // Check if the destination is an array (rather than a pointer to an array).
9779   QualType DstTy = DstArg->getType();
9780   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
9781                                                                     Context);
9782   if (!isKnownSizeArray) {
9783     if (PatternType == 1)
9784       Diag(SL, diag::warn_strncat_wrong_size) << SR;
9785     else
9786       Diag(SL, diag::warn_strncat_src_size) << SR;
9787     return;
9788   }
9789 
9790   if (PatternType == 1)
9791     Diag(SL, diag::warn_strncat_large_size) << SR;
9792   else
9793     Diag(SL, diag::warn_strncat_src_size) << SR;
9794 
9795   SmallString<128> sizeString;
9796   llvm::raw_svector_ostream OS(sizeString);
9797   OS << "sizeof(";
9798   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9799   OS << ") - ";
9800   OS << "strlen(";
9801   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9802   OS << ") - 1";
9803 
9804   Diag(SL, diag::note_strncat_wrong_size)
9805     << FixItHint::CreateReplacement(SR, OS.str());
9806 }
9807 
9808 void
9809 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
9810                          SourceLocation ReturnLoc,
9811                          bool isObjCMethod,
9812                          const AttrVec *Attrs,
9813                          const FunctionDecl *FD) {
9814   // Check if the return value is null but should not be.
9815   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
9816        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
9817       CheckNonNullExpr(*this, RetValExp))
9818     Diag(ReturnLoc, diag::warn_null_ret)
9819       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
9820 
9821   // C++11 [basic.stc.dynamic.allocation]p4:
9822   //   If an allocation function declared with a non-throwing
9823   //   exception-specification fails to allocate storage, it shall return
9824   //   a null pointer. Any other allocation function that fails to allocate
9825   //   storage shall indicate failure only by throwing an exception [...]
9826   if (FD) {
9827     OverloadedOperatorKind Op = FD->getOverloadedOperator();
9828     if (Op == OO_New || Op == OO_Array_New) {
9829       const FunctionProtoType *Proto
9830         = FD->getType()->castAs<FunctionProtoType>();
9831       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
9832           CheckNonNullExpr(*this, RetValExp))
9833         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
9834           << FD << getLangOpts().CPlusPlus11;
9835     }
9836   }
9837 }
9838 
9839 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
9840 
9841 /// Check for comparisons of floating point operands using != and ==.
9842 /// Issue a warning if these are no self-comparisons, as they are not likely
9843 /// to do what the programmer intended.
9844 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
9845   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
9846   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
9847 
9848   // Special case: check for x == x (which is OK).
9849   // Do not emit warnings for such cases.
9850   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
9851     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
9852       if (DRL->getDecl() == DRR->getDecl())
9853         return;
9854 
9855   // Special case: check for comparisons against literals that can be exactly
9856   //  represented by APFloat.  In such cases, do not emit a warning.  This
9857   //  is a heuristic: often comparison against such literals are used to
9858   //  detect if a value in a variable has not changed.  This clearly can
9859   //  lead to false negatives.
9860   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
9861     if (FLL->isExact())
9862       return;
9863   } else
9864     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
9865       if (FLR->isExact())
9866         return;
9867 
9868   // Check for comparisons with builtin types.
9869   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
9870     if (CL->getBuiltinCallee())
9871       return;
9872 
9873   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
9874     if (CR->getBuiltinCallee())
9875       return;
9876 
9877   // Emit the diagnostic.
9878   Diag(Loc, diag::warn_floatingpoint_eq)
9879     << LHS->getSourceRange() << RHS->getSourceRange();
9880 }
9881 
9882 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
9883 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
9884 
9885 namespace {
9886 
9887 /// Structure recording the 'active' range of an integer-valued
9888 /// expression.
9889 struct IntRange {
9890   /// The number of bits active in the int.
9891   unsigned Width;
9892 
9893   /// True if the int is known not to have negative values.
9894   bool NonNegative;
9895 
9896   IntRange(unsigned Width, bool NonNegative)
9897       : Width(Width), NonNegative(NonNegative) {}
9898 
9899   /// Returns the range of the bool type.
9900   static IntRange forBoolType() {
9901     return IntRange(1, true);
9902   }
9903 
9904   /// Returns the range of an opaque value of the given integral type.
9905   static IntRange forValueOfType(ASTContext &C, QualType T) {
9906     return forValueOfCanonicalType(C,
9907                           T->getCanonicalTypeInternal().getTypePtr());
9908   }
9909 
9910   /// Returns the range of an opaque value of a canonical integral type.
9911   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
9912     assert(T->isCanonicalUnqualified());
9913 
9914     if (const VectorType *VT = dyn_cast<VectorType>(T))
9915       T = VT->getElementType().getTypePtr();
9916     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9917       T = CT->getElementType().getTypePtr();
9918     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9919       T = AT->getValueType().getTypePtr();
9920 
9921     if (!C.getLangOpts().CPlusPlus) {
9922       // For enum types in C code, use the underlying datatype.
9923       if (const EnumType *ET = dyn_cast<EnumType>(T))
9924         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
9925     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
9926       // For enum types in C++, use the known bit width of the enumerators.
9927       EnumDecl *Enum = ET->getDecl();
9928       // In C++11, enums can have a fixed underlying type. Use this type to
9929       // compute the range.
9930       if (Enum->isFixed()) {
9931         return IntRange(C.getIntWidth(QualType(T, 0)),
9932                         !ET->isSignedIntegerOrEnumerationType());
9933       }
9934 
9935       unsigned NumPositive = Enum->getNumPositiveBits();
9936       unsigned NumNegative = Enum->getNumNegativeBits();
9937 
9938       if (NumNegative == 0)
9939         return IntRange(NumPositive, true/*NonNegative*/);
9940       else
9941         return IntRange(std::max(NumPositive + 1, NumNegative),
9942                         false/*NonNegative*/);
9943     }
9944 
9945     if (const auto *EIT = dyn_cast<ExtIntType>(T))
9946       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
9947 
9948     const BuiltinType *BT = cast<BuiltinType>(T);
9949     assert(BT->isInteger());
9950 
9951     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9952   }
9953 
9954   /// Returns the "target" range of a canonical integral type, i.e.
9955   /// the range of values expressible in the type.
9956   ///
9957   /// This matches forValueOfCanonicalType except that enums have the
9958   /// full range of their type, not the range of their enumerators.
9959   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
9960     assert(T->isCanonicalUnqualified());
9961 
9962     if (const VectorType *VT = dyn_cast<VectorType>(T))
9963       T = VT->getElementType().getTypePtr();
9964     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9965       T = CT->getElementType().getTypePtr();
9966     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9967       T = AT->getValueType().getTypePtr();
9968     if (const EnumType *ET = dyn_cast<EnumType>(T))
9969       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
9970 
9971     if (const auto *EIT = dyn_cast<ExtIntType>(T))
9972       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
9973 
9974     const BuiltinType *BT = cast<BuiltinType>(T);
9975     assert(BT->isInteger());
9976 
9977     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9978   }
9979 
9980   /// Returns the supremum of two ranges: i.e. their conservative merge.
9981   static IntRange join(IntRange L, IntRange R) {
9982     return IntRange(std::max(L.Width, R.Width),
9983                     L.NonNegative && R.NonNegative);
9984   }
9985 
9986   /// Returns the infinum of two ranges: i.e. their aggressive merge.
9987   static IntRange meet(IntRange L, IntRange R) {
9988     return IntRange(std::min(L.Width, R.Width),
9989                     L.NonNegative || R.NonNegative);
9990   }
9991 };
9992 
9993 } // namespace
9994 
9995 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
9996                               unsigned MaxWidth) {
9997   if (value.isSigned() && value.isNegative())
9998     return IntRange(value.getMinSignedBits(), false);
9999 
10000   if (value.getBitWidth() > MaxWidth)
10001     value = value.trunc(MaxWidth);
10002 
10003   // isNonNegative() just checks the sign bit without considering
10004   // signedness.
10005   return IntRange(value.getActiveBits(), true);
10006 }
10007 
10008 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
10009                               unsigned MaxWidth) {
10010   if (result.isInt())
10011     return GetValueRange(C, result.getInt(), MaxWidth);
10012 
10013   if (result.isVector()) {
10014     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
10015     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
10016       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
10017       R = IntRange::join(R, El);
10018     }
10019     return R;
10020   }
10021 
10022   if (result.isComplexInt()) {
10023     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
10024     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
10025     return IntRange::join(R, I);
10026   }
10027 
10028   // This can happen with lossless casts to intptr_t of "based" lvalues.
10029   // Assume it might use arbitrary bits.
10030   // FIXME: The only reason we need to pass the type in here is to get
10031   // the sign right on this one case.  It would be nice if APValue
10032   // preserved this.
10033   assert(result.isLValue() || result.isAddrLabelDiff());
10034   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
10035 }
10036 
10037 static QualType GetExprType(const Expr *E) {
10038   QualType Ty = E->getType();
10039   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
10040     Ty = AtomicRHS->getValueType();
10041   return Ty;
10042 }
10043 
10044 /// Pseudo-evaluate the given integer expression, estimating the
10045 /// range of values it might take.
10046 ///
10047 /// \param MaxWidth - the width to which the value will be truncated
10048 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
10049                              bool InConstantContext) {
10050   E = E->IgnoreParens();
10051 
10052   // Try a full evaluation first.
10053   Expr::EvalResult result;
10054   if (E->EvaluateAsRValue(result, C, InConstantContext))
10055     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
10056 
10057   // I think we only want to look through implicit casts here; if the
10058   // user has an explicit widening cast, we should treat the value as
10059   // being of the new, wider type.
10060   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
10061     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
10062       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext);
10063 
10064     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
10065 
10066     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
10067                          CE->getCastKind() == CK_BooleanToSignedIntegral;
10068 
10069     // Assume that non-integer casts can span the full range of the type.
10070     if (!isIntegerCast)
10071       return OutputTypeRange;
10072 
10073     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
10074                                      std::min(MaxWidth, OutputTypeRange.Width),
10075                                      InConstantContext);
10076 
10077     // Bail out if the subexpr's range is as wide as the cast type.
10078     if (SubRange.Width >= OutputTypeRange.Width)
10079       return OutputTypeRange;
10080 
10081     // Otherwise, we take the smaller width, and we're non-negative if
10082     // either the output type or the subexpr is.
10083     return IntRange(SubRange.Width,
10084                     SubRange.NonNegative || OutputTypeRange.NonNegative);
10085   }
10086 
10087   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
10088     // If we can fold the condition, just take that operand.
10089     bool CondResult;
10090     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
10091       return GetExprRange(C,
10092                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
10093                           MaxWidth, InConstantContext);
10094 
10095     // Otherwise, conservatively merge.
10096     IntRange L =
10097         GetExprRange(C, CO->getTrueExpr(), MaxWidth, InConstantContext);
10098     IntRange R =
10099         GetExprRange(C, CO->getFalseExpr(), MaxWidth, InConstantContext);
10100     return IntRange::join(L, R);
10101   }
10102 
10103   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
10104     switch (BO->getOpcode()) {
10105     case BO_Cmp:
10106       llvm_unreachable("builtin <=> should have class type");
10107 
10108     // Boolean-valued operations are single-bit and positive.
10109     case BO_LAnd:
10110     case BO_LOr:
10111     case BO_LT:
10112     case BO_GT:
10113     case BO_LE:
10114     case BO_GE:
10115     case BO_EQ:
10116     case BO_NE:
10117       return IntRange::forBoolType();
10118 
10119     // The type of the assignments is the type of the LHS, so the RHS
10120     // is not necessarily the same type.
10121     case BO_MulAssign:
10122     case BO_DivAssign:
10123     case BO_RemAssign:
10124     case BO_AddAssign:
10125     case BO_SubAssign:
10126     case BO_XorAssign:
10127     case BO_OrAssign:
10128       // TODO: bitfields?
10129       return IntRange::forValueOfType(C, GetExprType(E));
10130 
10131     // Simple assignments just pass through the RHS, which will have
10132     // been coerced to the LHS type.
10133     case BO_Assign:
10134       // TODO: bitfields?
10135       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10136 
10137     // Operations with opaque sources are black-listed.
10138     case BO_PtrMemD:
10139     case BO_PtrMemI:
10140       return IntRange::forValueOfType(C, GetExprType(E));
10141 
10142     // Bitwise-and uses the *infinum* of the two source ranges.
10143     case BO_And:
10144     case BO_AndAssign:
10145       return IntRange::meet(
10146           GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext),
10147           GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext));
10148 
10149     // Left shift gets black-listed based on a judgement call.
10150     case BO_Shl:
10151       // ...except that we want to treat '1 << (blah)' as logically
10152       // positive.  It's an important idiom.
10153       if (IntegerLiteral *I
10154             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
10155         if (I->getValue() == 1) {
10156           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
10157           return IntRange(R.Width, /*NonNegative*/ true);
10158         }
10159       }
10160       LLVM_FALLTHROUGH;
10161 
10162     case BO_ShlAssign:
10163       return IntRange::forValueOfType(C, GetExprType(E));
10164 
10165     // Right shift by a constant can narrow its left argument.
10166     case BO_Shr:
10167     case BO_ShrAssign: {
10168       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
10169 
10170       // If the shift amount is a positive constant, drop the width by
10171       // that much.
10172       llvm::APSInt shift;
10173       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
10174           shift.isNonNegative()) {
10175         unsigned zext = shift.getZExtValue();
10176         if (zext >= L.Width)
10177           L.Width = (L.NonNegative ? 0 : 1);
10178         else
10179           L.Width -= zext;
10180       }
10181 
10182       return L;
10183     }
10184 
10185     // Comma acts as its right operand.
10186     case BO_Comma:
10187       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10188 
10189     // Black-list pointer subtractions.
10190     case BO_Sub:
10191       if (BO->getLHS()->getType()->isPointerType())
10192         return IntRange::forValueOfType(C, GetExprType(E));
10193       break;
10194 
10195     // The width of a division result is mostly determined by the size
10196     // of the LHS.
10197     case BO_Div: {
10198       // Don't 'pre-truncate' the operands.
10199       unsigned opWidth = C.getIntWidth(GetExprType(E));
10200       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
10201 
10202       // If the divisor is constant, use that.
10203       llvm::APSInt divisor;
10204       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
10205         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
10206         if (log2 >= L.Width)
10207           L.Width = (L.NonNegative ? 0 : 1);
10208         else
10209           L.Width = std::min(L.Width - log2, MaxWidth);
10210         return L;
10211       }
10212 
10213       // Otherwise, just use the LHS's width.
10214       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
10215       return IntRange(L.Width, L.NonNegative && R.NonNegative);
10216     }
10217 
10218     // The result of a remainder can't be larger than the result of
10219     // either side.
10220     case BO_Rem: {
10221       // Don't 'pre-truncate' the operands.
10222       unsigned opWidth = C.getIntWidth(GetExprType(E));
10223       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
10224       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
10225 
10226       IntRange meet = IntRange::meet(L, R);
10227       meet.Width = std::min(meet.Width, MaxWidth);
10228       return meet;
10229     }
10230 
10231     // The default behavior is okay for these.
10232     case BO_Mul:
10233     case BO_Add:
10234     case BO_Xor:
10235     case BO_Or:
10236       break;
10237     }
10238 
10239     // The default case is to treat the operation as if it were closed
10240     // on the narrowest type that encompasses both operands.
10241     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
10242     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10243     return IntRange::join(L, R);
10244   }
10245 
10246   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
10247     switch (UO->getOpcode()) {
10248     // Boolean-valued operations are white-listed.
10249     case UO_LNot:
10250       return IntRange::forBoolType();
10251 
10252     // Operations with opaque sources are black-listed.
10253     case UO_Deref:
10254     case UO_AddrOf: // should be impossible
10255       return IntRange::forValueOfType(C, GetExprType(E));
10256 
10257     default:
10258       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext);
10259     }
10260   }
10261 
10262   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
10263     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext);
10264 
10265   if (const auto *BitField = E->getSourceBitField())
10266     return IntRange(BitField->getBitWidthValue(C),
10267                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
10268 
10269   return IntRange::forValueOfType(C, GetExprType(E));
10270 }
10271 
10272 static IntRange GetExprRange(ASTContext &C, const Expr *E,
10273                              bool InConstantContext) {
10274   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext);
10275 }
10276 
10277 /// Checks whether the given value, which currently has the given
10278 /// source semantics, has the same value when coerced through the
10279 /// target semantics.
10280 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
10281                                  const llvm::fltSemantics &Src,
10282                                  const llvm::fltSemantics &Tgt) {
10283   llvm::APFloat truncated = value;
10284 
10285   bool ignored;
10286   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
10287   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
10288 
10289   return truncated.bitwiseIsEqual(value);
10290 }
10291 
10292 /// Checks whether the given value, which currently has the given
10293 /// source semantics, has the same value when coerced through the
10294 /// target semantics.
10295 ///
10296 /// The value might be a vector of floats (or a complex number).
10297 static bool IsSameFloatAfterCast(const APValue &value,
10298                                  const llvm::fltSemantics &Src,
10299                                  const llvm::fltSemantics &Tgt) {
10300   if (value.isFloat())
10301     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
10302 
10303   if (value.isVector()) {
10304     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
10305       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
10306         return false;
10307     return true;
10308   }
10309 
10310   assert(value.isComplexFloat());
10311   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
10312           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
10313 }
10314 
10315 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
10316                                        bool IsListInit = false);
10317 
10318 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
10319   // Suppress cases where we are comparing against an enum constant.
10320   if (const DeclRefExpr *DR =
10321       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
10322     if (isa<EnumConstantDecl>(DR->getDecl()))
10323       return true;
10324 
10325   // Suppress cases where the value is expanded from a macro, unless that macro
10326   // is how a language represents a boolean literal. This is the case in both C
10327   // and Objective-C.
10328   SourceLocation BeginLoc = E->getBeginLoc();
10329   if (BeginLoc.isMacroID()) {
10330     StringRef MacroName = Lexer::getImmediateMacroName(
10331         BeginLoc, S.getSourceManager(), S.getLangOpts());
10332     return MacroName != "YES" && MacroName != "NO" &&
10333            MacroName != "true" && MacroName != "false";
10334   }
10335 
10336   return false;
10337 }
10338 
10339 static bool isKnownToHaveUnsignedValue(Expr *E) {
10340   return E->getType()->isIntegerType() &&
10341          (!E->getType()->isSignedIntegerType() ||
10342           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
10343 }
10344 
10345 namespace {
10346 /// The promoted range of values of a type. In general this has the
10347 /// following structure:
10348 ///
10349 ///     |-----------| . . . |-----------|
10350 ///     ^           ^       ^           ^
10351 ///    Min       HoleMin  HoleMax      Max
10352 ///
10353 /// ... where there is only a hole if a signed type is promoted to unsigned
10354 /// (in which case Min and Max are the smallest and largest representable
10355 /// values).
10356 struct PromotedRange {
10357   // Min, or HoleMax if there is a hole.
10358   llvm::APSInt PromotedMin;
10359   // Max, or HoleMin if there is a hole.
10360   llvm::APSInt PromotedMax;
10361 
10362   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
10363     if (R.Width == 0)
10364       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
10365     else if (R.Width >= BitWidth && !Unsigned) {
10366       // Promotion made the type *narrower*. This happens when promoting
10367       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
10368       // Treat all values of 'signed int' as being in range for now.
10369       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
10370       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
10371     } else {
10372       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
10373                         .extOrTrunc(BitWidth);
10374       PromotedMin.setIsUnsigned(Unsigned);
10375 
10376       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
10377                         .extOrTrunc(BitWidth);
10378       PromotedMax.setIsUnsigned(Unsigned);
10379     }
10380   }
10381 
10382   // Determine whether this range is contiguous (has no hole).
10383   bool isContiguous() const { return PromotedMin <= PromotedMax; }
10384 
10385   // Where a constant value is within the range.
10386   enum ComparisonResult {
10387     LT = 0x1,
10388     LE = 0x2,
10389     GT = 0x4,
10390     GE = 0x8,
10391     EQ = 0x10,
10392     NE = 0x20,
10393     InRangeFlag = 0x40,
10394 
10395     Less = LE | LT | NE,
10396     Min = LE | InRangeFlag,
10397     InRange = InRangeFlag,
10398     Max = GE | InRangeFlag,
10399     Greater = GE | GT | NE,
10400 
10401     OnlyValue = LE | GE | EQ | InRangeFlag,
10402     InHole = NE
10403   };
10404 
10405   ComparisonResult compare(const llvm::APSInt &Value) const {
10406     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
10407            Value.isUnsigned() == PromotedMin.isUnsigned());
10408     if (!isContiguous()) {
10409       assert(Value.isUnsigned() && "discontiguous range for signed compare");
10410       if (Value.isMinValue()) return Min;
10411       if (Value.isMaxValue()) return Max;
10412       if (Value >= PromotedMin) return InRange;
10413       if (Value <= PromotedMax) return InRange;
10414       return InHole;
10415     }
10416 
10417     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
10418     case -1: return Less;
10419     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
10420     case 1:
10421       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
10422       case -1: return InRange;
10423       case 0: return Max;
10424       case 1: return Greater;
10425       }
10426     }
10427 
10428     llvm_unreachable("impossible compare result");
10429   }
10430 
10431   static llvm::Optional<StringRef>
10432   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
10433     if (Op == BO_Cmp) {
10434       ComparisonResult LTFlag = LT, GTFlag = GT;
10435       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
10436 
10437       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
10438       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
10439       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
10440       return llvm::None;
10441     }
10442 
10443     ComparisonResult TrueFlag, FalseFlag;
10444     if (Op == BO_EQ) {
10445       TrueFlag = EQ;
10446       FalseFlag = NE;
10447     } else if (Op == BO_NE) {
10448       TrueFlag = NE;
10449       FalseFlag = EQ;
10450     } else {
10451       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
10452         TrueFlag = LT;
10453         FalseFlag = GE;
10454       } else {
10455         TrueFlag = GT;
10456         FalseFlag = LE;
10457       }
10458       if (Op == BO_GE || Op == BO_LE)
10459         std::swap(TrueFlag, FalseFlag);
10460     }
10461     if (R & TrueFlag)
10462       return StringRef("true");
10463     if (R & FalseFlag)
10464       return StringRef("false");
10465     return llvm::None;
10466   }
10467 };
10468 }
10469 
10470 static bool HasEnumType(Expr *E) {
10471   // Strip off implicit integral promotions.
10472   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
10473     if (ICE->getCastKind() != CK_IntegralCast &&
10474         ICE->getCastKind() != CK_NoOp)
10475       break;
10476     E = ICE->getSubExpr();
10477   }
10478 
10479   return E->getType()->isEnumeralType();
10480 }
10481 
10482 static int classifyConstantValue(Expr *Constant) {
10483   // The values of this enumeration are used in the diagnostics
10484   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
10485   enum ConstantValueKind {
10486     Miscellaneous = 0,
10487     LiteralTrue,
10488     LiteralFalse
10489   };
10490   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
10491     return BL->getValue() ? ConstantValueKind::LiteralTrue
10492                           : ConstantValueKind::LiteralFalse;
10493   return ConstantValueKind::Miscellaneous;
10494 }
10495 
10496 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
10497                                         Expr *Constant, Expr *Other,
10498                                         const llvm::APSInt &Value,
10499                                         bool RhsConstant) {
10500   if (S.inTemplateInstantiation())
10501     return false;
10502 
10503   Expr *OriginalOther = Other;
10504 
10505   Constant = Constant->IgnoreParenImpCasts();
10506   Other = Other->IgnoreParenImpCasts();
10507 
10508   // Suppress warnings on tautological comparisons between values of the same
10509   // enumeration type. There are only two ways we could warn on this:
10510   //  - If the constant is outside the range of representable values of
10511   //    the enumeration. In such a case, we should warn about the cast
10512   //    to enumeration type, not about the comparison.
10513   //  - If the constant is the maximum / minimum in-range value. For an
10514   //    enumeratin type, such comparisons can be meaningful and useful.
10515   if (Constant->getType()->isEnumeralType() &&
10516       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
10517     return false;
10518 
10519   // TODO: Investigate using GetExprRange() to get tighter bounds
10520   // on the bit ranges.
10521   QualType OtherT = Other->getType();
10522   if (const auto *AT = OtherT->getAs<AtomicType>())
10523     OtherT = AT->getValueType();
10524   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
10525 
10526   // Special case for ObjC BOOL on targets where its a typedef for a signed char
10527   // (Namely, macOS).
10528   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
10529                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
10530                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
10531 
10532   // Whether we're treating Other as being a bool because of the form of
10533   // expression despite it having another type (typically 'int' in C).
10534   bool OtherIsBooleanDespiteType =
10535       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
10536   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
10537     OtherRange = IntRange::forBoolType();
10538 
10539   // Determine the promoted range of the other type and see if a comparison of
10540   // the constant against that range is tautological.
10541   PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
10542                                    Value.isUnsigned());
10543   auto Cmp = OtherPromotedRange.compare(Value);
10544   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
10545   if (!Result)
10546     return false;
10547 
10548   // Suppress the diagnostic for an in-range comparison if the constant comes
10549   // from a macro or enumerator. We don't want to diagnose
10550   //
10551   //   some_long_value <= INT_MAX
10552   //
10553   // when sizeof(int) == sizeof(long).
10554   bool InRange = Cmp & PromotedRange::InRangeFlag;
10555   if (InRange && IsEnumConstOrFromMacro(S, Constant))
10556     return false;
10557 
10558   // If this is a comparison to an enum constant, include that
10559   // constant in the diagnostic.
10560   const EnumConstantDecl *ED = nullptr;
10561   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
10562     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
10563 
10564   // Should be enough for uint128 (39 decimal digits)
10565   SmallString<64> PrettySourceValue;
10566   llvm::raw_svector_ostream OS(PrettySourceValue);
10567   if (ED) {
10568     OS << '\'' << *ED << "' (" << Value << ")";
10569   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
10570                Constant->IgnoreParenImpCasts())) {
10571     OS << (BL->getValue() ? "YES" : "NO");
10572   } else {
10573     OS << Value;
10574   }
10575 
10576   if (IsObjCSignedCharBool) {
10577     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10578                           S.PDiag(diag::warn_tautological_compare_objc_bool)
10579                               << OS.str() << *Result);
10580     return true;
10581   }
10582 
10583   // FIXME: We use a somewhat different formatting for the in-range cases and
10584   // cases involving boolean values for historical reasons. We should pick a
10585   // consistent way of presenting these diagnostics.
10586   if (!InRange || Other->isKnownToHaveBooleanValue()) {
10587 
10588     S.DiagRuntimeBehavior(
10589         E->getOperatorLoc(), E,
10590         S.PDiag(!InRange ? diag::warn_out_of_range_compare
10591                          : diag::warn_tautological_bool_compare)
10592             << OS.str() << classifyConstantValue(Constant) << OtherT
10593             << OtherIsBooleanDespiteType << *Result
10594             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
10595   } else {
10596     unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
10597                         ? (HasEnumType(OriginalOther)
10598                                ? diag::warn_unsigned_enum_always_true_comparison
10599                                : diag::warn_unsigned_always_true_comparison)
10600                         : diag::warn_tautological_constant_compare;
10601 
10602     S.Diag(E->getOperatorLoc(), Diag)
10603         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
10604         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
10605   }
10606 
10607   return true;
10608 }
10609 
10610 /// Analyze the operands of the given comparison.  Implements the
10611 /// fallback case from AnalyzeComparison.
10612 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
10613   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10614   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10615 }
10616 
10617 /// Implements -Wsign-compare.
10618 ///
10619 /// \param E the binary operator to check for warnings
10620 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
10621   // The type the comparison is being performed in.
10622   QualType T = E->getLHS()->getType();
10623 
10624   // Only analyze comparison operators where both sides have been converted to
10625   // the same type.
10626   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
10627     return AnalyzeImpConvsInComparison(S, E);
10628 
10629   // Don't analyze value-dependent comparisons directly.
10630   if (E->isValueDependent())
10631     return AnalyzeImpConvsInComparison(S, E);
10632 
10633   Expr *LHS = E->getLHS();
10634   Expr *RHS = E->getRHS();
10635 
10636   if (T->isIntegralType(S.Context)) {
10637     llvm::APSInt RHSValue;
10638     llvm::APSInt LHSValue;
10639 
10640     bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
10641     bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
10642 
10643     // We don't care about expressions whose result is a constant.
10644     if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
10645       return AnalyzeImpConvsInComparison(S, E);
10646 
10647     // We only care about expressions where just one side is literal
10648     if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
10649       // Is the constant on the RHS or LHS?
10650       const bool RhsConstant = IsRHSIntegralLiteral;
10651       Expr *Const = RhsConstant ? RHS : LHS;
10652       Expr *Other = RhsConstant ? LHS : RHS;
10653       const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
10654 
10655       // Check whether an integer constant comparison results in a value
10656       // of 'true' or 'false'.
10657       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
10658         return AnalyzeImpConvsInComparison(S, E);
10659     }
10660   }
10661 
10662   if (!T->hasUnsignedIntegerRepresentation()) {
10663     // We don't do anything special if this isn't an unsigned integral
10664     // comparison:  we're only interested in integral comparisons, and
10665     // signed comparisons only happen in cases we don't care to warn about.
10666     return AnalyzeImpConvsInComparison(S, E);
10667   }
10668 
10669   LHS = LHS->IgnoreParenImpCasts();
10670   RHS = RHS->IgnoreParenImpCasts();
10671 
10672   if (!S.getLangOpts().CPlusPlus) {
10673     // Avoid warning about comparison of integers with different signs when
10674     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
10675     // the type of `E`.
10676     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
10677       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10678     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
10679       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10680   }
10681 
10682   // Check to see if one of the (unmodified) operands is of different
10683   // signedness.
10684   Expr *signedOperand, *unsignedOperand;
10685   if (LHS->getType()->hasSignedIntegerRepresentation()) {
10686     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
10687            "unsigned comparison between two signed integer expressions?");
10688     signedOperand = LHS;
10689     unsignedOperand = RHS;
10690   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
10691     signedOperand = RHS;
10692     unsignedOperand = LHS;
10693   } else {
10694     return AnalyzeImpConvsInComparison(S, E);
10695   }
10696 
10697   // Otherwise, calculate the effective range of the signed operand.
10698   IntRange signedRange =
10699       GetExprRange(S.Context, signedOperand, S.isConstantEvaluated());
10700 
10701   // Go ahead and analyze implicit conversions in the operands.  Note
10702   // that we skip the implicit conversions on both sides.
10703   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
10704   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
10705 
10706   // If the signed range is non-negative, -Wsign-compare won't fire.
10707   if (signedRange.NonNegative)
10708     return;
10709 
10710   // For (in)equality comparisons, if the unsigned operand is a
10711   // constant which cannot collide with a overflowed signed operand,
10712   // then reinterpreting the signed operand as unsigned will not
10713   // change the result of the comparison.
10714   if (E->isEqualityOp()) {
10715     unsigned comparisonWidth = S.Context.getIntWidth(T);
10716     IntRange unsignedRange =
10717         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated());
10718 
10719     // We should never be unable to prove that the unsigned operand is
10720     // non-negative.
10721     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
10722 
10723     if (unsignedRange.Width < comparisonWidth)
10724       return;
10725   }
10726 
10727   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10728                         S.PDiag(diag::warn_mixed_sign_comparison)
10729                             << LHS->getType() << RHS->getType()
10730                             << LHS->getSourceRange() << RHS->getSourceRange());
10731 }
10732 
10733 /// Analyzes an attempt to assign the given value to a bitfield.
10734 ///
10735 /// Returns true if there was something fishy about the attempt.
10736 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
10737                                       SourceLocation InitLoc) {
10738   assert(Bitfield->isBitField());
10739   if (Bitfield->isInvalidDecl())
10740     return false;
10741 
10742   // White-list bool bitfields.
10743   QualType BitfieldType = Bitfield->getType();
10744   if (BitfieldType->isBooleanType())
10745      return false;
10746 
10747   if (BitfieldType->isEnumeralType()) {
10748     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
10749     // If the underlying enum type was not explicitly specified as an unsigned
10750     // type and the enum contain only positive values, MSVC++ will cause an
10751     // inconsistency by storing this as a signed type.
10752     if (S.getLangOpts().CPlusPlus11 &&
10753         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
10754         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
10755         BitfieldEnumDecl->getNumNegativeBits() == 0) {
10756       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
10757         << BitfieldEnumDecl->getNameAsString();
10758     }
10759   }
10760 
10761   if (Bitfield->getType()->isBooleanType())
10762     return false;
10763 
10764   // Ignore value- or type-dependent expressions.
10765   if (Bitfield->getBitWidth()->isValueDependent() ||
10766       Bitfield->getBitWidth()->isTypeDependent() ||
10767       Init->isValueDependent() ||
10768       Init->isTypeDependent())
10769     return false;
10770 
10771   Expr *OriginalInit = Init->IgnoreParenImpCasts();
10772   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
10773 
10774   Expr::EvalResult Result;
10775   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
10776                                    Expr::SE_AllowSideEffects)) {
10777     // The RHS is not constant.  If the RHS has an enum type, make sure the
10778     // bitfield is wide enough to hold all the values of the enum without
10779     // truncation.
10780     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
10781       EnumDecl *ED = EnumTy->getDecl();
10782       bool SignedBitfield = BitfieldType->isSignedIntegerType();
10783 
10784       // Enum types are implicitly signed on Windows, so check if there are any
10785       // negative enumerators to see if the enum was intended to be signed or
10786       // not.
10787       bool SignedEnum = ED->getNumNegativeBits() > 0;
10788 
10789       // Check for surprising sign changes when assigning enum values to a
10790       // bitfield of different signedness.  If the bitfield is signed and we
10791       // have exactly the right number of bits to store this unsigned enum,
10792       // suggest changing the enum to an unsigned type. This typically happens
10793       // on Windows where unfixed enums always use an underlying type of 'int'.
10794       unsigned DiagID = 0;
10795       if (SignedEnum && !SignedBitfield) {
10796         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
10797       } else if (SignedBitfield && !SignedEnum &&
10798                  ED->getNumPositiveBits() == FieldWidth) {
10799         DiagID = diag::warn_signed_bitfield_enum_conversion;
10800       }
10801 
10802       if (DiagID) {
10803         S.Diag(InitLoc, DiagID) << Bitfield << ED;
10804         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
10805         SourceRange TypeRange =
10806             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
10807         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
10808             << SignedEnum << TypeRange;
10809       }
10810 
10811       // Compute the required bitwidth. If the enum has negative values, we need
10812       // one more bit than the normal number of positive bits to represent the
10813       // sign bit.
10814       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
10815                                                   ED->getNumNegativeBits())
10816                                        : ED->getNumPositiveBits();
10817 
10818       // Check the bitwidth.
10819       if (BitsNeeded > FieldWidth) {
10820         Expr *WidthExpr = Bitfield->getBitWidth();
10821         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
10822             << Bitfield << ED;
10823         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
10824             << BitsNeeded << ED << WidthExpr->getSourceRange();
10825       }
10826     }
10827 
10828     return false;
10829   }
10830 
10831   llvm::APSInt Value = Result.Val.getInt();
10832 
10833   unsigned OriginalWidth = Value.getBitWidth();
10834 
10835   if (!Value.isSigned() || Value.isNegative())
10836     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
10837       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
10838         OriginalWidth = Value.getMinSignedBits();
10839 
10840   if (OriginalWidth <= FieldWidth)
10841     return false;
10842 
10843   // Compute the value which the bitfield will contain.
10844   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
10845   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
10846 
10847   // Check whether the stored value is equal to the original value.
10848   TruncatedValue = TruncatedValue.extend(OriginalWidth);
10849   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
10850     return false;
10851 
10852   // Special-case bitfields of width 1: booleans are naturally 0/1, and
10853   // therefore don't strictly fit into a signed bitfield of width 1.
10854   if (FieldWidth == 1 && Value == 1)
10855     return false;
10856 
10857   std::string PrettyValue = Value.toString(10);
10858   std::string PrettyTrunc = TruncatedValue.toString(10);
10859 
10860   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
10861     << PrettyValue << PrettyTrunc << OriginalInit->getType()
10862     << Init->getSourceRange();
10863 
10864   return true;
10865 }
10866 
10867 /// Analyze the given simple or compound assignment for warning-worthy
10868 /// operations.
10869 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
10870   // Just recurse on the LHS.
10871   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10872 
10873   // We want to recurse on the RHS as normal unless we're assigning to
10874   // a bitfield.
10875   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
10876     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
10877                                   E->getOperatorLoc())) {
10878       // Recurse, ignoring any implicit conversions on the RHS.
10879       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
10880                                         E->getOperatorLoc());
10881     }
10882   }
10883 
10884   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10885 
10886   // Diagnose implicitly sequentially-consistent atomic assignment.
10887   if (E->getLHS()->getType()->isAtomicType())
10888     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
10889 }
10890 
10891 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
10892 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
10893                             SourceLocation CContext, unsigned diag,
10894                             bool pruneControlFlow = false) {
10895   if (pruneControlFlow) {
10896     S.DiagRuntimeBehavior(E->getExprLoc(), E,
10897                           S.PDiag(diag)
10898                               << SourceType << T << E->getSourceRange()
10899                               << SourceRange(CContext));
10900     return;
10901   }
10902   S.Diag(E->getExprLoc(), diag)
10903     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
10904 }
10905 
10906 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
10907 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
10908                             SourceLocation CContext,
10909                             unsigned diag, bool pruneControlFlow = false) {
10910   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
10911 }
10912 
10913 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
10914   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
10915       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
10916 }
10917 
10918 static void adornObjCBoolConversionDiagWithTernaryFixit(
10919     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
10920   Expr *Ignored = SourceExpr->IgnoreImplicit();
10921   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
10922     Ignored = OVE->getSourceExpr();
10923   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
10924                      isa<BinaryOperator>(Ignored) ||
10925                      isa<CXXOperatorCallExpr>(Ignored);
10926   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
10927   if (NeedsParens)
10928     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
10929             << FixItHint::CreateInsertion(EndLoc, ")");
10930   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
10931 }
10932 
10933 /// Diagnose an implicit cast from a floating point value to an integer value.
10934 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
10935                                     SourceLocation CContext) {
10936   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
10937   const bool PruneWarnings = S.inTemplateInstantiation();
10938 
10939   Expr *InnerE = E->IgnoreParenImpCasts();
10940   // We also want to warn on, e.g., "int i = -1.234"
10941   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
10942     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
10943       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
10944 
10945   const bool IsLiteral =
10946       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
10947 
10948   llvm::APFloat Value(0.0);
10949   bool IsConstant =
10950     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
10951   if (!IsConstant) {
10952     if (isObjCSignedCharBool(S, T)) {
10953       return adornObjCBoolConversionDiagWithTernaryFixit(
10954           S, E,
10955           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
10956               << E->getType());
10957     }
10958 
10959     return DiagnoseImpCast(S, E, T, CContext,
10960                            diag::warn_impcast_float_integer, PruneWarnings);
10961   }
10962 
10963   bool isExact = false;
10964 
10965   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
10966                             T->hasUnsignedIntegerRepresentation());
10967   llvm::APFloat::opStatus Result = Value.convertToInteger(
10968       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
10969 
10970   // FIXME: Force the precision of the source value down so we don't print
10971   // digits which are usually useless (we don't really care here if we
10972   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
10973   // would automatically print the shortest representation, but it's a bit
10974   // tricky to implement.
10975   SmallString<16> PrettySourceValue;
10976   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
10977   precision = (precision * 59 + 195) / 196;
10978   Value.toString(PrettySourceValue, precision);
10979 
10980   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
10981     return adornObjCBoolConversionDiagWithTernaryFixit(
10982         S, E,
10983         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
10984             << PrettySourceValue);
10985   }
10986 
10987   if (Result == llvm::APFloat::opOK && isExact) {
10988     if (IsLiteral) return;
10989     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
10990                            PruneWarnings);
10991   }
10992 
10993   // Conversion of a floating-point value to a non-bool integer where the
10994   // integral part cannot be represented by the integer type is undefined.
10995   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
10996     return DiagnoseImpCast(
10997         S, E, T, CContext,
10998         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
10999                   : diag::warn_impcast_float_to_integer_out_of_range,
11000         PruneWarnings);
11001 
11002   unsigned DiagID = 0;
11003   if (IsLiteral) {
11004     // Warn on floating point literal to integer.
11005     DiagID = diag::warn_impcast_literal_float_to_integer;
11006   } else if (IntegerValue == 0) {
11007     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
11008       return DiagnoseImpCast(S, E, T, CContext,
11009                              diag::warn_impcast_float_integer, PruneWarnings);
11010     }
11011     // Warn on non-zero to zero conversion.
11012     DiagID = diag::warn_impcast_float_to_integer_zero;
11013   } else {
11014     if (IntegerValue.isUnsigned()) {
11015       if (!IntegerValue.isMaxValue()) {
11016         return DiagnoseImpCast(S, E, T, CContext,
11017                                diag::warn_impcast_float_integer, PruneWarnings);
11018       }
11019     } else {  // IntegerValue.isSigned()
11020       if (!IntegerValue.isMaxSignedValue() &&
11021           !IntegerValue.isMinSignedValue()) {
11022         return DiagnoseImpCast(S, E, T, CContext,
11023                                diag::warn_impcast_float_integer, PruneWarnings);
11024       }
11025     }
11026     // Warn on evaluatable floating point expression to integer conversion.
11027     DiagID = diag::warn_impcast_float_to_integer;
11028   }
11029 
11030   SmallString<16> PrettyTargetValue;
11031   if (IsBool)
11032     PrettyTargetValue = Value.isZero() ? "false" : "true";
11033   else
11034     IntegerValue.toString(PrettyTargetValue);
11035 
11036   if (PruneWarnings) {
11037     S.DiagRuntimeBehavior(E->getExprLoc(), E,
11038                           S.PDiag(DiagID)
11039                               << E->getType() << T.getUnqualifiedType()
11040                               << PrettySourceValue << PrettyTargetValue
11041                               << E->getSourceRange() << SourceRange(CContext));
11042   } else {
11043     S.Diag(E->getExprLoc(), DiagID)
11044         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
11045         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
11046   }
11047 }
11048 
11049 /// Analyze the given compound assignment for the possible losing of
11050 /// floating-point precision.
11051 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
11052   assert(isa<CompoundAssignOperator>(E) &&
11053          "Must be compound assignment operation");
11054   // Recurse on the LHS and RHS in here
11055   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11056   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11057 
11058   if (E->getLHS()->getType()->isAtomicType())
11059     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
11060 
11061   // Now check the outermost expression
11062   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
11063   const auto *RBT = cast<CompoundAssignOperator>(E)
11064                         ->getComputationResultType()
11065                         ->getAs<BuiltinType>();
11066 
11067   // The below checks assume source is floating point.
11068   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
11069 
11070   // If source is floating point but target is an integer.
11071   if (ResultBT->isInteger())
11072     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
11073                            E->getExprLoc(), diag::warn_impcast_float_integer);
11074 
11075   if (!ResultBT->isFloatingPoint())
11076     return;
11077 
11078   // If both source and target are floating points, warn about losing precision.
11079   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11080       QualType(ResultBT, 0), QualType(RBT, 0));
11081   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
11082     // warn about dropping FP rank.
11083     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
11084                     diag::warn_impcast_float_result_precision);
11085 }
11086 
11087 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
11088                                       IntRange Range) {
11089   if (!Range.Width) return "0";
11090 
11091   llvm::APSInt ValueInRange = Value;
11092   ValueInRange.setIsSigned(!Range.NonNegative);
11093   ValueInRange = ValueInRange.trunc(Range.Width);
11094   return ValueInRange.toString(10);
11095 }
11096 
11097 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
11098   if (!isa<ImplicitCastExpr>(Ex))
11099     return false;
11100 
11101   Expr *InnerE = Ex->IgnoreParenImpCasts();
11102   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
11103   const Type *Source =
11104     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
11105   if (Target->isDependentType())
11106     return false;
11107 
11108   const BuiltinType *FloatCandidateBT =
11109     dyn_cast<BuiltinType>(ToBool ? Source : Target);
11110   const Type *BoolCandidateType = ToBool ? Target : Source;
11111 
11112   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
11113           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
11114 }
11115 
11116 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
11117                                              SourceLocation CC) {
11118   unsigned NumArgs = TheCall->getNumArgs();
11119   for (unsigned i = 0; i < NumArgs; ++i) {
11120     Expr *CurrA = TheCall->getArg(i);
11121     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
11122       continue;
11123 
11124     bool IsSwapped = ((i > 0) &&
11125         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
11126     IsSwapped |= ((i < (NumArgs - 1)) &&
11127         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
11128     if (IsSwapped) {
11129       // Warn on this floating-point to bool conversion.
11130       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
11131                       CurrA->getType(), CC,
11132                       diag::warn_impcast_floating_point_to_bool);
11133     }
11134   }
11135 }
11136 
11137 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
11138                                    SourceLocation CC) {
11139   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
11140                         E->getExprLoc()))
11141     return;
11142 
11143   // Don't warn on functions which have return type nullptr_t.
11144   if (isa<CallExpr>(E))
11145     return;
11146 
11147   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
11148   const Expr::NullPointerConstantKind NullKind =
11149       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
11150   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
11151     return;
11152 
11153   // Return if target type is a safe conversion.
11154   if (T->isAnyPointerType() || T->isBlockPointerType() ||
11155       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
11156     return;
11157 
11158   SourceLocation Loc = E->getSourceRange().getBegin();
11159 
11160   // Venture through the macro stacks to get to the source of macro arguments.
11161   // The new location is a better location than the complete location that was
11162   // passed in.
11163   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
11164   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
11165 
11166   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
11167   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
11168     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
11169         Loc, S.SourceMgr, S.getLangOpts());
11170     if (MacroName == "NULL")
11171       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
11172   }
11173 
11174   // Only warn if the null and context location are in the same macro expansion.
11175   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
11176     return;
11177 
11178   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
11179       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
11180       << FixItHint::CreateReplacement(Loc,
11181                                       S.getFixItZeroLiteralForType(T, Loc));
11182 }
11183 
11184 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11185                                   ObjCArrayLiteral *ArrayLiteral);
11186 
11187 static void
11188 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11189                            ObjCDictionaryLiteral *DictionaryLiteral);
11190 
11191 /// Check a single element within a collection literal against the
11192 /// target element type.
11193 static void checkObjCCollectionLiteralElement(Sema &S,
11194                                               QualType TargetElementType,
11195                                               Expr *Element,
11196                                               unsigned ElementKind) {
11197   // Skip a bitcast to 'id' or qualified 'id'.
11198   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
11199     if (ICE->getCastKind() == CK_BitCast &&
11200         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
11201       Element = ICE->getSubExpr();
11202   }
11203 
11204   QualType ElementType = Element->getType();
11205   ExprResult ElementResult(Element);
11206   if (ElementType->getAs<ObjCObjectPointerType>() &&
11207       S.CheckSingleAssignmentConstraints(TargetElementType,
11208                                          ElementResult,
11209                                          false, false)
11210         != Sema::Compatible) {
11211     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
11212         << ElementType << ElementKind << TargetElementType
11213         << Element->getSourceRange();
11214   }
11215 
11216   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
11217     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
11218   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
11219     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
11220 }
11221 
11222 /// Check an Objective-C array literal being converted to the given
11223 /// target type.
11224 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11225                                   ObjCArrayLiteral *ArrayLiteral) {
11226   if (!S.NSArrayDecl)
11227     return;
11228 
11229   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11230   if (!TargetObjCPtr)
11231     return;
11232 
11233   if (TargetObjCPtr->isUnspecialized() ||
11234       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11235         != S.NSArrayDecl->getCanonicalDecl())
11236     return;
11237 
11238   auto TypeArgs = TargetObjCPtr->getTypeArgs();
11239   if (TypeArgs.size() != 1)
11240     return;
11241 
11242   QualType TargetElementType = TypeArgs[0];
11243   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
11244     checkObjCCollectionLiteralElement(S, TargetElementType,
11245                                       ArrayLiteral->getElement(I),
11246                                       0);
11247   }
11248 }
11249 
11250 /// Check an Objective-C dictionary literal being converted to the given
11251 /// target type.
11252 static void
11253 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11254                            ObjCDictionaryLiteral *DictionaryLiteral) {
11255   if (!S.NSDictionaryDecl)
11256     return;
11257 
11258   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11259   if (!TargetObjCPtr)
11260     return;
11261 
11262   if (TargetObjCPtr->isUnspecialized() ||
11263       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11264         != S.NSDictionaryDecl->getCanonicalDecl())
11265     return;
11266 
11267   auto TypeArgs = TargetObjCPtr->getTypeArgs();
11268   if (TypeArgs.size() != 2)
11269     return;
11270 
11271   QualType TargetKeyType = TypeArgs[0];
11272   QualType TargetObjectType = TypeArgs[1];
11273   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
11274     auto Element = DictionaryLiteral->getKeyValueElement(I);
11275     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
11276     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
11277   }
11278 }
11279 
11280 // Helper function to filter out cases for constant width constant conversion.
11281 // Don't warn on char array initialization or for non-decimal values.
11282 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
11283                                           SourceLocation CC) {
11284   // If initializing from a constant, and the constant starts with '0',
11285   // then it is a binary, octal, or hexadecimal.  Allow these constants
11286   // to fill all the bits, even if there is a sign change.
11287   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
11288     const char FirstLiteralCharacter =
11289         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
11290     if (FirstLiteralCharacter == '0')
11291       return false;
11292   }
11293 
11294   // If the CC location points to a '{', and the type is char, then assume
11295   // assume it is an array initialization.
11296   if (CC.isValid() && T->isCharType()) {
11297     const char FirstContextCharacter =
11298         S.getSourceManager().getCharacterData(CC)[0];
11299     if (FirstContextCharacter == '{')
11300       return false;
11301   }
11302 
11303   return true;
11304 }
11305 
11306 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
11307   const auto *IL = dyn_cast<IntegerLiteral>(E);
11308   if (!IL) {
11309     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
11310       if (UO->getOpcode() == UO_Minus)
11311         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
11312     }
11313   }
11314 
11315   return IL;
11316 }
11317 
11318 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
11319   E = E->IgnoreParenImpCasts();
11320   SourceLocation ExprLoc = E->getExprLoc();
11321 
11322   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11323     BinaryOperator::Opcode Opc = BO->getOpcode();
11324     Expr::EvalResult Result;
11325     // Do not diagnose unsigned shifts.
11326     if (Opc == BO_Shl) {
11327       const auto *LHS = getIntegerLiteral(BO->getLHS());
11328       const auto *RHS = getIntegerLiteral(BO->getRHS());
11329       if (LHS && LHS->getValue() == 0)
11330         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
11331       else if (!E->isValueDependent() && LHS && RHS &&
11332                RHS->getValue().isNonNegative() &&
11333                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
11334         S.Diag(ExprLoc, diag::warn_left_shift_always)
11335             << (Result.Val.getInt() != 0);
11336       else if (E->getType()->isSignedIntegerType())
11337         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
11338     }
11339   }
11340 
11341   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11342     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
11343     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
11344     if (!LHS || !RHS)
11345       return;
11346     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
11347         (RHS->getValue() == 0 || RHS->getValue() == 1))
11348       // Do not diagnose common idioms.
11349       return;
11350     if (LHS->getValue() != 0 && RHS->getValue() != 0)
11351       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
11352   }
11353 }
11354 
11355 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
11356                                     SourceLocation CC,
11357                                     bool *ICContext = nullptr,
11358                                     bool IsListInit = false) {
11359   if (E->isTypeDependent() || E->isValueDependent()) return;
11360 
11361   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
11362   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
11363   if (Source == Target) return;
11364   if (Target->isDependentType()) return;
11365 
11366   // If the conversion context location is invalid don't complain. We also
11367   // don't want to emit a warning if the issue occurs from the expansion of
11368   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
11369   // delay this check as long as possible. Once we detect we are in that
11370   // scenario, we just return.
11371   if (CC.isInvalid())
11372     return;
11373 
11374   if (Source->isAtomicType())
11375     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
11376 
11377   // Diagnose implicit casts to bool.
11378   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
11379     if (isa<StringLiteral>(E))
11380       // Warn on string literal to bool.  Checks for string literals in logical
11381       // and expressions, for instance, assert(0 && "error here"), are
11382       // prevented by a check in AnalyzeImplicitConversions().
11383       return DiagnoseImpCast(S, E, T, CC,
11384                              diag::warn_impcast_string_literal_to_bool);
11385     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
11386         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
11387       // This covers the literal expressions that evaluate to Objective-C
11388       // objects.
11389       return DiagnoseImpCast(S, E, T, CC,
11390                              diag::warn_impcast_objective_c_literal_to_bool);
11391     }
11392     if (Source->isPointerType() || Source->canDecayToPointerType()) {
11393       // Warn on pointer to bool conversion that is always true.
11394       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
11395                                      SourceRange(CC));
11396     }
11397   }
11398 
11399   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
11400   // is a typedef for signed char (macOS), then that constant value has to be 1
11401   // or 0.
11402   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
11403     Expr::EvalResult Result;
11404     if (E->EvaluateAsInt(Result, S.getASTContext(),
11405                          Expr::SE_AllowSideEffects)) {
11406       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
11407         adornObjCBoolConversionDiagWithTernaryFixit(
11408             S, E,
11409             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
11410                 << Result.Val.getInt().toString(10));
11411       }
11412       return;
11413     }
11414   }
11415 
11416   // Check implicit casts from Objective-C collection literals to specialized
11417   // collection types, e.g., NSArray<NSString *> *.
11418   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
11419     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
11420   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
11421     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
11422 
11423   // Strip vector types.
11424   if (isa<VectorType>(Source)) {
11425     if (!isa<VectorType>(Target)) {
11426       if (S.SourceMgr.isInSystemMacro(CC))
11427         return;
11428       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
11429     }
11430 
11431     // If the vector cast is cast between two vectors of the same size, it is
11432     // a bitcast, not a conversion.
11433     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
11434       return;
11435 
11436     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
11437     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
11438   }
11439   if (auto VecTy = dyn_cast<VectorType>(Target))
11440     Target = VecTy->getElementType().getTypePtr();
11441 
11442   // Strip complex types.
11443   if (isa<ComplexType>(Source)) {
11444     if (!isa<ComplexType>(Target)) {
11445       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
11446         return;
11447 
11448       return DiagnoseImpCast(S, E, T, CC,
11449                              S.getLangOpts().CPlusPlus
11450                                  ? diag::err_impcast_complex_scalar
11451                                  : diag::warn_impcast_complex_scalar);
11452     }
11453 
11454     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
11455     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
11456   }
11457 
11458   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
11459   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
11460 
11461   // If the source is floating point...
11462   if (SourceBT && SourceBT->isFloatingPoint()) {
11463     // ...and the target is floating point...
11464     if (TargetBT && TargetBT->isFloatingPoint()) {
11465       // ...then warn if we're dropping FP rank.
11466 
11467       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11468           QualType(SourceBT, 0), QualType(TargetBT, 0));
11469       if (Order > 0) {
11470         // Don't warn about float constants that are precisely
11471         // representable in the target type.
11472         Expr::EvalResult result;
11473         if (E->EvaluateAsRValue(result, S.Context)) {
11474           // Value might be a float, a float vector, or a float complex.
11475           if (IsSameFloatAfterCast(result.Val,
11476                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
11477                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
11478             return;
11479         }
11480 
11481         if (S.SourceMgr.isInSystemMacro(CC))
11482           return;
11483 
11484         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
11485       }
11486       // ... or possibly if we're increasing rank, too
11487       else if (Order < 0) {
11488         if (S.SourceMgr.isInSystemMacro(CC))
11489           return;
11490 
11491         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
11492       }
11493       return;
11494     }
11495 
11496     // If the target is integral, always warn.
11497     if (TargetBT && TargetBT->isInteger()) {
11498       if (S.SourceMgr.isInSystemMacro(CC))
11499         return;
11500 
11501       DiagnoseFloatingImpCast(S, E, T, CC);
11502     }
11503 
11504     // Detect the case where a call result is converted from floating-point to
11505     // to bool, and the final argument to the call is converted from bool, to
11506     // discover this typo:
11507     //
11508     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
11509     //
11510     // FIXME: This is an incredibly special case; is there some more general
11511     // way to detect this class of misplaced-parentheses bug?
11512     if (Target->isBooleanType() && isa<CallExpr>(E)) {
11513       // Check last argument of function call to see if it is an
11514       // implicit cast from a type matching the type the result
11515       // is being cast to.
11516       CallExpr *CEx = cast<CallExpr>(E);
11517       if (unsigned NumArgs = CEx->getNumArgs()) {
11518         Expr *LastA = CEx->getArg(NumArgs - 1);
11519         Expr *InnerE = LastA->IgnoreParenImpCasts();
11520         if (isa<ImplicitCastExpr>(LastA) &&
11521             InnerE->getType()->isBooleanType()) {
11522           // Warn on this floating-point to bool conversion
11523           DiagnoseImpCast(S, E, T, CC,
11524                           diag::warn_impcast_floating_point_to_bool);
11525         }
11526       }
11527     }
11528     return;
11529   }
11530 
11531   // Valid casts involving fixed point types should be accounted for here.
11532   if (Source->isFixedPointType()) {
11533     if (Target->isUnsaturatedFixedPointType()) {
11534       Expr::EvalResult Result;
11535       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
11536                                   S.isConstantEvaluated())) {
11537         APFixedPoint Value = Result.Val.getFixedPoint();
11538         APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
11539         APFixedPoint MinVal = S.Context.getFixedPointMin(T);
11540         if (Value > MaxVal || Value < MinVal) {
11541           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11542                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11543                                     << Value.toString() << T
11544                                     << E->getSourceRange()
11545                                     << clang::SourceRange(CC));
11546           return;
11547         }
11548       }
11549     } else if (Target->isIntegerType()) {
11550       Expr::EvalResult Result;
11551       if (!S.isConstantEvaluated() &&
11552           E->EvaluateAsFixedPoint(Result, S.Context,
11553                                   Expr::SE_AllowSideEffects)) {
11554         APFixedPoint FXResult = Result.Val.getFixedPoint();
11555 
11556         bool Overflowed;
11557         llvm::APSInt IntResult = FXResult.convertToInt(
11558             S.Context.getIntWidth(T),
11559             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
11560 
11561         if (Overflowed) {
11562           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11563                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11564                                     << FXResult.toString() << T
11565                                     << E->getSourceRange()
11566                                     << clang::SourceRange(CC));
11567           return;
11568         }
11569       }
11570     }
11571   } else if (Target->isUnsaturatedFixedPointType()) {
11572     if (Source->isIntegerType()) {
11573       Expr::EvalResult Result;
11574       if (!S.isConstantEvaluated() &&
11575           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
11576         llvm::APSInt Value = Result.Val.getInt();
11577 
11578         bool Overflowed;
11579         APFixedPoint IntResult = APFixedPoint::getFromIntValue(
11580             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
11581 
11582         if (Overflowed) {
11583           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11584                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11585                                     << Value.toString(/*Radix=*/10) << T
11586                                     << E->getSourceRange()
11587                                     << clang::SourceRange(CC));
11588           return;
11589         }
11590       }
11591     }
11592   }
11593 
11594   // If we are casting an integer type to a floating point type without
11595   // initialization-list syntax, we might lose accuracy if the floating
11596   // point type has a narrower significand than the integer type.
11597   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
11598       TargetBT->isFloatingType() && !IsListInit) {
11599     // Determine the number of precision bits in the source integer type.
11600     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated());
11601     unsigned int SourcePrecision = SourceRange.Width;
11602 
11603     // Determine the number of precision bits in the
11604     // target floating point type.
11605     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
11606         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
11607 
11608     if (SourcePrecision > 0 && TargetPrecision > 0 &&
11609         SourcePrecision > TargetPrecision) {
11610 
11611       llvm::APSInt SourceInt;
11612       if (E->isIntegerConstantExpr(SourceInt, S.Context)) {
11613         // If the source integer is a constant, convert it to the target
11614         // floating point type. Issue a warning if the value changes
11615         // during the whole conversion.
11616         llvm::APFloat TargetFloatValue(
11617             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
11618         llvm::APFloat::opStatus ConversionStatus =
11619             TargetFloatValue.convertFromAPInt(
11620                 SourceInt, SourceBT->isSignedInteger(),
11621                 llvm::APFloat::rmNearestTiesToEven);
11622 
11623         if (ConversionStatus != llvm::APFloat::opOK) {
11624           std::string PrettySourceValue = SourceInt.toString(10);
11625           SmallString<32> PrettyTargetValue;
11626           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
11627 
11628           S.DiagRuntimeBehavior(
11629               E->getExprLoc(), E,
11630               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
11631                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
11632                   << E->getSourceRange() << clang::SourceRange(CC));
11633         }
11634       } else {
11635         // Otherwise, the implicit conversion may lose precision.
11636         DiagnoseImpCast(S, E, T, CC,
11637                         diag::warn_impcast_integer_float_precision);
11638       }
11639     }
11640   }
11641 
11642   DiagnoseNullConversion(S, E, T, CC);
11643 
11644   S.DiscardMisalignedMemberAddress(Target, E);
11645 
11646   if (Target->isBooleanType())
11647     DiagnoseIntInBoolContext(S, E);
11648 
11649   if (!Source->isIntegerType() || !Target->isIntegerType())
11650     return;
11651 
11652   // TODO: remove this early return once the false positives for constant->bool
11653   // in templates, macros, etc, are reduced or removed.
11654   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
11655     return;
11656 
11657   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
11658       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
11659     return adornObjCBoolConversionDiagWithTernaryFixit(
11660         S, E,
11661         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
11662             << E->getType());
11663   }
11664 
11665   IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated());
11666   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
11667 
11668   if (SourceRange.Width > TargetRange.Width) {
11669     // If the source is a constant, use a default-on diagnostic.
11670     // TODO: this should happen for bitfield stores, too.
11671     Expr::EvalResult Result;
11672     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
11673                          S.isConstantEvaluated())) {
11674       llvm::APSInt Value(32);
11675       Value = Result.Val.getInt();
11676 
11677       if (S.SourceMgr.isInSystemMacro(CC))
11678         return;
11679 
11680       std::string PrettySourceValue = Value.toString(10);
11681       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11682 
11683       S.DiagRuntimeBehavior(
11684           E->getExprLoc(), E,
11685           S.PDiag(diag::warn_impcast_integer_precision_constant)
11686               << PrettySourceValue << PrettyTargetValue << E->getType() << T
11687               << E->getSourceRange() << clang::SourceRange(CC));
11688       return;
11689     }
11690 
11691     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
11692     if (S.SourceMgr.isInSystemMacro(CC))
11693       return;
11694 
11695     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
11696       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
11697                              /* pruneControlFlow */ true);
11698     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
11699   }
11700 
11701   if (TargetRange.Width > SourceRange.Width) {
11702     if (auto *UO = dyn_cast<UnaryOperator>(E))
11703       if (UO->getOpcode() == UO_Minus)
11704         if (Source->isUnsignedIntegerType()) {
11705           if (Target->isUnsignedIntegerType())
11706             return DiagnoseImpCast(S, E, T, CC,
11707                                    diag::warn_impcast_high_order_zero_bits);
11708           if (Target->isSignedIntegerType())
11709             return DiagnoseImpCast(S, E, T, CC,
11710                                    diag::warn_impcast_nonnegative_result);
11711         }
11712   }
11713 
11714   if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
11715       SourceRange.NonNegative && Source->isSignedIntegerType()) {
11716     // Warn when doing a signed to signed conversion, warn if the positive
11717     // source value is exactly the width of the target type, which will
11718     // cause a negative value to be stored.
11719 
11720     Expr::EvalResult Result;
11721     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
11722         !S.SourceMgr.isInSystemMacro(CC)) {
11723       llvm::APSInt Value = Result.Val.getInt();
11724       if (isSameWidthConstantConversion(S, E, T, CC)) {
11725         std::string PrettySourceValue = Value.toString(10);
11726         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11727 
11728         S.DiagRuntimeBehavior(
11729             E->getExprLoc(), E,
11730             S.PDiag(diag::warn_impcast_integer_precision_constant)
11731                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
11732                 << E->getSourceRange() << clang::SourceRange(CC));
11733         return;
11734       }
11735     }
11736 
11737     // Fall through for non-constants to give a sign conversion warning.
11738   }
11739 
11740   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
11741       (!TargetRange.NonNegative && SourceRange.NonNegative &&
11742        SourceRange.Width == TargetRange.Width)) {
11743     if (S.SourceMgr.isInSystemMacro(CC))
11744       return;
11745 
11746     unsigned DiagID = diag::warn_impcast_integer_sign;
11747 
11748     // Traditionally, gcc has warned about this under -Wsign-compare.
11749     // We also want to warn about it in -Wconversion.
11750     // So if -Wconversion is off, use a completely identical diagnostic
11751     // in the sign-compare group.
11752     // The conditional-checking code will
11753     if (ICContext) {
11754       DiagID = diag::warn_impcast_integer_sign_conditional;
11755       *ICContext = true;
11756     }
11757 
11758     return DiagnoseImpCast(S, E, T, CC, DiagID);
11759   }
11760 
11761   // Diagnose conversions between different enumeration types.
11762   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
11763   // type, to give us better diagnostics.
11764   QualType SourceType = E->getType();
11765   if (!S.getLangOpts().CPlusPlus) {
11766     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11767       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
11768         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
11769         SourceType = S.Context.getTypeDeclType(Enum);
11770         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
11771       }
11772   }
11773 
11774   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
11775     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
11776       if (SourceEnum->getDecl()->hasNameForLinkage() &&
11777           TargetEnum->getDecl()->hasNameForLinkage() &&
11778           SourceEnum != TargetEnum) {
11779         if (S.SourceMgr.isInSystemMacro(CC))
11780           return;
11781 
11782         return DiagnoseImpCast(S, E, SourceType, T, CC,
11783                                diag::warn_impcast_different_enum_types);
11784       }
11785 }
11786 
11787 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11788                                      SourceLocation CC, QualType T);
11789 
11790 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
11791                                     SourceLocation CC, bool &ICContext) {
11792   E = E->IgnoreParenImpCasts();
11793 
11794   if (isa<ConditionalOperator>(E))
11795     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
11796 
11797   AnalyzeImplicitConversions(S, E, CC);
11798   if (E->getType() != T)
11799     return CheckImplicitConversion(S, E, T, CC, &ICContext);
11800 }
11801 
11802 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11803                                      SourceLocation CC, QualType T) {
11804   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
11805 
11806   bool Suspicious = false;
11807   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
11808   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
11809 
11810   if (T->isBooleanType())
11811     DiagnoseIntInBoolContext(S, E);
11812 
11813   // If -Wconversion would have warned about either of the candidates
11814   // for a signedness conversion to the context type...
11815   if (!Suspicious) return;
11816 
11817   // ...but it's currently ignored...
11818   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
11819     return;
11820 
11821   // ...then check whether it would have warned about either of the
11822   // candidates for a signedness conversion to the condition type.
11823   if (E->getType() == T) return;
11824 
11825   Suspicious = false;
11826   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
11827                           E->getType(), CC, &Suspicious);
11828   if (!Suspicious)
11829     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
11830                             E->getType(), CC, &Suspicious);
11831 }
11832 
11833 /// Check conversion of given expression to boolean.
11834 /// Input argument E is a logical expression.
11835 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
11836   if (S.getLangOpts().Bool)
11837     return;
11838   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
11839     return;
11840   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
11841 }
11842 
11843 namespace {
11844 struct AnalyzeImplicitConversionsWorkItem {
11845   Expr *E;
11846   SourceLocation CC;
11847   bool IsListInit;
11848 };
11849 }
11850 
11851 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
11852 /// that should be visited are added to WorkList.
11853 static void AnalyzeImplicitConversions(
11854     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
11855     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
11856   Expr *OrigE = Item.E;
11857   SourceLocation CC = Item.CC;
11858 
11859   QualType T = OrigE->getType();
11860   Expr *E = OrigE->IgnoreParenImpCasts();
11861 
11862   // Propagate whether we are in a C++ list initialization expression.
11863   // If so, we do not issue warnings for implicit int-float conversion
11864   // precision loss, because C++11 narrowing already handles it.
11865   bool IsListInit = Item.IsListInit ||
11866                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
11867 
11868   if (E->isTypeDependent() || E->isValueDependent())
11869     return;
11870 
11871   Expr *SourceExpr = E;
11872   // Examine, but don't traverse into the source expression of an
11873   // OpaqueValueExpr, since it may have multiple parents and we don't want to
11874   // emit duplicate diagnostics. Its fine to examine the form or attempt to
11875   // evaluate it in the context of checking the specific conversion to T though.
11876   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11877     if (auto *Src = OVE->getSourceExpr())
11878       SourceExpr = Src;
11879 
11880   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
11881     if (UO->getOpcode() == UO_Not &&
11882         UO->getSubExpr()->isKnownToHaveBooleanValue())
11883       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
11884           << OrigE->getSourceRange() << T->isBooleanType()
11885           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
11886 
11887   // For conditional operators, we analyze the arguments as if they
11888   // were being fed directly into the output.
11889   if (auto *CO = dyn_cast<ConditionalOperator>(SourceExpr)) {
11890     CheckConditionalOperator(S, CO, CC, T);
11891     return;
11892   }
11893 
11894   // Check implicit argument conversions for function calls.
11895   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
11896     CheckImplicitArgumentConversions(S, Call, CC);
11897 
11898   // Go ahead and check any implicit conversions we might have skipped.
11899   // The non-canonical typecheck is just an optimization;
11900   // CheckImplicitConversion will filter out dead implicit conversions.
11901   if (SourceExpr->getType() != T)
11902     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
11903 
11904   // Now continue drilling into this expression.
11905 
11906   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
11907     // The bound subexpressions in a PseudoObjectExpr are not reachable
11908     // as transitive children.
11909     // FIXME: Use a more uniform representation for this.
11910     for (auto *SE : POE->semantics())
11911       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
11912         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
11913   }
11914 
11915   // Skip past explicit casts.
11916   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
11917     E = CE->getSubExpr()->IgnoreParenImpCasts();
11918     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
11919       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
11920     WorkList.push_back({E, CC, IsListInit});
11921     return;
11922   }
11923 
11924   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11925     // Do a somewhat different check with comparison operators.
11926     if (BO->isComparisonOp())
11927       return AnalyzeComparison(S, BO);
11928 
11929     // And with simple assignments.
11930     if (BO->getOpcode() == BO_Assign)
11931       return AnalyzeAssignment(S, BO);
11932     // And with compound assignments.
11933     if (BO->isAssignmentOp())
11934       return AnalyzeCompoundAssignment(S, BO);
11935   }
11936 
11937   // These break the otherwise-useful invariant below.  Fortunately,
11938   // we don't really need to recurse into them, because any internal
11939   // expressions should have been analyzed already when they were
11940   // built into statements.
11941   if (isa<StmtExpr>(E)) return;
11942 
11943   // Don't descend into unevaluated contexts.
11944   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
11945 
11946   // Now just recurse over the expression's children.
11947   CC = E->getExprLoc();
11948   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
11949   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
11950   for (Stmt *SubStmt : E->children()) {
11951     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
11952     if (!ChildExpr)
11953       continue;
11954 
11955     if (IsLogicalAndOperator &&
11956         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
11957       // Ignore checking string literals that are in logical and operators.
11958       // This is a common pattern for asserts.
11959       continue;
11960     WorkList.push_back({ChildExpr, CC, IsListInit});
11961   }
11962 
11963   if (BO && BO->isLogicalOp()) {
11964     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
11965     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
11966       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
11967 
11968     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
11969     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
11970       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
11971   }
11972 
11973   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
11974     if (U->getOpcode() == UO_LNot) {
11975       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
11976     } else if (U->getOpcode() != UO_AddrOf) {
11977       if (U->getSubExpr()->getType()->isAtomicType())
11978         S.Diag(U->getSubExpr()->getBeginLoc(),
11979                diag::warn_atomic_implicit_seq_cst);
11980     }
11981   }
11982 }
11983 
11984 /// AnalyzeImplicitConversions - Find and report any interesting
11985 /// implicit conversions in the given expression.  There are a couple
11986 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
11987 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
11988                                        bool IsListInit/*= false*/) {
11989   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
11990   WorkList.push_back({OrigE, CC, IsListInit});
11991   while (!WorkList.empty())
11992     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
11993 }
11994 
11995 /// Diagnose integer type and any valid implicit conversion to it.
11996 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
11997   // Taking into account implicit conversions,
11998   // allow any integer.
11999   if (!E->getType()->isIntegerType()) {
12000     S.Diag(E->getBeginLoc(),
12001            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
12002     return true;
12003   }
12004   // Potentially emit standard warnings for implicit conversions if enabled
12005   // using -Wconversion.
12006   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
12007   return false;
12008 }
12009 
12010 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
12011 // Returns true when emitting a warning about taking the address of a reference.
12012 static bool CheckForReference(Sema &SemaRef, const Expr *E,
12013                               const PartialDiagnostic &PD) {
12014   E = E->IgnoreParenImpCasts();
12015 
12016   const FunctionDecl *FD = nullptr;
12017 
12018   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12019     if (!DRE->getDecl()->getType()->isReferenceType())
12020       return false;
12021   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12022     if (!M->getMemberDecl()->getType()->isReferenceType())
12023       return false;
12024   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
12025     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
12026       return false;
12027     FD = Call->getDirectCallee();
12028   } else {
12029     return false;
12030   }
12031 
12032   SemaRef.Diag(E->getExprLoc(), PD);
12033 
12034   // If possible, point to location of function.
12035   if (FD) {
12036     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
12037   }
12038 
12039   return true;
12040 }
12041 
12042 // Returns true if the SourceLocation is expanded from any macro body.
12043 // Returns false if the SourceLocation is invalid, is from not in a macro
12044 // expansion, or is from expanded from a top-level macro argument.
12045 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
12046   if (Loc.isInvalid())
12047     return false;
12048 
12049   while (Loc.isMacroID()) {
12050     if (SM.isMacroBodyExpansion(Loc))
12051       return true;
12052     Loc = SM.getImmediateMacroCallerLoc(Loc);
12053   }
12054 
12055   return false;
12056 }
12057 
12058 /// Diagnose pointers that are always non-null.
12059 /// \param E the expression containing the pointer
12060 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
12061 /// compared to a null pointer
12062 /// \param IsEqual True when the comparison is equal to a null pointer
12063 /// \param Range Extra SourceRange to highlight in the diagnostic
12064 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
12065                                         Expr::NullPointerConstantKind NullKind,
12066                                         bool IsEqual, SourceRange Range) {
12067   if (!E)
12068     return;
12069 
12070   // Don't warn inside macros.
12071   if (E->getExprLoc().isMacroID()) {
12072     const SourceManager &SM = getSourceManager();
12073     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
12074         IsInAnyMacroBody(SM, Range.getBegin()))
12075       return;
12076   }
12077   E = E->IgnoreImpCasts();
12078 
12079   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
12080 
12081   if (isa<CXXThisExpr>(E)) {
12082     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
12083                                 : diag::warn_this_bool_conversion;
12084     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
12085     return;
12086   }
12087 
12088   bool IsAddressOf = false;
12089 
12090   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12091     if (UO->getOpcode() != UO_AddrOf)
12092       return;
12093     IsAddressOf = true;
12094     E = UO->getSubExpr();
12095   }
12096 
12097   if (IsAddressOf) {
12098     unsigned DiagID = IsCompare
12099                           ? diag::warn_address_of_reference_null_compare
12100                           : diag::warn_address_of_reference_bool_conversion;
12101     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
12102                                          << IsEqual;
12103     if (CheckForReference(*this, E, PD)) {
12104       return;
12105     }
12106   }
12107 
12108   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
12109     bool IsParam = isa<NonNullAttr>(NonnullAttr);
12110     std::string Str;
12111     llvm::raw_string_ostream S(Str);
12112     E->printPretty(S, nullptr, getPrintingPolicy());
12113     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
12114                                 : diag::warn_cast_nonnull_to_bool;
12115     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
12116       << E->getSourceRange() << Range << IsEqual;
12117     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
12118   };
12119 
12120   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
12121   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
12122     if (auto *Callee = Call->getDirectCallee()) {
12123       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
12124         ComplainAboutNonnullParamOrCall(A);
12125         return;
12126       }
12127     }
12128   }
12129 
12130   // Expect to find a single Decl.  Skip anything more complicated.
12131   ValueDecl *D = nullptr;
12132   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
12133     D = R->getDecl();
12134   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12135     D = M->getMemberDecl();
12136   }
12137 
12138   // Weak Decls can be null.
12139   if (!D || D->isWeak())
12140     return;
12141 
12142   // Check for parameter decl with nonnull attribute
12143   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
12144     if (getCurFunction() &&
12145         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
12146       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
12147         ComplainAboutNonnullParamOrCall(A);
12148         return;
12149       }
12150 
12151       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
12152         // Skip function template not specialized yet.
12153         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
12154           return;
12155         auto ParamIter = llvm::find(FD->parameters(), PV);
12156         assert(ParamIter != FD->param_end());
12157         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
12158 
12159         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
12160           if (!NonNull->args_size()) {
12161               ComplainAboutNonnullParamOrCall(NonNull);
12162               return;
12163           }
12164 
12165           for (const ParamIdx &ArgNo : NonNull->args()) {
12166             if (ArgNo.getASTIndex() == ParamNo) {
12167               ComplainAboutNonnullParamOrCall(NonNull);
12168               return;
12169             }
12170           }
12171         }
12172       }
12173     }
12174   }
12175 
12176   QualType T = D->getType();
12177   const bool IsArray = T->isArrayType();
12178   const bool IsFunction = T->isFunctionType();
12179 
12180   // Address of function is used to silence the function warning.
12181   if (IsAddressOf && IsFunction) {
12182     return;
12183   }
12184 
12185   // Found nothing.
12186   if (!IsAddressOf && !IsFunction && !IsArray)
12187     return;
12188 
12189   // Pretty print the expression for the diagnostic.
12190   std::string Str;
12191   llvm::raw_string_ostream S(Str);
12192   E->printPretty(S, nullptr, getPrintingPolicy());
12193 
12194   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
12195                               : diag::warn_impcast_pointer_to_bool;
12196   enum {
12197     AddressOf,
12198     FunctionPointer,
12199     ArrayPointer
12200   } DiagType;
12201   if (IsAddressOf)
12202     DiagType = AddressOf;
12203   else if (IsFunction)
12204     DiagType = FunctionPointer;
12205   else if (IsArray)
12206     DiagType = ArrayPointer;
12207   else
12208     llvm_unreachable("Could not determine diagnostic.");
12209   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
12210                                 << Range << IsEqual;
12211 
12212   if (!IsFunction)
12213     return;
12214 
12215   // Suggest '&' to silence the function warning.
12216   Diag(E->getExprLoc(), diag::note_function_warning_silence)
12217       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
12218 
12219   // Check to see if '()' fixit should be emitted.
12220   QualType ReturnType;
12221   UnresolvedSet<4> NonTemplateOverloads;
12222   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
12223   if (ReturnType.isNull())
12224     return;
12225 
12226   if (IsCompare) {
12227     // There are two cases here.  If there is null constant, the only suggest
12228     // for a pointer return type.  If the null is 0, then suggest if the return
12229     // type is a pointer or an integer type.
12230     if (!ReturnType->isPointerType()) {
12231       if (NullKind == Expr::NPCK_ZeroExpression ||
12232           NullKind == Expr::NPCK_ZeroLiteral) {
12233         if (!ReturnType->isIntegerType())
12234           return;
12235       } else {
12236         return;
12237       }
12238     }
12239   } else { // !IsCompare
12240     // For function to bool, only suggest if the function pointer has bool
12241     // return type.
12242     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
12243       return;
12244   }
12245   Diag(E->getExprLoc(), diag::note_function_to_function_call)
12246       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
12247 }
12248 
12249 /// Diagnoses "dangerous" implicit conversions within the given
12250 /// expression (which is a full expression).  Implements -Wconversion
12251 /// and -Wsign-compare.
12252 ///
12253 /// \param CC the "context" location of the implicit conversion, i.e.
12254 ///   the most location of the syntactic entity requiring the implicit
12255 ///   conversion
12256 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
12257   // Don't diagnose in unevaluated contexts.
12258   if (isUnevaluatedContext())
12259     return;
12260 
12261   // Don't diagnose for value- or type-dependent expressions.
12262   if (E->isTypeDependent() || E->isValueDependent())
12263     return;
12264 
12265   // Check for array bounds violations in cases where the check isn't triggered
12266   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
12267   // ArraySubscriptExpr is on the RHS of a variable initialization.
12268   CheckArrayAccess(E);
12269 
12270   // This is not the right CC for (e.g.) a variable initialization.
12271   AnalyzeImplicitConversions(*this, E, CC);
12272 }
12273 
12274 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
12275 /// Input argument E is a logical expression.
12276 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
12277   ::CheckBoolLikeConversion(*this, E, CC);
12278 }
12279 
12280 /// Diagnose when expression is an integer constant expression and its evaluation
12281 /// results in integer overflow
12282 void Sema::CheckForIntOverflow (Expr *E) {
12283   // Use a work list to deal with nested struct initializers.
12284   SmallVector<Expr *, 2> Exprs(1, E);
12285 
12286   do {
12287     Expr *OriginalE = Exprs.pop_back_val();
12288     Expr *E = OriginalE->IgnoreParenCasts();
12289 
12290     if (isa<BinaryOperator>(E)) {
12291       E->EvaluateForOverflow(Context);
12292       continue;
12293     }
12294 
12295     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
12296       Exprs.append(InitList->inits().begin(), InitList->inits().end());
12297     else if (isa<ObjCBoxedExpr>(OriginalE))
12298       E->EvaluateForOverflow(Context);
12299     else if (auto Call = dyn_cast<CallExpr>(E))
12300       Exprs.append(Call->arg_begin(), Call->arg_end());
12301     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
12302       Exprs.append(Message->arg_begin(), Message->arg_end());
12303   } while (!Exprs.empty());
12304 }
12305 
12306 namespace {
12307 
12308 /// Visitor for expressions which looks for unsequenced operations on the
12309 /// same object.
12310 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
12311   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
12312 
12313   /// A tree of sequenced regions within an expression. Two regions are
12314   /// unsequenced if one is an ancestor or a descendent of the other. When we
12315   /// finish processing an expression with sequencing, such as a comma
12316   /// expression, we fold its tree nodes into its parent, since they are
12317   /// unsequenced with respect to nodes we will visit later.
12318   class SequenceTree {
12319     struct Value {
12320       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
12321       unsigned Parent : 31;
12322       unsigned Merged : 1;
12323     };
12324     SmallVector<Value, 8> Values;
12325 
12326   public:
12327     /// A region within an expression which may be sequenced with respect
12328     /// to some other region.
12329     class Seq {
12330       friend class SequenceTree;
12331 
12332       unsigned Index;
12333 
12334       explicit Seq(unsigned N) : Index(N) {}
12335 
12336     public:
12337       Seq() : Index(0) {}
12338     };
12339 
12340     SequenceTree() { Values.push_back(Value(0)); }
12341     Seq root() const { return Seq(0); }
12342 
12343     /// Create a new sequence of operations, which is an unsequenced
12344     /// subset of \p Parent. This sequence of operations is sequenced with
12345     /// respect to other children of \p Parent.
12346     Seq allocate(Seq Parent) {
12347       Values.push_back(Value(Parent.Index));
12348       return Seq(Values.size() - 1);
12349     }
12350 
12351     /// Merge a sequence of operations into its parent.
12352     void merge(Seq S) {
12353       Values[S.Index].Merged = true;
12354     }
12355 
12356     /// Determine whether two operations are unsequenced. This operation
12357     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
12358     /// should have been merged into its parent as appropriate.
12359     bool isUnsequenced(Seq Cur, Seq Old) {
12360       unsigned C = representative(Cur.Index);
12361       unsigned Target = representative(Old.Index);
12362       while (C >= Target) {
12363         if (C == Target)
12364           return true;
12365         C = Values[C].Parent;
12366       }
12367       return false;
12368     }
12369 
12370   private:
12371     /// Pick a representative for a sequence.
12372     unsigned representative(unsigned K) {
12373       if (Values[K].Merged)
12374         // Perform path compression as we go.
12375         return Values[K].Parent = representative(Values[K].Parent);
12376       return K;
12377     }
12378   };
12379 
12380   /// An object for which we can track unsequenced uses.
12381   using Object = const NamedDecl *;
12382 
12383   /// Different flavors of object usage which we track. We only track the
12384   /// least-sequenced usage of each kind.
12385   enum UsageKind {
12386     /// A read of an object. Multiple unsequenced reads are OK.
12387     UK_Use,
12388 
12389     /// A modification of an object which is sequenced before the value
12390     /// computation of the expression, such as ++n in C++.
12391     UK_ModAsValue,
12392 
12393     /// A modification of an object which is not sequenced before the value
12394     /// computation of the expression, such as n++.
12395     UK_ModAsSideEffect,
12396 
12397     UK_Count = UK_ModAsSideEffect + 1
12398   };
12399 
12400   /// Bundle together a sequencing region and the expression corresponding
12401   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
12402   struct Usage {
12403     const Expr *UsageExpr;
12404     SequenceTree::Seq Seq;
12405 
12406     Usage() : UsageExpr(nullptr), Seq() {}
12407   };
12408 
12409   struct UsageInfo {
12410     Usage Uses[UK_Count];
12411 
12412     /// Have we issued a diagnostic for this object already?
12413     bool Diagnosed;
12414 
12415     UsageInfo() : Uses(), Diagnosed(false) {}
12416   };
12417   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
12418 
12419   Sema &SemaRef;
12420 
12421   /// Sequenced regions within the expression.
12422   SequenceTree Tree;
12423 
12424   /// Declaration modifications and references which we have seen.
12425   UsageInfoMap UsageMap;
12426 
12427   /// The region we are currently within.
12428   SequenceTree::Seq Region;
12429 
12430   /// Filled in with declarations which were modified as a side-effect
12431   /// (that is, post-increment operations).
12432   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
12433 
12434   /// Expressions to check later. We defer checking these to reduce
12435   /// stack usage.
12436   SmallVectorImpl<const Expr *> &WorkList;
12437 
12438   /// RAII object wrapping the visitation of a sequenced subexpression of an
12439   /// expression. At the end of this process, the side-effects of the evaluation
12440   /// become sequenced with respect to the value computation of the result, so
12441   /// we downgrade any UK_ModAsSideEffect within the evaluation to
12442   /// UK_ModAsValue.
12443   struct SequencedSubexpression {
12444     SequencedSubexpression(SequenceChecker &Self)
12445       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
12446       Self.ModAsSideEffect = &ModAsSideEffect;
12447     }
12448 
12449     ~SequencedSubexpression() {
12450       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
12451         // Add a new usage with usage kind UK_ModAsValue, and then restore
12452         // the previous usage with UK_ModAsSideEffect (thus clearing it if
12453         // the previous one was empty).
12454         UsageInfo &UI = Self.UsageMap[M.first];
12455         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
12456         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
12457         SideEffectUsage = M.second;
12458       }
12459       Self.ModAsSideEffect = OldModAsSideEffect;
12460     }
12461 
12462     SequenceChecker &Self;
12463     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
12464     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
12465   };
12466 
12467   /// RAII object wrapping the visitation of a subexpression which we might
12468   /// choose to evaluate as a constant. If any subexpression is evaluated and
12469   /// found to be non-constant, this allows us to suppress the evaluation of
12470   /// the outer expression.
12471   class EvaluationTracker {
12472   public:
12473     EvaluationTracker(SequenceChecker &Self)
12474         : Self(Self), Prev(Self.EvalTracker) {
12475       Self.EvalTracker = this;
12476     }
12477 
12478     ~EvaluationTracker() {
12479       Self.EvalTracker = Prev;
12480       if (Prev)
12481         Prev->EvalOK &= EvalOK;
12482     }
12483 
12484     bool evaluate(const Expr *E, bool &Result) {
12485       if (!EvalOK || E->isValueDependent())
12486         return false;
12487       EvalOK = E->EvaluateAsBooleanCondition(
12488           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
12489       return EvalOK;
12490     }
12491 
12492   private:
12493     SequenceChecker &Self;
12494     EvaluationTracker *Prev;
12495     bool EvalOK = true;
12496   } *EvalTracker = nullptr;
12497 
12498   /// Find the object which is produced by the specified expression,
12499   /// if any.
12500   Object getObject(const Expr *E, bool Mod) const {
12501     E = E->IgnoreParenCasts();
12502     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12503       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
12504         return getObject(UO->getSubExpr(), Mod);
12505     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12506       if (BO->getOpcode() == BO_Comma)
12507         return getObject(BO->getRHS(), Mod);
12508       if (Mod && BO->isAssignmentOp())
12509         return getObject(BO->getLHS(), Mod);
12510     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12511       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
12512       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
12513         return ME->getMemberDecl();
12514     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12515       // FIXME: If this is a reference, map through to its value.
12516       return DRE->getDecl();
12517     return nullptr;
12518   }
12519 
12520   /// Note that an object \p O was modified or used by an expression
12521   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
12522   /// the object \p O as obtained via the \p UsageMap.
12523   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
12524     // Get the old usage for the given object and usage kind.
12525     Usage &U = UI.Uses[UK];
12526     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
12527       // If we have a modification as side effect and are in a sequenced
12528       // subexpression, save the old Usage so that we can restore it later
12529       // in SequencedSubexpression::~SequencedSubexpression.
12530       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
12531         ModAsSideEffect->push_back(std::make_pair(O, U));
12532       // Then record the new usage with the current sequencing region.
12533       U.UsageExpr = UsageExpr;
12534       U.Seq = Region;
12535     }
12536   }
12537 
12538   /// Check whether a modification or use of an object \p O in an expression
12539   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
12540   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
12541   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
12542   /// usage and false we are checking for a mod-use unsequenced usage.
12543   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
12544                   UsageKind OtherKind, bool IsModMod) {
12545     if (UI.Diagnosed)
12546       return;
12547 
12548     const Usage &U = UI.Uses[OtherKind];
12549     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
12550       return;
12551 
12552     const Expr *Mod = U.UsageExpr;
12553     const Expr *ModOrUse = UsageExpr;
12554     if (OtherKind == UK_Use)
12555       std::swap(Mod, ModOrUse);
12556 
12557     SemaRef.DiagRuntimeBehavior(
12558         Mod->getExprLoc(), {Mod, ModOrUse},
12559         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
12560                                : diag::warn_unsequenced_mod_use)
12561             << O << SourceRange(ModOrUse->getExprLoc()));
12562     UI.Diagnosed = true;
12563   }
12564 
12565   // A note on note{Pre, Post}{Use, Mod}:
12566   //
12567   // (It helps to follow the algorithm with an expression such as
12568   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
12569   //  operations before C++17 and both are well-defined in C++17).
12570   //
12571   // When visiting a node which uses/modify an object we first call notePreUse
12572   // or notePreMod before visiting its sub-expression(s). At this point the
12573   // children of the current node have not yet been visited and so the eventual
12574   // uses/modifications resulting from the children of the current node have not
12575   // been recorded yet.
12576   //
12577   // We then visit the children of the current node. After that notePostUse or
12578   // notePostMod is called. These will 1) detect an unsequenced modification
12579   // as side effect (as in "k++ + k") and 2) add a new usage with the
12580   // appropriate usage kind.
12581   //
12582   // We also have to be careful that some operation sequences modification as
12583   // side effect as well (for example: || or ,). To account for this we wrap
12584   // the visitation of such a sub-expression (for example: the LHS of || or ,)
12585   // with SequencedSubexpression. SequencedSubexpression is an RAII object
12586   // which record usages which are modifications as side effect, and then
12587   // downgrade them (or more accurately restore the previous usage which was a
12588   // modification as side effect) when exiting the scope of the sequenced
12589   // subexpression.
12590 
12591   void notePreUse(Object O, const Expr *UseExpr) {
12592     UsageInfo &UI = UsageMap[O];
12593     // Uses conflict with other modifications.
12594     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
12595   }
12596 
12597   void notePostUse(Object O, const Expr *UseExpr) {
12598     UsageInfo &UI = UsageMap[O];
12599     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
12600                /*IsModMod=*/false);
12601     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
12602   }
12603 
12604   void notePreMod(Object O, const Expr *ModExpr) {
12605     UsageInfo &UI = UsageMap[O];
12606     // Modifications conflict with other modifications and with uses.
12607     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
12608     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
12609   }
12610 
12611   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
12612     UsageInfo &UI = UsageMap[O];
12613     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
12614                /*IsModMod=*/true);
12615     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
12616   }
12617 
12618 public:
12619   SequenceChecker(Sema &S, const Expr *E,
12620                   SmallVectorImpl<const Expr *> &WorkList)
12621       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
12622     Visit(E);
12623     // Silence a -Wunused-private-field since WorkList is now unused.
12624     // TODO: Evaluate if it can be used, and if not remove it.
12625     (void)this->WorkList;
12626   }
12627 
12628   void VisitStmt(const Stmt *S) {
12629     // Skip all statements which aren't expressions for now.
12630   }
12631 
12632   void VisitExpr(const Expr *E) {
12633     // By default, just recurse to evaluated subexpressions.
12634     Base::VisitStmt(E);
12635   }
12636 
12637   void VisitCastExpr(const CastExpr *E) {
12638     Object O = Object();
12639     if (E->getCastKind() == CK_LValueToRValue)
12640       O = getObject(E->getSubExpr(), false);
12641 
12642     if (O)
12643       notePreUse(O, E);
12644     VisitExpr(E);
12645     if (O)
12646       notePostUse(O, E);
12647   }
12648 
12649   void VisitSequencedExpressions(const Expr *SequencedBefore,
12650                                  const Expr *SequencedAfter) {
12651     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
12652     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
12653     SequenceTree::Seq OldRegion = Region;
12654 
12655     {
12656       SequencedSubexpression SeqBefore(*this);
12657       Region = BeforeRegion;
12658       Visit(SequencedBefore);
12659     }
12660 
12661     Region = AfterRegion;
12662     Visit(SequencedAfter);
12663 
12664     Region = OldRegion;
12665 
12666     Tree.merge(BeforeRegion);
12667     Tree.merge(AfterRegion);
12668   }
12669 
12670   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
12671     // C++17 [expr.sub]p1:
12672     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
12673     //   expression E1 is sequenced before the expression E2.
12674     if (SemaRef.getLangOpts().CPlusPlus17)
12675       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
12676     else {
12677       Visit(ASE->getLHS());
12678       Visit(ASE->getRHS());
12679     }
12680   }
12681 
12682   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
12683   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
12684   void VisitBinPtrMem(const BinaryOperator *BO) {
12685     // C++17 [expr.mptr.oper]p4:
12686     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
12687     //  the expression E1 is sequenced before the expression E2.
12688     if (SemaRef.getLangOpts().CPlusPlus17)
12689       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12690     else {
12691       Visit(BO->getLHS());
12692       Visit(BO->getRHS());
12693     }
12694   }
12695 
12696   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
12697   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
12698   void VisitBinShlShr(const BinaryOperator *BO) {
12699     // C++17 [expr.shift]p4:
12700     //  The expression E1 is sequenced before the expression E2.
12701     if (SemaRef.getLangOpts().CPlusPlus17)
12702       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12703     else {
12704       Visit(BO->getLHS());
12705       Visit(BO->getRHS());
12706     }
12707   }
12708 
12709   void VisitBinComma(const BinaryOperator *BO) {
12710     // C++11 [expr.comma]p1:
12711     //   Every value computation and side effect associated with the left
12712     //   expression is sequenced before every value computation and side
12713     //   effect associated with the right expression.
12714     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12715   }
12716 
12717   void VisitBinAssign(const BinaryOperator *BO) {
12718     SequenceTree::Seq RHSRegion;
12719     SequenceTree::Seq LHSRegion;
12720     if (SemaRef.getLangOpts().CPlusPlus17) {
12721       RHSRegion = Tree.allocate(Region);
12722       LHSRegion = Tree.allocate(Region);
12723     } else {
12724       RHSRegion = Region;
12725       LHSRegion = Region;
12726     }
12727     SequenceTree::Seq OldRegion = Region;
12728 
12729     // C++11 [expr.ass]p1:
12730     //  [...] the assignment is sequenced after the value computation
12731     //  of the right and left operands, [...]
12732     //
12733     // so check it before inspecting the operands and update the
12734     // map afterwards.
12735     Object O = getObject(BO->getLHS(), /*Mod=*/true);
12736     if (O)
12737       notePreMod(O, BO);
12738 
12739     if (SemaRef.getLangOpts().CPlusPlus17) {
12740       // C++17 [expr.ass]p1:
12741       //  [...] The right operand is sequenced before the left operand. [...]
12742       {
12743         SequencedSubexpression SeqBefore(*this);
12744         Region = RHSRegion;
12745         Visit(BO->getRHS());
12746       }
12747 
12748       Region = LHSRegion;
12749       Visit(BO->getLHS());
12750 
12751       if (O && isa<CompoundAssignOperator>(BO))
12752         notePostUse(O, BO);
12753 
12754     } else {
12755       // C++11 does not specify any sequencing between the LHS and RHS.
12756       Region = LHSRegion;
12757       Visit(BO->getLHS());
12758 
12759       if (O && isa<CompoundAssignOperator>(BO))
12760         notePostUse(O, BO);
12761 
12762       Region = RHSRegion;
12763       Visit(BO->getRHS());
12764     }
12765 
12766     // C++11 [expr.ass]p1:
12767     //  the assignment is sequenced [...] before the value computation of the
12768     //  assignment expression.
12769     // C11 6.5.16/3 has no such rule.
12770     Region = OldRegion;
12771     if (O)
12772       notePostMod(O, BO,
12773                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12774                                                   : UK_ModAsSideEffect);
12775     if (SemaRef.getLangOpts().CPlusPlus17) {
12776       Tree.merge(RHSRegion);
12777       Tree.merge(LHSRegion);
12778     }
12779   }
12780 
12781   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
12782     VisitBinAssign(CAO);
12783   }
12784 
12785   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12786   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12787   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
12788     Object O = getObject(UO->getSubExpr(), true);
12789     if (!O)
12790       return VisitExpr(UO);
12791 
12792     notePreMod(O, UO);
12793     Visit(UO->getSubExpr());
12794     // C++11 [expr.pre.incr]p1:
12795     //   the expression ++x is equivalent to x+=1
12796     notePostMod(O, UO,
12797                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12798                                                 : UK_ModAsSideEffect);
12799   }
12800 
12801   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12802   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12803   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
12804     Object O = getObject(UO->getSubExpr(), true);
12805     if (!O)
12806       return VisitExpr(UO);
12807 
12808     notePreMod(O, UO);
12809     Visit(UO->getSubExpr());
12810     notePostMod(O, UO, UK_ModAsSideEffect);
12811   }
12812 
12813   void VisitBinLOr(const BinaryOperator *BO) {
12814     // C++11 [expr.log.or]p2:
12815     //  If the second expression is evaluated, every value computation and
12816     //  side effect associated with the first expression is sequenced before
12817     //  every value computation and side effect associated with the
12818     //  second expression.
12819     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
12820     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
12821     SequenceTree::Seq OldRegion = Region;
12822 
12823     EvaluationTracker Eval(*this);
12824     {
12825       SequencedSubexpression Sequenced(*this);
12826       Region = LHSRegion;
12827       Visit(BO->getLHS());
12828     }
12829 
12830     // C++11 [expr.log.or]p1:
12831     //  [...] the second operand is not evaluated if the first operand
12832     //  evaluates to true.
12833     bool EvalResult = false;
12834     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
12835     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
12836     if (ShouldVisitRHS) {
12837       Region = RHSRegion;
12838       Visit(BO->getRHS());
12839     }
12840 
12841     Region = OldRegion;
12842     Tree.merge(LHSRegion);
12843     Tree.merge(RHSRegion);
12844   }
12845 
12846   void VisitBinLAnd(const BinaryOperator *BO) {
12847     // C++11 [expr.log.and]p2:
12848     //  If the second expression is evaluated, every value computation and
12849     //  side effect associated with the first expression is sequenced before
12850     //  every value computation and side effect associated with the
12851     //  second expression.
12852     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
12853     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
12854     SequenceTree::Seq OldRegion = Region;
12855 
12856     EvaluationTracker Eval(*this);
12857     {
12858       SequencedSubexpression Sequenced(*this);
12859       Region = LHSRegion;
12860       Visit(BO->getLHS());
12861     }
12862 
12863     // C++11 [expr.log.and]p1:
12864     //  [...] the second operand is not evaluated if the first operand is false.
12865     bool EvalResult = false;
12866     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
12867     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
12868     if (ShouldVisitRHS) {
12869       Region = RHSRegion;
12870       Visit(BO->getRHS());
12871     }
12872 
12873     Region = OldRegion;
12874     Tree.merge(LHSRegion);
12875     Tree.merge(RHSRegion);
12876   }
12877 
12878   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
12879     // C++11 [expr.cond]p1:
12880     //  [...] Every value computation and side effect associated with the first
12881     //  expression is sequenced before every value computation and side effect
12882     //  associated with the second or third expression.
12883     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
12884 
12885     // No sequencing is specified between the true and false expression.
12886     // However since exactly one of both is going to be evaluated we can
12887     // consider them to be sequenced. This is needed to avoid warning on
12888     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
12889     // both the true and false expressions because we can't evaluate x.
12890     // This will still allow us to detect an expression like (pre C++17)
12891     // "(x ? y += 1 : y += 2) = y".
12892     //
12893     // We don't wrap the visitation of the true and false expression with
12894     // SequencedSubexpression because we don't want to downgrade modifications
12895     // as side effect in the true and false expressions after the visition
12896     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
12897     // not warn between the two "y++", but we should warn between the "y++"
12898     // and the "y".
12899     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
12900     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
12901     SequenceTree::Seq OldRegion = Region;
12902 
12903     EvaluationTracker Eval(*this);
12904     {
12905       SequencedSubexpression Sequenced(*this);
12906       Region = ConditionRegion;
12907       Visit(CO->getCond());
12908     }
12909 
12910     // C++11 [expr.cond]p1:
12911     // [...] The first expression is contextually converted to bool (Clause 4).
12912     // It is evaluated and if it is true, the result of the conditional
12913     // expression is the value of the second expression, otherwise that of the
12914     // third expression. Only one of the second and third expressions is
12915     // evaluated. [...]
12916     bool EvalResult = false;
12917     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
12918     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
12919     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
12920     if (ShouldVisitTrueExpr) {
12921       Region = TrueRegion;
12922       Visit(CO->getTrueExpr());
12923     }
12924     if (ShouldVisitFalseExpr) {
12925       Region = FalseRegion;
12926       Visit(CO->getFalseExpr());
12927     }
12928 
12929     Region = OldRegion;
12930     Tree.merge(ConditionRegion);
12931     Tree.merge(TrueRegion);
12932     Tree.merge(FalseRegion);
12933   }
12934 
12935   void VisitCallExpr(const CallExpr *CE) {
12936     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
12937 
12938     if (CE->isUnevaluatedBuiltinCall(Context))
12939       return;
12940 
12941     // C++11 [intro.execution]p15:
12942     //   When calling a function [...], every value computation and side effect
12943     //   associated with any argument expression, or with the postfix expression
12944     //   designating the called function, is sequenced before execution of every
12945     //   expression or statement in the body of the function [and thus before
12946     //   the value computation of its result].
12947     SequencedSubexpression Sequenced(*this);
12948     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
12949       // C++17 [expr.call]p5
12950       //   The postfix-expression is sequenced before each expression in the
12951       //   expression-list and any default argument. [...]
12952       SequenceTree::Seq CalleeRegion;
12953       SequenceTree::Seq OtherRegion;
12954       if (SemaRef.getLangOpts().CPlusPlus17) {
12955         CalleeRegion = Tree.allocate(Region);
12956         OtherRegion = Tree.allocate(Region);
12957       } else {
12958         CalleeRegion = Region;
12959         OtherRegion = Region;
12960       }
12961       SequenceTree::Seq OldRegion = Region;
12962 
12963       // Visit the callee expression first.
12964       Region = CalleeRegion;
12965       if (SemaRef.getLangOpts().CPlusPlus17) {
12966         SequencedSubexpression Sequenced(*this);
12967         Visit(CE->getCallee());
12968       } else {
12969         Visit(CE->getCallee());
12970       }
12971 
12972       // Then visit the argument expressions.
12973       Region = OtherRegion;
12974       for (const Expr *Argument : CE->arguments())
12975         Visit(Argument);
12976 
12977       Region = OldRegion;
12978       if (SemaRef.getLangOpts().CPlusPlus17) {
12979         Tree.merge(CalleeRegion);
12980         Tree.merge(OtherRegion);
12981       }
12982     });
12983   }
12984 
12985   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
12986     // This is a call, so all subexpressions are sequenced before the result.
12987     SequencedSubexpression Sequenced(*this);
12988 
12989     if (!CCE->isListInitialization())
12990       return VisitExpr(CCE);
12991 
12992     // In C++11, list initializations are sequenced.
12993     SmallVector<SequenceTree::Seq, 32> Elts;
12994     SequenceTree::Seq Parent = Region;
12995     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
12996                                               E = CCE->arg_end();
12997          I != E; ++I) {
12998       Region = Tree.allocate(Parent);
12999       Elts.push_back(Region);
13000       Visit(*I);
13001     }
13002 
13003     // Forget that the initializers are sequenced.
13004     Region = Parent;
13005     for (unsigned I = 0; I < Elts.size(); ++I)
13006       Tree.merge(Elts[I]);
13007   }
13008 
13009   void VisitInitListExpr(const InitListExpr *ILE) {
13010     if (!SemaRef.getLangOpts().CPlusPlus11)
13011       return VisitExpr(ILE);
13012 
13013     // In C++11, list initializations are sequenced.
13014     SmallVector<SequenceTree::Seq, 32> Elts;
13015     SequenceTree::Seq Parent = Region;
13016     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
13017       const Expr *E = ILE->getInit(I);
13018       if (!E)
13019         continue;
13020       Region = Tree.allocate(Parent);
13021       Elts.push_back(Region);
13022       Visit(E);
13023     }
13024 
13025     // Forget that the initializers are sequenced.
13026     Region = Parent;
13027     for (unsigned I = 0; I < Elts.size(); ++I)
13028       Tree.merge(Elts[I]);
13029   }
13030 };
13031 
13032 } // namespace
13033 
13034 void Sema::CheckUnsequencedOperations(const Expr *E) {
13035   SmallVector<const Expr *, 8> WorkList;
13036   WorkList.push_back(E);
13037   while (!WorkList.empty()) {
13038     const Expr *Item = WorkList.pop_back_val();
13039     SequenceChecker(*this, Item, WorkList);
13040   }
13041 }
13042 
13043 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
13044                               bool IsConstexpr) {
13045   llvm::SaveAndRestore<bool> ConstantContext(
13046       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
13047   CheckImplicitConversions(E, CheckLoc);
13048   if (!E->isInstantiationDependent())
13049     CheckUnsequencedOperations(E);
13050   if (!IsConstexpr && !E->isValueDependent())
13051     CheckForIntOverflow(E);
13052   DiagnoseMisalignedMembers();
13053 }
13054 
13055 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
13056                                        FieldDecl *BitField,
13057                                        Expr *Init) {
13058   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
13059 }
13060 
13061 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
13062                                          SourceLocation Loc) {
13063   if (!PType->isVariablyModifiedType())
13064     return;
13065   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
13066     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
13067     return;
13068   }
13069   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
13070     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
13071     return;
13072   }
13073   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
13074     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
13075     return;
13076   }
13077 
13078   const ArrayType *AT = S.Context.getAsArrayType(PType);
13079   if (!AT)
13080     return;
13081 
13082   if (AT->getSizeModifier() != ArrayType::Star) {
13083     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
13084     return;
13085   }
13086 
13087   S.Diag(Loc, diag::err_array_star_in_function_definition);
13088 }
13089 
13090 /// CheckParmsForFunctionDef - Check that the parameters of the given
13091 /// function are appropriate for the definition of a function. This
13092 /// takes care of any checks that cannot be performed on the
13093 /// declaration itself, e.g., that the types of each of the function
13094 /// parameters are complete.
13095 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
13096                                     bool CheckParameterNames) {
13097   bool HasInvalidParm = false;
13098   for (ParmVarDecl *Param : Parameters) {
13099     // C99 6.7.5.3p4: the parameters in a parameter type list in a
13100     // function declarator that is part of a function definition of
13101     // that function shall not have incomplete type.
13102     //
13103     // This is also C++ [dcl.fct]p6.
13104     if (!Param->isInvalidDecl() &&
13105         RequireCompleteType(Param->getLocation(), Param->getType(),
13106                             diag::err_typecheck_decl_incomplete_type)) {
13107       Param->setInvalidDecl();
13108       HasInvalidParm = true;
13109     }
13110 
13111     // C99 6.9.1p5: If the declarator includes a parameter type list, the
13112     // declaration of each parameter shall include an identifier.
13113     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
13114         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
13115       // Diagnose this as an extension in C17 and earlier.
13116       if (!getLangOpts().C2x)
13117         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
13118     }
13119 
13120     // C99 6.7.5.3p12:
13121     //   If the function declarator is not part of a definition of that
13122     //   function, parameters may have incomplete type and may use the [*]
13123     //   notation in their sequences of declarator specifiers to specify
13124     //   variable length array types.
13125     QualType PType = Param->getOriginalType();
13126     // FIXME: This diagnostic should point the '[*]' if source-location
13127     // information is added for it.
13128     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
13129 
13130     // If the parameter is a c++ class type and it has to be destructed in the
13131     // callee function, declare the destructor so that it can be called by the
13132     // callee function. Do not perform any direct access check on the dtor here.
13133     if (!Param->isInvalidDecl()) {
13134       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
13135         if (!ClassDecl->isInvalidDecl() &&
13136             !ClassDecl->hasIrrelevantDestructor() &&
13137             !ClassDecl->isDependentContext() &&
13138             ClassDecl->isParamDestroyedInCallee()) {
13139           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
13140           MarkFunctionReferenced(Param->getLocation(), Destructor);
13141           DiagnoseUseOfDecl(Destructor, Param->getLocation());
13142         }
13143       }
13144     }
13145 
13146     // Parameters with the pass_object_size attribute only need to be marked
13147     // constant at function definitions. Because we lack information about
13148     // whether we're on a declaration or definition when we're instantiating the
13149     // attribute, we need to check for constness here.
13150     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
13151       if (!Param->getType().isConstQualified())
13152         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
13153             << Attr->getSpelling() << 1;
13154 
13155     // Check for parameter names shadowing fields from the class.
13156     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
13157       // The owning context for the parameter should be the function, but we
13158       // want to see if this function's declaration context is a record.
13159       DeclContext *DC = Param->getDeclContext();
13160       if (DC && DC->isFunctionOrMethod()) {
13161         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
13162           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
13163                                      RD, /*DeclIsField*/ false);
13164       }
13165     }
13166   }
13167 
13168   return HasInvalidParm;
13169 }
13170 
13171 Optional<std::pair<CharUnits, CharUnits>>
13172 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
13173 
13174 /// Compute the alignment and offset of the base class object given the
13175 /// derived-to-base cast expression and the alignment and offset of the derived
13176 /// class object.
13177 static std::pair<CharUnits, CharUnits>
13178 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
13179                                    CharUnits BaseAlignment, CharUnits Offset,
13180                                    ASTContext &Ctx) {
13181   for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
13182        ++PathI) {
13183     const CXXBaseSpecifier *Base = *PathI;
13184     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
13185     if (Base->isVirtual()) {
13186       // The complete object may have a lower alignment than the non-virtual
13187       // alignment of the base, in which case the base may be misaligned. Choose
13188       // the smaller of the non-virtual alignment and BaseAlignment, which is a
13189       // conservative lower bound of the complete object alignment.
13190       CharUnits NonVirtualAlignment =
13191           Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
13192       BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
13193       Offset = CharUnits::Zero();
13194     } else {
13195       const ASTRecordLayout &RL =
13196           Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
13197       Offset += RL.getBaseClassOffset(BaseDecl);
13198     }
13199     DerivedType = Base->getType();
13200   }
13201 
13202   return std::make_pair(BaseAlignment, Offset);
13203 }
13204 
13205 /// Compute the alignment and offset of a binary additive operator.
13206 static Optional<std::pair<CharUnits, CharUnits>>
13207 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
13208                                      bool IsSub, ASTContext &Ctx) {
13209   QualType PointeeType = PtrE->getType()->getPointeeType();
13210 
13211   if (!PointeeType->isConstantSizeType())
13212     return llvm::None;
13213 
13214   auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
13215 
13216   if (!P)
13217     return llvm::None;
13218 
13219   llvm::APSInt IdxRes;
13220   CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
13221   if (IntE->isIntegerConstantExpr(IdxRes, Ctx)) {
13222     CharUnits Offset = EltSize * IdxRes.getExtValue();
13223     if (IsSub)
13224       Offset = -Offset;
13225     return std::make_pair(P->first, P->second + Offset);
13226   }
13227 
13228   // If the integer expression isn't a constant expression, compute the lower
13229   // bound of the alignment using the alignment and offset of the pointer
13230   // expression and the element size.
13231   return std::make_pair(
13232       P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
13233       CharUnits::Zero());
13234 }
13235 
13236 /// This helper function takes an lvalue expression and returns the alignment of
13237 /// a VarDecl and a constant offset from the VarDecl.
13238 Optional<std::pair<CharUnits, CharUnits>>
13239 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
13240   E = E->IgnoreParens();
13241   switch (E->getStmtClass()) {
13242   default:
13243     break;
13244   case Stmt::CStyleCastExprClass:
13245   case Stmt::CXXStaticCastExprClass:
13246   case Stmt::ImplicitCastExprClass: {
13247     auto *CE = cast<CastExpr>(E);
13248     const Expr *From = CE->getSubExpr();
13249     switch (CE->getCastKind()) {
13250     default:
13251       break;
13252     case CK_NoOp:
13253       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
13254     case CK_UncheckedDerivedToBase:
13255     case CK_DerivedToBase: {
13256       auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
13257       if (!P)
13258         break;
13259       return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
13260                                                 P->second, Ctx);
13261     }
13262     }
13263     break;
13264   }
13265   case Stmt::ArraySubscriptExprClass: {
13266     auto *ASE = cast<ArraySubscriptExpr>(E);
13267     return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
13268                                                 false, Ctx);
13269   }
13270   case Stmt::DeclRefExprClass: {
13271     if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
13272       // FIXME: If VD is captured by copy or is an escaping __block variable,
13273       // use the alignment of VD's type.
13274       if (!VD->getType()->isReferenceType())
13275         return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
13276       if (VD->hasInit())
13277         return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
13278     }
13279     break;
13280   }
13281   case Stmt::MemberExprClass: {
13282     auto *ME = cast<MemberExpr>(E);
13283     if (ME->isArrow())
13284       break;
13285     auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
13286     if (!FD || FD->getType()->isReferenceType())
13287       break;
13288     auto P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
13289     if (!P)
13290       break;
13291     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
13292     uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
13293     return std::make_pair(P->first,
13294                           P->second + CharUnits::fromQuantity(Offset));
13295   }
13296   case Stmt::UnaryOperatorClass: {
13297     auto *UO = cast<UnaryOperator>(E);
13298     switch (UO->getOpcode()) {
13299     default:
13300       break;
13301     case UO_Deref:
13302       return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
13303     }
13304     break;
13305   }
13306   case Stmt::BinaryOperatorClass: {
13307     auto *BO = cast<BinaryOperator>(E);
13308     auto Opcode = BO->getOpcode();
13309     switch (Opcode) {
13310     default:
13311       break;
13312     case BO_Comma:
13313       return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
13314     }
13315     break;
13316   }
13317   }
13318   return llvm::None;
13319 }
13320 
13321 /// This helper function takes a pointer expression and returns the alignment of
13322 /// a VarDecl and a constant offset from the VarDecl.
13323 Optional<std::pair<CharUnits, CharUnits>>
13324 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
13325   E = E->IgnoreParens();
13326   switch (E->getStmtClass()) {
13327   default:
13328     break;
13329   case Stmt::CStyleCastExprClass:
13330   case Stmt::CXXStaticCastExprClass:
13331   case Stmt::ImplicitCastExprClass: {
13332     auto *CE = cast<CastExpr>(E);
13333     const Expr *From = CE->getSubExpr();
13334     switch (CE->getCastKind()) {
13335     default:
13336       break;
13337     case CK_NoOp:
13338       return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
13339     case CK_ArrayToPointerDecay:
13340       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
13341     case CK_UncheckedDerivedToBase:
13342     case CK_DerivedToBase: {
13343       auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
13344       if (!P)
13345         break;
13346       return getDerivedToBaseAlignmentAndOffset(
13347           CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
13348     }
13349     }
13350     break;
13351   }
13352   case Stmt::UnaryOperatorClass: {
13353     auto *UO = cast<UnaryOperator>(E);
13354     if (UO->getOpcode() == UO_AddrOf)
13355       return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
13356     break;
13357   }
13358   case Stmt::BinaryOperatorClass: {
13359     auto *BO = cast<BinaryOperator>(E);
13360     auto Opcode = BO->getOpcode();
13361     switch (Opcode) {
13362     default:
13363       break;
13364     case BO_Add:
13365     case BO_Sub: {
13366       const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
13367       if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
13368         std::swap(LHS, RHS);
13369       return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
13370                                                   Ctx);
13371     }
13372     case BO_Comma:
13373       return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
13374     }
13375     break;
13376   }
13377   }
13378   return llvm::None;
13379 }
13380 
13381 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
13382   // See if we can compute the alignment of a VarDecl and an offset from it.
13383   Optional<std::pair<CharUnits, CharUnits>> P =
13384       getBaseAlignmentAndOffsetFromPtr(E, S.Context);
13385 
13386   if (P)
13387     return P->first.alignmentAtOffset(P->second);
13388 
13389   // If that failed, return the type's alignment.
13390   return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
13391 }
13392 
13393 /// CheckCastAlign - Implements -Wcast-align, which warns when a
13394 /// pointer cast increases the alignment requirements.
13395 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
13396   // This is actually a lot of work to potentially be doing on every
13397   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
13398   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
13399     return;
13400 
13401   // Ignore dependent types.
13402   if (T->isDependentType() || Op->getType()->isDependentType())
13403     return;
13404 
13405   // Require that the destination be a pointer type.
13406   const PointerType *DestPtr = T->getAs<PointerType>();
13407   if (!DestPtr) return;
13408 
13409   // If the destination has alignment 1, we're done.
13410   QualType DestPointee = DestPtr->getPointeeType();
13411   if (DestPointee->isIncompleteType()) return;
13412   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
13413   if (DestAlign.isOne()) return;
13414 
13415   // Require that the source be a pointer type.
13416   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
13417   if (!SrcPtr) return;
13418   QualType SrcPointee = SrcPtr->getPointeeType();
13419 
13420   // Whitelist casts from cv void*.  We already implicitly
13421   // whitelisted casts to cv void*, since they have alignment 1.
13422   // Also whitelist casts involving incomplete types, which implicitly
13423   // includes 'void'.
13424   if (SrcPointee->isIncompleteType()) return;
13425 
13426   CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
13427 
13428   if (SrcAlign >= DestAlign) return;
13429 
13430   Diag(TRange.getBegin(), diag::warn_cast_align)
13431     << Op->getType() << T
13432     << static_cast<unsigned>(SrcAlign.getQuantity())
13433     << static_cast<unsigned>(DestAlign.getQuantity())
13434     << TRange << Op->getSourceRange();
13435 }
13436 
13437 /// Check whether this array fits the idiom of a size-one tail padded
13438 /// array member of a struct.
13439 ///
13440 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
13441 /// commonly used to emulate flexible arrays in C89 code.
13442 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
13443                                     const NamedDecl *ND) {
13444   if (Size != 1 || !ND) return false;
13445 
13446   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
13447   if (!FD) return false;
13448 
13449   // Don't consider sizes resulting from macro expansions or template argument
13450   // substitution to form C89 tail-padded arrays.
13451 
13452   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
13453   while (TInfo) {
13454     TypeLoc TL = TInfo->getTypeLoc();
13455     // Look through typedefs.
13456     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
13457       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
13458       TInfo = TDL->getTypeSourceInfo();
13459       continue;
13460     }
13461     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
13462       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
13463       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
13464         return false;
13465     }
13466     break;
13467   }
13468 
13469   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
13470   if (!RD) return false;
13471   if (RD->isUnion()) return false;
13472   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
13473     if (!CRD->isStandardLayout()) return false;
13474   }
13475 
13476   // See if this is the last field decl in the record.
13477   const Decl *D = FD;
13478   while ((D = D->getNextDeclInContext()))
13479     if (isa<FieldDecl>(D))
13480       return false;
13481   return true;
13482 }
13483 
13484 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
13485                             const ArraySubscriptExpr *ASE,
13486                             bool AllowOnePastEnd, bool IndexNegated) {
13487   // Already diagnosed by the constant evaluator.
13488   if (isConstantEvaluated())
13489     return;
13490 
13491   IndexExpr = IndexExpr->IgnoreParenImpCasts();
13492   if (IndexExpr->isValueDependent())
13493     return;
13494 
13495   const Type *EffectiveType =
13496       BaseExpr->getType()->getPointeeOrArrayElementType();
13497   BaseExpr = BaseExpr->IgnoreParenCasts();
13498   const ConstantArrayType *ArrayTy =
13499       Context.getAsConstantArrayType(BaseExpr->getType());
13500 
13501   if (!ArrayTy)
13502     return;
13503 
13504   const Type *BaseType = ArrayTy->getElementType().getTypePtr();
13505   if (EffectiveType->isDependentType() || BaseType->isDependentType())
13506     return;
13507 
13508   Expr::EvalResult Result;
13509   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
13510     return;
13511 
13512   llvm::APSInt index = Result.Val.getInt();
13513   if (IndexNegated)
13514     index = -index;
13515 
13516   const NamedDecl *ND = nullptr;
13517   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
13518     ND = DRE->getDecl();
13519   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
13520     ND = ME->getMemberDecl();
13521 
13522   if (index.isUnsigned() || !index.isNegative()) {
13523     // It is possible that the type of the base expression after
13524     // IgnoreParenCasts is incomplete, even though the type of the base
13525     // expression before IgnoreParenCasts is complete (see PR39746 for an
13526     // example). In this case we have no information about whether the array
13527     // access exceeds the array bounds. However we can still diagnose an array
13528     // access which precedes the array bounds.
13529     if (BaseType->isIncompleteType())
13530       return;
13531 
13532     llvm::APInt size = ArrayTy->getSize();
13533     if (!size.isStrictlyPositive())
13534       return;
13535 
13536     if (BaseType != EffectiveType) {
13537       // Make sure we're comparing apples to apples when comparing index to size
13538       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
13539       uint64_t array_typesize = Context.getTypeSize(BaseType);
13540       // Handle ptrarith_typesize being zero, such as when casting to void*
13541       if (!ptrarith_typesize) ptrarith_typesize = 1;
13542       if (ptrarith_typesize != array_typesize) {
13543         // There's a cast to a different size type involved
13544         uint64_t ratio = array_typesize / ptrarith_typesize;
13545         // TODO: Be smarter about handling cases where array_typesize is not a
13546         // multiple of ptrarith_typesize
13547         if (ptrarith_typesize * ratio == array_typesize)
13548           size *= llvm::APInt(size.getBitWidth(), ratio);
13549       }
13550     }
13551 
13552     if (size.getBitWidth() > index.getBitWidth())
13553       index = index.zext(size.getBitWidth());
13554     else if (size.getBitWidth() < index.getBitWidth())
13555       size = size.zext(index.getBitWidth());
13556 
13557     // For array subscripting the index must be less than size, but for pointer
13558     // arithmetic also allow the index (offset) to be equal to size since
13559     // computing the next address after the end of the array is legal and
13560     // commonly done e.g. in C++ iterators and range-based for loops.
13561     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
13562       return;
13563 
13564     // Also don't warn for arrays of size 1 which are members of some
13565     // structure. These are often used to approximate flexible arrays in C89
13566     // code.
13567     if (IsTailPaddedMemberArray(*this, size, ND))
13568       return;
13569 
13570     // Suppress the warning if the subscript expression (as identified by the
13571     // ']' location) and the index expression are both from macro expansions
13572     // within a system header.
13573     if (ASE) {
13574       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
13575           ASE->getRBracketLoc());
13576       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
13577         SourceLocation IndexLoc =
13578             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
13579         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
13580           return;
13581       }
13582     }
13583 
13584     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
13585     if (ASE)
13586       DiagID = diag::warn_array_index_exceeds_bounds;
13587 
13588     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
13589                         PDiag(DiagID) << index.toString(10, true)
13590                                       << size.toString(10, true)
13591                                       << (unsigned)size.getLimitedValue(~0U)
13592                                       << IndexExpr->getSourceRange());
13593   } else {
13594     unsigned DiagID = diag::warn_array_index_precedes_bounds;
13595     if (!ASE) {
13596       DiagID = diag::warn_ptr_arith_precedes_bounds;
13597       if (index.isNegative()) index = -index;
13598     }
13599 
13600     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
13601                         PDiag(DiagID) << index.toString(10, true)
13602                                       << IndexExpr->getSourceRange());
13603   }
13604 
13605   if (!ND) {
13606     // Try harder to find a NamedDecl to point at in the note.
13607     while (const ArraySubscriptExpr *ASE =
13608            dyn_cast<ArraySubscriptExpr>(BaseExpr))
13609       BaseExpr = ASE->getBase()->IgnoreParenCasts();
13610     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
13611       ND = DRE->getDecl();
13612     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
13613       ND = ME->getMemberDecl();
13614   }
13615 
13616   if (ND)
13617     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
13618                         PDiag(diag::note_array_declared_here)
13619                             << ND->getDeclName());
13620 }
13621 
13622 void Sema::CheckArrayAccess(const Expr *expr) {
13623   int AllowOnePastEnd = 0;
13624   while (expr) {
13625     expr = expr->IgnoreParenImpCasts();
13626     switch (expr->getStmtClass()) {
13627       case Stmt::ArraySubscriptExprClass: {
13628         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
13629         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
13630                          AllowOnePastEnd > 0);
13631         expr = ASE->getBase();
13632         break;
13633       }
13634       case Stmt::MemberExprClass: {
13635         expr = cast<MemberExpr>(expr)->getBase();
13636         break;
13637       }
13638       case Stmt::OMPArraySectionExprClass: {
13639         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
13640         if (ASE->getLowerBound())
13641           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
13642                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
13643         return;
13644       }
13645       case Stmt::UnaryOperatorClass: {
13646         // Only unwrap the * and & unary operators
13647         const UnaryOperator *UO = cast<UnaryOperator>(expr);
13648         expr = UO->getSubExpr();
13649         switch (UO->getOpcode()) {
13650           case UO_AddrOf:
13651             AllowOnePastEnd++;
13652             break;
13653           case UO_Deref:
13654             AllowOnePastEnd--;
13655             break;
13656           default:
13657             return;
13658         }
13659         break;
13660       }
13661       case Stmt::ConditionalOperatorClass: {
13662         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
13663         if (const Expr *lhs = cond->getLHS())
13664           CheckArrayAccess(lhs);
13665         if (const Expr *rhs = cond->getRHS())
13666           CheckArrayAccess(rhs);
13667         return;
13668       }
13669       case Stmt::CXXOperatorCallExprClass: {
13670         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
13671         for (const auto *Arg : OCE->arguments())
13672           CheckArrayAccess(Arg);
13673         return;
13674       }
13675       default:
13676         return;
13677     }
13678   }
13679 }
13680 
13681 //===--- CHECK: Objective-C retain cycles ----------------------------------//
13682 
13683 namespace {
13684 
13685 struct RetainCycleOwner {
13686   VarDecl *Variable = nullptr;
13687   SourceRange Range;
13688   SourceLocation Loc;
13689   bool Indirect = false;
13690 
13691   RetainCycleOwner() = default;
13692 
13693   void setLocsFrom(Expr *e) {
13694     Loc = e->getExprLoc();
13695     Range = e->getSourceRange();
13696   }
13697 };
13698 
13699 } // namespace
13700 
13701 /// Consider whether capturing the given variable can possibly lead to
13702 /// a retain cycle.
13703 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
13704   // In ARC, it's captured strongly iff the variable has __strong
13705   // lifetime.  In MRR, it's captured strongly if the variable is
13706   // __block and has an appropriate type.
13707   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
13708     return false;
13709 
13710   owner.Variable = var;
13711   if (ref)
13712     owner.setLocsFrom(ref);
13713   return true;
13714 }
13715 
13716 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
13717   while (true) {
13718     e = e->IgnoreParens();
13719     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
13720       switch (cast->getCastKind()) {
13721       case CK_BitCast:
13722       case CK_LValueBitCast:
13723       case CK_LValueToRValue:
13724       case CK_ARCReclaimReturnedObject:
13725         e = cast->getSubExpr();
13726         continue;
13727 
13728       default:
13729         return false;
13730       }
13731     }
13732 
13733     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
13734       ObjCIvarDecl *ivar = ref->getDecl();
13735       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
13736         return false;
13737 
13738       // Try to find a retain cycle in the base.
13739       if (!findRetainCycleOwner(S, ref->getBase(), owner))
13740         return false;
13741 
13742       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
13743       owner.Indirect = true;
13744       return true;
13745     }
13746 
13747     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
13748       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
13749       if (!var) return false;
13750       return considerVariable(var, ref, owner);
13751     }
13752 
13753     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
13754       if (member->isArrow()) return false;
13755 
13756       // Don't count this as an indirect ownership.
13757       e = member->getBase();
13758       continue;
13759     }
13760 
13761     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
13762       // Only pay attention to pseudo-objects on property references.
13763       ObjCPropertyRefExpr *pre
13764         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
13765                                               ->IgnoreParens());
13766       if (!pre) return false;
13767       if (pre->isImplicitProperty()) return false;
13768       ObjCPropertyDecl *property = pre->getExplicitProperty();
13769       if (!property->isRetaining() &&
13770           !(property->getPropertyIvarDecl() &&
13771             property->getPropertyIvarDecl()->getType()
13772               .getObjCLifetime() == Qualifiers::OCL_Strong))
13773           return false;
13774 
13775       owner.Indirect = true;
13776       if (pre->isSuperReceiver()) {
13777         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
13778         if (!owner.Variable)
13779           return false;
13780         owner.Loc = pre->getLocation();
13781         owner.Range = pre->getSourceRange();
13782         return true;
13783       }
13784       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
13785                               ->getSourceExpr());
13786       continue;
13787     }
13788 
13789     // Array ivars?
13790 
13791     return false;
13792   }
13793 }
13794 
13795 namespace {
13796 
13797   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
13798     ASTContext &Context;
13799     VarDecl *Variable;
13800     Expr *Capturer = nullptr;
13801     bool VarWillBeReased = false;
13802 
13803     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
13804         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
13805           Context(Context), Variable(variable) {}
13806 
13807     void VisitDeclRefExpr(DeclRefExpr *ref) {
13808       if (ref->getDecl() == Variable && !Capturer)
13809         Capturer = ref;
13810     }
13811 
13812     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
13813       if (Capturer) return;
13814       Visit(ref->getBase());
13815       if (Capturer && ref->isFreeIvar())
13816         Capturer = ref;
13817     }
13818 
13819     void VisitBlockExpr(BlockExpr *block) {
13820       // Look inside nested blocks
13821       if (block->getBlockDecl()->capturesVariable(Variable))
13822         Visit(block->getBlockDecl()->getBody());
13823     }
13824 
13825     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
13826       if (Capturer) return;
13827       if (OVE->getSourceExpr())
13828         Visit(OVE->getSourceExpr());
13829     }
13830 
13831     void VisitBinaryOperator(BinaryOperator *BinOp) {
13832       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
13833         return;
13834       Expr *LHS = BinOp->getLHS();
13835       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
13836         if (DRE->getDecl() != Variable)
13837           return;
13838         if (Expr *RHS = BinOp->getRHS()) {
13839           RHS = RHS->IgnoreParenCasts();
13840           llvm::APSInt Value;
13841           VarWillBeReased =
13842             (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
13843         }
13844       }
13845     }
13846   };
13847 
13848 } // namespace
13849 
13850 /// Check whether the given argument is a block which captures a
13851 /// variable.
13852 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
13853   assert(owner.Variable && owner.Loc.isValid());
13854 
13855   e = e->IgnoreParenCasts();
13856 
13857   // Look through [^{...} copy] and Block_copy(^{...}).
13858   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
13859     Selector Cmd = ME->getSelector();
13860     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
13861       e = ME->getInstanceReceiver();
13862       if (!e)
13863         return nullptr;
13864       e = e->IgnoreParenCasts();
13865     }
13866   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
13867     if (CE->getNumArgs() == 1) {
13868       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
13869       if (Fn) {
13870         const IdentifierInfo *FnI = Fn->getIdentifier();
13871         if (FnI && FnI->isStr("_Block_copy")) {
13872           e = CE->getArg(0)->IgnoreParenCasts();
13873         }
13874       }
13875     }
13876   }
13877 
13878   BlockExpr *block = dyn_cast<BlockExpr>(e);
13879   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
13880     return nullptr;
13881 
13882   FindCaptureVisitor visitor(S.Context, owner.Variable);
13883   visitor.Visit(block->getBlockDecl()->getBody());
13884   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
13885 }
13886 
13887 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
13888                                 RetainCycleOwner &owner) {
13889   assert(capturer);
13890   assert(owner.Variable && owner.Loc.isValid());
13891 
13892   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
13893     << owner.Variable << capturer->getSourceRange();
13894   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
13895     << owner.Indirect << owner.Range;
13896 }
13897 
13898 /// Check for a keyword selector that starts with the word 'add' or
13899 /// 'set'.
13900 static bool isSetterLikeSelector(Selector sel) {
13901   if (sel.isUnarySelector()) return false;
13902 
13903   StringRef str = sel.getNameForSlot(0);
13904   while (!str.empty() && str.front() == '_') str = str.substr(1);
13905   if (str.startswith("set"))
13906     str = str.substr(3);
13907   else if (str.startswith("add")) {
13908     // Specially whitelist 'addOperationWithBlock:'.
13909     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
13910       return false;
13911     str = str.substr(3);
13912   }
13913   else
13914     return false;
13915 
13916   if (str.empty()) return true;
13917   return !isLowercase(str.front());
13918 }
13919 
13920 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
13921                                                     ObjCMessageExpr *Message) {
13922   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
13923                                                 Message->getReceiverInterface(),
13924                                                 NSAPI::ClassId_NSMutableArray);
13925   if (!IsMutableArray) {
13926     return None;
13927   }
13928 
13929   Selector Sel = Message->getSelector();
13930 
13931   Optional<NSAPI::NSArrayMethodKind> MKOpt =
13932     S.NSAPIObj->getNSArrayMethodKind(Sel);
13933   if (!MKOpt) {
13934     return None;
13935   }
13936 
13937   NSAPI::NSArrayMethodKind MK = *MKOpt;
13938 
13939   switch (MK) {
13940     case NSAPI::NSMutableArr_addObject:
13941     case NSAPI::NSMutableArr_insertObjectAtIndex:
13942     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
13943       return 0;
13944     case NSAPI::NSMutableArr_replaceObjectAtIndex:
13945       return 1;
13946 
13947     default:
13948       return None;
13949   }
13950 
13951   return None;
13952 }
13953 
13954 static
13955 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
13956                                                   ObjCMessageExpr *Message) {
13957   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
13958                                             Message->getReceiverInterface(),
13959                                             NSAPI::ClassId_NSMutableDictionary);
13960   if (!IsMutableDictionary) {
13961     return None;
13962   }
13963 
13964   Selector Sel = Message->getSelector();
13965 
13966   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
13967     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
13968   if (!MKOpt) {
13969     return None;
13970   }
13971 
13972   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
13973 
13974   switch (MK) {
13975     case NSAPI::NSMutableDict_setObjectForKey:
13976     case NSAPI::NSMutableDict_setValueForKey:
13977     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
13978       return 0;
13979 
13980     default:
13981       return None;
13982   }
13983 
13984   return None;
13985 }
13986 
13987 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
13988   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
13989                                                 Message->getReceiverInterface(),
13990                                                 NSAPI::ClassId_NSMutableSet);
13991 
13992   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
13993                                             Message->getReceiverInterface(),
13994                                             NSAPI::ClassId_NSMutableOrderedSet);
13995   if (!IsMutableSet && !IsMutableOrderedSet) {
13996     return None;
13997   }
13998 
13999   Selector Sel = Message->getSelector();
14000 
14001   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
14002   if (!MKOpt) {
14003     return None;
14004   }
14005 
14006   NSAPI::NSSetMethodKind MK = *MKOpt;
14007 
14008   switch (MK) {
14009     case NSAPI::NSMutableSet_addObject:
14010     case NSAPI::NSOrderedSet_setObjectAtIndex:
14011     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
14012     case NSAPI::NSOrderedSet_insertObjectAtIndex:
14013       return 0;
14014     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
14015       return 1;
14016   }
14017 
14018   return None;
14019 }
14020 
14021 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
14022   if (!Message->isInstanceMessage()) {
14023     return;
14024   }
14025 
14026   Optional<int> ArgOpt;
14027 
14028   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
14029       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
14030       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
14031     return;
14032   }
14033 
14034   int ArgIndex = *ArgOpt;
14035 
14036   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
14037   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
14038     Arg = OE->getSourceExpr()->IgnoreImpCasts();
14039   }
14040 
14041   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
14042     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
14043       if (ArgRE->isObjCSelfExpr()) {
14044         Diag(Message->getSourceRange().getBegin(),
14045              diag::warn_objc_circular_container)
14046           << ArgRE->getDecl() << StringRef("'super'");
14047       }
14048     }
14049   } else {
14050     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
14051 
14052     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
14053       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
14054     }
14055 
14056     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
14057       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
14058         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
14059           ValueDecl *Decl = ReceiverRE->getDecl();
14060           Diag(Message->getSourceRange().getBegin(),
14061                diag::warn_objc_circular_container)
14062             << Decl << Decl;
14063           if (!ArgRE->isObjCSelfExpr()) {
14064             Diag(Decl->getLocation(),
14065                  diag::note_objc_circular_container_declared_here)
14066               << Decl;
14067           }
14068         }
14069       }
14070     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
14071       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
14072         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
14073           ObjCIvarDecl *Decl = IvarRE->getDecl();
14074           Diag(Message->getSourceRange().getBegin(),
14075                diag::warn_objc_circular_container)
14076             << Decl << Decl;
14077           Diag(Decl->getLocation(),
14078                diag::note_objc_circular_container_declared_here)
14079             << Decl;
14080         }
14081       }
14082     }
14083   }
14084 }
14085 
14086 /// Check a message send to see if it's likely to cause a retain cycle.
14087 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
14088   // Only check instance methods whose selector looks like a setter.
14089   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
14090     return;
14091 
14092   // Try to find a variable that the receiver is strongly owned by.
14093   RetainCycleOwner owner;
14094   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
14095     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
14096       return;
14097   } else {
14098     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
14099     owner.Variable = getCurMethodDecl()->getSelfDecl();
14100     owner.Loc = msg->getSuperLoc();
14101     owner.Range = msg->getSuperLoc();
14102   }
14103 
14104   // Check whether the receiver is captured by any of the arguments.
14105   const ObjCMethodDecl *MD = msg->getMethodDecl();
14106   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
14107     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
14108       // noescape blocks should not be retained by the method.
14109       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
14110         continue;
14111       return diagnoseRetainCycle(*this, capturer, owner);
14112     }
14113   }
14114 }
14115 
14116 /// Check a property assign to see if it's likely to cause a retain cycle.
14117 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
14118   RetainCycleOwner owner;
14119   if (!findRetainCycleOwner(*this, receiver, owner))
14120     return;
14121 
14122   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
14123     diagnoseRetainCycle(*this, capturer, owner);
14124 }
14125 
14126 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
14127   RetainCycleOwner Owner;
14128   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
14129     return;
14130 
14131   // Because we don't have an expression for the variable, we have to set the
14132   // location explicitly here.
14133   Owner.Loc = Var->getLocation();
14134   Owner.Range = Var->getSourceRange();
14135 
14136   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
14137     diagnoseRetainCycle(*this, Capturer, Owner);
14138 }
14139 
14140 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
14141                                      Expr *RHS, bool isProperty) {
14142   // Check if RHS is an Objective-C object literal, which also can get
14143   // immediately zapped in a weak reference.  Note that we explicitly
14144   // allow ObjCStringLiterals, since those are designed to never really die.
14145   RHS = RHS->IgnoreParenImpCasts();
14146 
14147   // This enum needs to match with the 'select' in
14148   // warn_objc_arc_literal_assign (off-by-1).
14149   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
14150   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
14151     return false;
14152 
14153   S.Diag(Loc, diag::warn_arc_literal_assign)
14154     << (unsigned) Kind
14155     << (isProperty ? 0 : 1)
14156     << RHS->getSourceRange();
14157 
14158   return true;
14159 }
14160 
14161 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
14162                                     Qualifiers::ObjCLifetime LT,
14163                                     Expr *RHS, bool isProperty) {
14164   // Strip off any implicit cast added to get to the one ARC-specific.
14165   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
14166     if (cast->getCastKind() == CK_ARCConsumeObject) {
14167       S.Diag(Loc, diag::warn_arc_retained_assign)
14168         << (LT == Qualifiers::OCL_ExplicitNone)
14169         << (isProperty ? 0 : 1)
14170         << RHS->getSourceRange();
14171       return true;
14172     }
14173     RHS = cast->getSubExpr();
14174   }
14175 
14176   if (LT == Qualifiers::OCL_Weak &&
14177       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
14178     return true;
14179 
14180   return false;
14181 }
14182 
14183 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
14184                               QualType LHS, Expr *RHS) {
14185   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
14186 
14187   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
14188     return false;
14189 
14190   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
14191     return true;
14192 
14193   return false;
14194 }
14195 
14196 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
14197                               Expr *LHS, Expr *RHS) {
14198   QualType LHSType;
14199   // PropertyRef on LHS type need be directly obtained from
14200   // its declaration as it has a PseudoType.
14201   ObjCPropertyRefExpr *PRE
14202     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
14203   if (PRE && !PRE->isImplicitProperty()) {
14204     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
14205     if (PD)
14206       LHSType = PD->getType();
14207   }
14208 
14209   if (LHSType.isNull())
14210     LHSType = LHS->getType();
14211 
14212   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
14213 
14214   if (LT == Qualifiers::OCL_Weak) {
14215     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
14216       getCurFunction()->markSafeWeakUse(LHS);
14217   }
14218 
14219   if (checkUnsafeAssigns(Loc, LHSType, RHS))
14220     return;
14221 
14222   // FIXME. Check for other life times.
14223   if (LT != Qualifiers::OCL_None)
14224     return;
14225 
14226   if (PRE) {
14227     if (PRE->isImplicitProperty())
14228       return;
14229     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
14230     if (!PD)
14231       return;
14232 
14233     unsigned Attributes = PD->getPropertyAttributes();
14234     if (Attributes & ObjCPropertyAttribute::kind_assign) {
14235       // when 'assign' attribute was not explicitly specified
14236       // by user, ignore it and rely on property type itself
14237       // for lifetime info.
14238       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
14239       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
14240           LHSType->isObjCRetainableType())
14241         return;
14242 
14243       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
14244         if (cast->getCastKind() == CK_ARCConsumeObject) {
14245           Diag(Loc, diag::warn_arc_retained_property_assign)
14246           << RHS->getSourceRange();
14247           return;
14248         }
14249         RHS = cast->getSubExpr();
14250       }
14251     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
14252       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
14253         return;
14254     }
14255   }
14256 }
14257 
14258 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
14259 
14260 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
14261                                         SourceLocation StmtLoc,
14262                                         const NullStmt *Body) {
14263   // Do not warn if the body is a macro that expands to nothing, e.g:
14264   //
14265   // #define CALL(x)
14266   // if (condition)
14267   //   CALL(0);
14268   if (Body->hasLeadingEmptyMacro())
14269     return false;
14270 
14271   // Get line numbers of statement and body.
14272   bool StmtLineInvalid;
14273   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
14274                                                       &StmtLineInvalid);
14275   if (StmtLineInvalid)
14276     return false;
14277 
14278   bool BodyLineInvalid;
14279   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
14280                                                       &BodyLineInvalid);
14281   if (BodyLineInvalid)
14282     return false;
14283 
14284   // Warn if null statement and body are on the same line.
14285   if (StmtLine != BodyLine)
14286     return false;
14287 
14288   return true;
14289 }
14290 
14291 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
14292                                  const Stmt *Body,
14293                                  unsigned DiagID) {
14294   // Since this is a syntactic check, don't emit diagnostic for template
14295   // instantiations, this just adds noise.
14296   if (CurrentInstantiationScope)
14297     return;
14298 
14299   // The body should be a null statement.
14300   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
14301   if (!NBody)
14302     return;
14303 
14304   // Do the usual checks.
14305   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
14306     return;
14307 
14308   Diag(NBody->getSemiLoc(), DiagID);
14309   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
14310 }
14311 
14312 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
14313                                  const Stmt *PossibleBody) {
14314   assert(!CurrentInstantiationScope); // Ensured by caller
14315 
14316   SourceLocation StmtLoc;
14317   const Stmt *Body;
14318   unsigned DiagID;
14319   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
14320     StmtLoc = FS->getRParenLoc();
14321     Body = FS->getBody();
14322     DiagID = diag::warn_empty_for_body;
14323   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
14324     StmtLoc = WS->getCond()->getSourceRange().getEnd();
14325     Body = WS->getBody();
14326     DiagID = diag::warn_empty_while_body;
14327   } else
14328     return; // Neither `for' nor `while'.
14329 
14330   // The body should be a null statement.
14331   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
14332   if (!NBody)
14333     return;
14334 
14335   // Skip expensive checks if diagnostic is disabled.
14336   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
14337     return;
14338 
14339   // Do the usual checks.
14340   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
14341     return;
14342 
14343   // `for(...);' and `while(...);' are popular idioms, so in order to keep
14344   // noise level low, emit diagnostics only if for/while is followed by a
14345   // CompoundStmt, e.g.:
14346   //    for (int i = 0; i < n; i++);
14347   //    {
14348   //      a(i);
14349   //    }
14350   // or if for/while is followed by a statement with more indentation
14351   // than for/while itself:
14352   //    for (int i = 0; i < n; i++);
14353   //      a(i);
14354   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
14355   if (!ProbableTypo) {
14356     bool BodyColInvalid;
14357     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
14358         PossibleBody->getBeginLoc(), &BodyColInvalid);
14359     if (BodyColInvalid)
14360       return;
14361 
14362     bool StmtColInvalid;
14363     unsigned StmtCol =
14364         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
14365     if (StmtColInvalid)
14366       return;
14367 
14368     if (BodyCol > StmtCol)
14369       ProbableTypo = true;
14370   }
14371 
14372   if (ProbableTypo) {
14373     Diag(NBody->getSemiLoc(), DiagID);
14374     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
14375   }
14376 }
14377 
14378 //===--- CHECK: Warn on self move with std::move. -------------------------===//
14379 
14380 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
14381 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
14382                              SourceLocation OpLoc) {
14383   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
14384     return;
14385 
14386   if (inTemplateInstantiation())
14387     return;
14388 
14389   // Strip parens and casts away.
14390   LHSExpr = LHSExpr->IgnoreParenImpCasts();
14391   RHSExpr = RHSExpr->IgnoreParenImpCasts();
14392 
14393   // Check for a call expression
14394   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
14395   if (!CE || CE->getNumArgs() != 1)
14396     return;
14397 
14398   // Check for a call to std::move
14399   if (!CE->isCallToStdMove())
14400     return;
14401 
14402   // Get argument from std::move
14403   RHSExpr = CE->getArg(0);
14404 
14405   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
14406   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
14407 
14408   // Two DeclRefExpr's, check that the decls are the same.
14409   if (LHSDeclRef && RHSDeclRef) {
14410     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
14411       return;
14412     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
14413         RHSDeclRef->getDecl()->getCanonicalDecl())
14414       return;
14415 
14416     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14417                                         << LHSExpr->getSourceRange()
14418                                         << RHSExpr->getSourceRange();
14419     return;
14420   }
14421 
14422   // Member variables require a different approach to check for self moves.
14423   // MemberExpr's are the same if every nested MemberExpr refers to the same
14424   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
14425   // the base Expr's are CXXThisExpr's.
14426   const Expr *LHSBase = LHSExpr;
14427   const Expr *RHSBase = RHSExpr;
14428   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
14429   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
14430   if (!LHSME || !RHSME)
14431     return;
14432 
14433   while (LHSME && RHSME) {
14434     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
14435         RHSME->getMemberDecl()->getCanonicalDecl())
14436       return;
14437 
14438     LHSBase = LHSME->getBase();
14439     RHSBase = RHSME->getBase();
14440     LHSME = dyn_cast<MemberExpr>(LHSBase);
14441     RHSME = dyn_cast<MemberExpr>(RHSBase);
14442   }
14443 
14444   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
14445   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
14446   if (LHSDeclRef && RHSDeclRef) {
14447     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
14448       return;
14449     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
14450         RHSDeclRef->getDecl()->getCanonicalDecl())
14451       return;
14452 
14453     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14454                                         << LHSExpr->getSourceRange()
14455                                         << RHSExpr->getSourceRange();
14456     return;
14457   }
14458 
14459   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
14460     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14461                                         << LHSExpr->getSourceRange()
14462                                         << RHSExpr->getSourceRange();
14463 }
14464 
14465 //===--- Layout compatibility ----------------------------------------------//
14466 
14467 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
14468 
14469 /// Check if two enumeration types are layout-compatible.
14470 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
14471   // C++11 [dcl.enum] p8:
14472   // Two enumeration types are layout-compatible if they have the same
14473   // underlying type.
14474   return ED1->isComplete() && ED2->isComplete() &&
14475          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
14476 }
14477 
14478 /// Check if two fields are layout-compatible.
14479 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
14480                                FieldDecl *Field2) {
14481   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
14482     return false;
14483 
14484   if (Field1->isBitField() != Field2->isBitField())
14485     return false;
14486 
14487   if (Field1->isBitField()) {
14488     // Make sure that the bit-fields are the same length.
14489     unsigned Bits1 = Field1->getBitWidthValue(C);
14490     unsigned Bits2 = Field2->getBitWidthValue(C);
14491 
14492     if (Bits1 != Bits2)
14493       return false;
14494   }
14495 
14496   return true;
14497 }
14498 
14499 /// Check if two standard-layout structs are layout-compatible.
14500 /// (C++11 [class.mem] p17)
14501 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
14502                                      RecordDecl *RD2) {
14503   // If both records are C++ classes, check that base classes match.
14504   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
14505     // If one of records is a CXXRecordDecl we are in C++ mode,
14506     // thus the other one is a CXXRecordDecl, too.
14507     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
14508     // Check number of base classes.
14509     if (D1CXX->getNumBases() != D2CXX->getNumBases())
14510       return false;
14511 
14512     // Check the base classes.
14513     for (CXXRecordDecl::base_class_const_iterator
14514                Base1 = D1CXX->bases_begin(),
14515            BaseEnd1 = D1CXX->bases_end(),
14516               Base2 = D2CXX->bases_begin();
14517          Base1 != BaseEnd1;
14518          ++Base1, ++Base2) {
14519       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
14520         return false;
14521     }
14522   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
14523     // If only RD2 is a C++ class, it should have zero base classes.
14524     if (D2CXX->getNumBases() > 0)
14525       return false;
14526   }
14527 
14528   // Check the fields.
14529   RecordDecl::field_iterator Field2 = RD2->field_begin(),
14530                              Field2End = RD2->field_end(),
14531                              Field1 = RD1->field_begin(),
14532                              Field1End = RD1->field_end();
14533   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
14534     if (!isLayoutCompatible(C, *Field1, *Field2))
14535       return false;
14536   }
14537   if (Field1 != Field1End || Field2 != Field2End)
14538     return false;
14539 
14540   return true;
14541 }
14542 
14543 /// Check if two standard-layout unions are layout-compatible.
14544 /// (C++11 [class.mem] p18)
14545 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
14546                                     RecordDecl *RD2) {
14547   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
14548   for (auto *Field2 : RD2->fields())
14549     UnmatchedFields.insert(Field2);
14550 
14551   for (auto *Field1 : RD1->fields()) {
14552     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
14553         I = UnmatchedFields.begin(),
14554         E = UnmatchedFields.end();
14555 
14556     for ( ; I != E; ++I) {
14557       if (isLayoutCompatible(C, Field1, *I)) {
14558         bool Result = UnmatchedFields.erase(*I);
14559         (void) Result;
14560         assert(Result);
14561         break;
14562       }
14563     }
14564     if (I == E)
14565       return false;
14566   }
14567 
14568   return UnmatchedFields.empty();
14569 }
14570 
14571 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
14572                                RecordDecl *RD2) {
14573   if (RD1->isUnion() != RD2->isUnion())
14574     return false;
14575 
14576   if (RD1->isUnion())
14577     return isLayoutCompatibleUnion(C, RD1, RD2);
14578   else
14579     return isLayoutCompatibleStruct(C, RD1, RD2);
14580 }
14581 
14582 /// Check if two types are layout-compatible in C++11 sense.
14583 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
14584   if (T1.isNull() || T2.isNull())
14585     return false;
14586 
14587   // C++11 [basic.types] p11:
14588   // If two types T1 and T2 are the same type, then T1 and T2 are
14589   // layout-compatible types.
14590   if (C.hasSameType(T1, T2))
14591     return true;
14592 
14593   T1 = T1.getCanonicalType().getUnqualifiedType();
14594   T2 = T2.getCanonicalType().getUnqualifiedType();
14595 
14596   const Type::TypeClass TC1 = T1->getTypeClass();
14597   const Type::TypeClass TC2 = T2->getTypeClass();
14598 
14599   if (TC1 != TC2)
14600     return false;
14601 
14602   if (TC1 == Type::Enum) {
14603     return isLayoutCompatible(C,
14604                               cast<EnumType>(T1)->getDecl(),
14605                               cast<EnumType>(T2)->getDecl());
14606   } else if (TC1 == Type::Record) {
14607     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
14608       return false;
14609 
14610     return isLayoutCompatible(C,
14611                               cast<RecordType>(T1)->getDecl(),
14612                               cast<RecordType>(T2)->getDecl());
14613   }
14614 
14615   return false;
14616 }
14617 
14618 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
14619 
14620 /// Given a type tag expression find the type tag itself.
14621 ///
14622 /// \param TypeExpr Type tag expression, as it appears in user's code.
14623 ///
14624 /// \param VD Declaration of an identifier that appears in a type tag.
14625 ///
14626 /// \param MagicValue Type tag magic value.
14627 ///
14628 /// \param isConstantEvaluated wether the evalaution should be performed in
14629 
14630 /// constant context.
14631 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
14632                             const ValueDecl **VD, uint64_t *MagicValue,
14633                             bool isConstantEvaluated) {
14634   while(true) {
14635     if (!TypeExpr)
14636       return false;
14637 
14638     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
14639 
14640     switch (TypeExpr->getStmtClass()) {
14641     case Stmt::UnaryOperatorClass: {
14642       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
14643       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
14644         TypeExpr = UO->getSubExpr();
14645         continue;
14646       }
14647       return false;
14648     }
14649 
14650     case Stmt::DeclRefExprClass: {
14651       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
14652       *VD = DRE->getDecl();
14653       return true;
14654     }
14655 
14656     case Stmt::IntegerLiteralClass: {
14657       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
14658       llvm::APInt MagicValueAPInt = IL->getValue();
14659       if (MagicValueAPInt.getActiveBits() <= 64) {
14660         *MagicValue = MagicValueAPInt.getZExtValue();
14661         return true;
14662       } else
14663         return false;
14664     }
14665 
14666     case Stmt::BinaryConditionalOperatorClass:
14667     case Stmt::ConditionalOperatorClass: {
14668       const AbstractConditionalOperator *ACO =
14669           cast<AbstractConditionalOperator>(TypeExpr);
14670       bool Result;
14671       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
14672                                                      isConstantEvaluated)) {
14673         if (Result)
14674           TypeExpr = ACO->getTrueExpr();
14675         else
14676           TypeExpr = ACO->getFalseExpr();
14677         continue;
14678       }
14679       return false;
14680     }
14681 
14682     case Stmt::BinaryOperatorClass: {
14683       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
14684       if (BO->getOpcode() == BO_Comma) {
14685         TypeExpr = BO->getRHS();
14686         continue;
14687       }
14688       return false;
14689     }
14690 
14691     default:
14692       return false;
14693     }
14694   }
14695 }
14696 
14697 /// Retrieve the C type corresponding to type tag TypeExpr.
14698 ///
14699 /// \param TypeExpr Expression that specifies a type tag.
14700 ///
14701 /// \param MagicValues Registered magic values.
14702 ///
14703 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
14704 ///        kind.
14705 ///
14706 /// \param TypeInfo Information about the corresponding C type.
14707 ///
14708 /// \param isConstantEvaluated wether the evalaution should be performed in
14709 /// constant context.
14710 ///
14711 /// \returns true if the corresponding C type was found.
14712 static bool GetMatchingCType(
14713     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
14714     const ASTContext &Ctx,
14715     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
14716         *MagicValues,
14717     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
14718     bool isConstantEvaluated) {
14719   FoundWrongKind = false;
14720 
14721   // Variable declaration that has type_tag_for_datatype attribute.
14722   const ValueDecl *VD = nullptr;
14723 
14724   uint64_t MagicValue;
14725 
14726   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
14727     return false;
14728 
14729   if (VD) {
14730     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
14731       if (I->getArgumentKind() != ArgumentKind) {
14732         FoundWrongKind = true;
14733         return false;
14734       }
14735       TypeInfo.Type = I->getMatchingCType();
14736       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
14737       TypeInfo.MustBeNull = I->getMustBeNull();
14738       return true;
14739     }
14740     return false;
14741   }
14742 
14743   if (!MagicValues)
14744     return false;
14745 
14746   llvm::DenseMap<Sema::TypeTagMagicValue,
14747                  Sema::TypeTagData>::const_iterator I =
14748       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
14749   if (I == MagicValues->end())
14750     return false;
14751 
14752   TypeInfo = I->second;
14753   return true;
14754 }
14755 
14756 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
14757                                       uint64_t MagicValue, QualType Type,
14758                                       bool LayoutCompatible,
14759                                       bool MustBeNull) {
14760   if (!TypeTagForDatatypeMagicValues)
14761     TypeTagForDatatypeMagicValues.reset(
14762         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
14763 
14764   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
14765   (*TypeTagForDatatypeMagicValues)[Magic] =
14766       TypeTagData(Type, LayoutCompatible, MustBeNull);
14767 }
14768 
14769 static bool IsSameCharType(QualType T1, QualType T2) {
14770   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
14771   if (!BT1)
14772     return false;
14773 
14774   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
14775   if (!BT2)
14776     return false;
14777 
14778   BuiltinType::Kind T1Kind = BT1->getKind();
14779   BuiltinType::Kind T2Kind = BT2->getKind();
14780 
14781   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
14782          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
14783          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
14784          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
14785 }
14786 
14787 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
14788                                     const ArrayRef<const Expr *> ExprArgs,
14789                                     SourceLocation CallSiteLoc) {
14790   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
14791   bool IsPointerAttr = Attr->getIsPointer();
14792 
14793   // Retrieve the argument representing the 'type_tag'.
14794   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
14795   if (TypeTagIdxAST >= ExprArgs.size()) {
14796     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
14797         << 0 << Attr->getTypeTagIdx().getSourceIndex();
14798     return;
14799   }
14800   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
14801   bool FoundWrongKind;
14802   TypeTagData TypeInfo;
14803   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
14804                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
14805                         TypeInfo, isConstantEvaluated())) {
14806     if (FoundWrongKind)
14807       Diag(TypeTagExpr->getExprLoc(),
14808            diag::warn_type_tag_for_datatype_wrong_kind)
14809         << TypeTagExpr->getSourceRange();
14810     return;
14811   }
14812 
14813   // Retrieve the argument representing the 'arg_idx'.
14814   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
14815   if (ArgumentIdxAST >= ExprArgs.size()) {
14816     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
14817         << 1 << Attr->getArgumentIdx().getSourceIndex();
14818     return;
14819   }
14820   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
14821   if (IsPointerAttr) {
14822     // Skip implicit cast of pointer to `void *' (as a function argument).
14823     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
14824       if (ICE->getType()->isVoidPointerType() &&
14825           ICE->getCastKind() == CK_BitCast)
14826         ArgumentExpr = ICE->getSubExpr();
14827   }
14828   QualType ArgumentType = ArgumentExpr->getType();
14829 
14830   // Passing a `void*' pointer shouldn't trigger a warning.
14831   if (IsPointerAttr && ArgumentType->isVoidPointerType())
14832     return;
14833 
14834   if (TypeInfo.MustBeNull) {
14835     // Type tag with matching void type requires a null pointer.
14836     if (!ArgumentExpr->isNullPointerConstant(Context,
14837                                              Expr::NPC_ValueDependentIsNotNull)) {
14838       Diag(ArgumentExpr->getExprLoc(),
14839            diag::warn_type_safety_null_pointer_required)
14840           << ArgumentKind->getName()
14841           << ArgumentExpr->getSourceRange()
14842           << TypeTagExpr->getSourceRange();
14843     }
14844     return;
14845   }
14846 
14847   QualType RequiredType = TypeInfo.Type;
14848   if (IsPointerAttr)
14849     RequiredType = Context.getPointerType(RequiredType);
14850 
14851   bool mismatch = false;
14852   if (!TypeInfo.LayoutCompatible) {
14853     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
14854 
14855     // C++11 [basic.fundamental] p1:
14856     // Plain char, signed char, and unsigned char are three distinct types.
14857     //
14858     // But we treat plain `char' as equivalent to `signed char' or `unsigned
14859     // char' depending on the current char signedness mode.
14860     if (mismatch)
14861       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
14862                                            RequiredType->getPointeeType())) ||
14863           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
14864         mismatch = false;
14865   } else
14866     if (IsPointerAttr)
14867       mismatch = !isLayoutCompatible(Context,
14868                                      ArgumentType->getPointeeType(),
14869                                      RequiredType->getPointeeType());
14870     else
14871       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
14872 
14873   if (mismatch)
14874     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
14875         << ArgumentType << ArgumentKind
14876         << TypeInfo.LayoutCompatible << RequiredType
14877         << ArgumentExpr->getSourceRange()
14878         << TypeTagExpr->getSourceRange();
14879 }
14880 
14881 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
14882                                          CharUnits Alignment) {
14883   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
14884 }
14885 
14886 void Sema::DiagnoseMisalignedMembers() {
14887   for (MisalignedMember &m : MisalignedMembers) {
14888     const NamedDecl *ND = m.RD;
14889     if (ND->getName().empty()) {
14890       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
14891         ND = TD;
14892     }
14893     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
14894         << m.MD << ND << m.E->getSourceRange();
14895   }
14896   MisalignedMembers.clear();
14897 }
14898 
14899 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
14900   E = E->IgnoreParens();
14901   if (!T->isPointerType() && !T->isIntegerType())
14902     return;
14903   if (isa<UnaryOperator>(E) &&
14904       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
14905     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
14906     if (isa<MemberExpr>(Op)) {
14907       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
14908       if (MA != MisalignedMembers.end() &&
14909           (T->isIntegerType() ||
14910            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
14911                                    Context.getTypeAlignInChars(
14912                                        T->getPointeeType()) <= MA->Alignment))))
14913         MisalignedMembers.erase(MA);
14914     }
14915   }
14916 }
14917 
14918 void Sema::RefersToMemberWithReducedAlignment(
14919     Expr *E,
14920     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
14921         Action) {
14922   const auto *ME = dyn_cast<MemberExpr>(E);
14923   if (!ME)
14924     return;
14925 
14926   // No need to check expressions with an __unaligned-qualified type.
14927   if (E->getType().getQualifiers().hasUnaligned())
14928     return;
14929 
14930   // For a chain of MemberExpr like "a.b.c.d" this list
14931   // will keep FieldDecl's like [d, c, b].
14932   SmallVector<FieldDecl *, 4> ReverseMemberChain;
14933   const MemberExpr *TopME = nullptr;
14934   bool AnyIsPacked = false;
14935   do {
14936     QualType BaseType = ME->getBase()->getType();
14937     if (BaseType->isDependentType())
14938       return;
14939     if (ME->isArrow())
14940       BaseType = BaseType->getPointeeType();
14941     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
14942     if (RD->isInvalidDecl())
14943       return;
14944 
14945     ValueDecl *MD = ME->getMemberDecl();
14946     auto *FD = dyn_cast<FieldDecl>(MD);
14947     // We do not care about non-data members.
14948     if (!FD || FD->isInvalidDecl())
14949       return;
14950 
14951     AnyIsPacked =
14952         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
14953     ReverseMemberChain.push_back(FD);
14954 
14955     TopME = ME;
14956     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
14957   } while (ME);
14958   assert(TopME && "We did not compute a topmost MemberExpr!");
14959 
14960   // Not the scope of this diagnostic.
14961   if (!AnyIsPacked)
14962     return;
14963 
14964   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
14965   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
14966   // TODO: The innermost base of the member expression may be too complicated.
14967   // For now, just disregard these cases. This is left for future
14968   // improvement.
14969   if (!DRE && !isa<CXXThisExpr>(TopBase))
14970       return;
14971 
14972   // Alignment expected by the whole expression.
14973   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
14974 
14975   // No need to do anything else with this case.
14976   if (ExpectedAlignment.isOne())
14977     return;
14978 
14979   // Synthesize offset of the whole access.
14980   CharUnits Offset;
14981   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
14982        I++) {
14983     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
14984   }
14985 
14986   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
14987   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
14988       ReverseMemberChain.back()->getParent()->getTypeForDecl());
14989 
14990   // The base expression of the innermost MemberExpr may give
14991   // stronger guarantees than the class containing the member.
14992   if (DRE && !TopME->isArrow()) {
14993     const ValueDecl *VD = DRE->getDecl();
14994     if (!VD->getType()->isReferenceType())
14995       CompleteObjectAlignment =
14996           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
14997   }
14998 
14999   // Check if the synthesized offset fulfills the alignment.
15000   if (Offset % ExpectedAlignment != 0 ||
15001       // It may fulfill the offset it but the effective alignment may still be
15002       // lower than the expected expression alignment.
15003       CompleteObjectAlignment < ExpectedAlignment) {
15004     // If this happens, we want to determine a sensible culprit of this.
15005     // Intuitively, watching the chain of member expressions from right to
15006     // left, we start with the required alignment (as required by the field
15007     // type) but some packed attribute in that chain has reduced the alignment.
15008     // It may happen that another packed structure increases it again. But if
15009     // we are here such increase has not been enough. So pointing the first
15010     // FieldDecl that either is packed or else its RecordDecl is,
15011     // seems reasonable.
15012     FieldDecl *FD = nullptr;
15013     CharUnits Alignment;
15014     for (FieldDecl *FDI : ReverseMemberChain) {
15015       if (FDI->hasAttr<PackedAttr>() ||
15016           FDI->getParent()->hasAttr<PackedAttr>()) {
15017         FD = FDI;
15018         Alignment = std::min(
15019             Context.getTypeAlignInChars(FD->getType()),
15020             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
15021         break;
15022       }
15023     }
15024     assert(FD && "We did not find a packed FieldDecl!");
15025     Action(E, FD->getParent(), FD, Alignment);
15026   }
15027 }
15028 
15029 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
15030   using namespace std::placeholders;
15031 
15032   RefersToMemberWithReducedAlignment(
15033       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
15034                      _2, _3, _4));
15035 }
15036