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   case Builtin::BI__builtin_matrix_transpose:
1917     return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
1918   }
1919 
1920   // Since the target specific builtins for each arch overlap, only check those
1921   // of the arch we are compiling for.
1922   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1923     if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
1924       assert(Context.getAuxTargetInfo() &&
1925              "Aux Target Builtin, but not an aux target?");
1926 
1927       if (CheckTSBuiltinFunctionCall(
1928               *Context.getAuxTargetInfo(),
1929               Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
1930         return ExprError();
1931     } else {
1932       if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
1933                                      TheCall))
1934         return ExprError();
1935     }
1936   }
1937 
1938   return TheCallResult;
1939 }
1940 
1941 // Get the valid immediate range for the specified NEON type code.
1942 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1943   NeonTypeFlags Type(t);
1944   int IsQuad = ForceQuad ? true : Type.isQuad();
1945   switch (Type.getEltType()) {
1946   case NeonTypeFlags::Int8:
1947   case NeonTypeFlags::Poly8:
1948     return shift ? 7 : (8 << IsQuad) - 1;
1949   case NeonTypeFlags::Int16:
1950   case NeonTypeFlags::Poly16:
1951     return shift ? 15 : (4 << IsQuad) - 1;
1952   case NeonTypeFlags::Int32:
1953     return shift ? 31 : (2 << IsQuad) - 1;
1954   case NeonTypeFlags::Int64:
1955   case NeonTypeFlags::Poly64:
1956     return shift ? 63 : (1 << IsQuad) - 1;
1957   case NeonTypeFlags::Poly128:
1958     return shift ? 127 : (1 << IsQuad) - 1;
1959   case NeonTypeFlags::Float16:
1960     assert(!shift && "cannot shift float types!");
1961     return (4 << IsQuad) - 1;
1962   case NeonTypeFlags::Float32:
1963     assert(!shift && "cannot shift float types!");
1964     return (2 << IsQuad) - 1;
1965   case NeonTypeFlags::Float64:
1966     assert(!shift && "cannot shift float types!");
1967     return (1 << IsQuad) - 1;
1968   case NeonTypeFlags::BFloat16:
1969     assert(!shift && "cannot shift float types!");
1970     return (4 << IsQuad) - 1;
1971   }
1972   llvm_unreachable("Invalid NeonTypeFlag!");
1973 }
1974 
1975 /// getNeonEltType - Return the QualType corresponding to the elements of
1976 /// the vector type specified by the NeonTypeFlags.  This is used to check
1977 /// the pointer arguments for Neon load/store intrinsics.
1978 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
1979                                bool IsPolyUnsigned, bool IsInt64Long) {
1980   switch (Flags.getEltType()) {
1981   case NeonTypeFlags::Int8:
1982     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1983   case NeonTypeFlags::Int16:
1984     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1985   case NeonTypeFlags::Int32:
1986     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1987   case NeonTypeFlags::Int64:
1988     if (IsInt64Long)
1989       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1990     else
1991       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1992                                 : Context.LongLongTy;
1993   case NeonTypeFlags::Poly8:
1994     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
1995   case NeonTypeFlags::Poly16:
1996     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
1997   case NeonTypeFlags::Poly64:
1998     if (IsInt64Long)
1999       return Context.UnsignedLongTy;
2000     else
2001       return Context.UnsignedLongLongTy;
2002   case NeonTypeFlags::Poly128:
2003     break;
2004   case NeonTypeFlags::Float16:
2005     return Context.HalfTy;
2006   case NeonTypeFlags::Float32:
2007     return Context.FloatTy;
2008   case NeonTypeFlags::Float64:
2009     return Context.DoubleTy;
2010   case NeonTypeFlags::BFloat16:
2011     return Context.BFloat16Ty;
2012   }
2013   llvm_unreachable("Invalid NeonTypeFlag!");
2014 }
2015 
2016 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2017   // Range check SVE intrinsics that take immediate values.
2018   SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
2019 
2020   switch (BuiltinID) {
2021   default:
2022     return false;
2023 #define GET_SVE_IMMEDIATE_CHECK
2024 #include "clang/Basic/arm_sve_sema_rangechecks.inc"
2025 #undef GET_SVE_IMMEDIATE_CHECK
2026   }
2027 
2028   // Perform all the immediate checks for this builtin call.
2029   bool HasError = false;
2030   for (auto &I : ImmChecks) {
2031     int ArgNum, CheckTy, ElementSizeInBits;
2032     std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
2033 
2034     typedef bool(*OptionSetCheckFnTy)(int64_t Value);
2035 
2036     // Function that checks whether the operand (ArgNum) is an immediate
2037     // that is one of the predefined values.
2038     auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
2039                                    int ErrDiag) -> bool {
2040       // We can't check the value of a dependent argument.
2041       Expr *Arg = TheCall->getArg(ArgNum);
2042       if (Arg->isTypeDependent() || Arg->isValueDependent())
2043         return false;
2044 
2045       // Check constant-ness first.
2046       llvm::APSInt Imm;
2047       if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
2048         return true;
2049 
2050       if (!CheckImm(Imm.getSExtValue()))
2051         return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
2052       return false;
2053     };
2054 
2055     switch ((SVETypeFlags::ImmCheckType)CheckTy) {
2056     case SVETypeFlags::ImmCheck0_31:
2057       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
2058         HasError = true;
2059       break;
2060     case SVETypeFlags::ImmCheck0_13:
2061       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
2062         HasError = true;
2063       break;
2064     case SVETypeFlags::ImmCheck1_16:
2065       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
2066         HasError = true;
2067       break;
2068     case SVETypeFlags::ImmCheck0_7:
2069       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
2070         HasError = true;
2071       break;
2072     case SVETypeFlags::ImmCheckExtract:
2073       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2074                                       (2048 / ElementSizeInBits) - 1))
2075         HasError = true;
2076       break;
2077     case SVETypeFlags::ImmCheckShiftRight:
2078       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
2079         HasError = true;
2080       break;
2081     case SVETypeFlags::ImmCheckShiftRightNarrow:
2082       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
2083                                       ElementSizeInBits / 2))
2084         HasError = true;
2085       break;
2086     case SVETypeFlags::ImmCheckShiftLeft:
2087       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2088                                       ElementSizeInBits - 1))
2089         HasError = true;
2090       break;
2091     case SVETypeFlags::ImmCheckLaneIndex:
2092       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2093                                       (128 / (1 * ElementSizeInBits)) - 1))
2094         HasError = true;
2095       break;
2096     case SVETypeFlags::ImmCheckLaneIndexCompRotate:
2097       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2098                                       (128 / (2 * ElementSizeInBits)) - 1))
2099         HasError = true;
2100       break;
2101     case SVETypeFlags::ImmCheckLaneIndexDot:
2102       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2103                                       (128 / (4 * ElementSizeInBits)) - 1))
2104         HasError = true;
2105       break;
2106     case SVETypeFlags::ImmCheckComplexRot90_270:
2107       if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
2108                               diag::err_rotation_argument_to_cadd))
2109         HasError = true;
2110       break;
2111     case SVETypeFlags::ImmCheckComplexRotAll90:
2112       if (CheckImmediateInSet(
2113               [](int64_t V) {
2114                 return V == 0 || V == 90 || V == 180 || V == 270;
2115               },
2116               diag::err_rotation_argument_to_cmla))
2117         HasError = true;
2118       break;
2119     }
2120   }
2121 
2122   return HasError;
2123 }
2124 
2125 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
2126                                         unsigned BuiltinID, CallExpr *TheCall) {
2127   llvm::APSInt Result;
2128   uint64_t mask = 0;
2129   unsigned TV = 0;
2130   int PtrArgNum = -1;
2131   bool HasConstPtr = false;
2132   switch (BuiltinID) {
2133 #define GET_NEON_OVERLOAD_CHECK
2134 #include "clang/Basic/arm_neon.inc"
2135 #include "clang/Basic/arm_fp16.inc"
2136 #undef GET_NEON_OVERLOAD_CHECK
2137   }
2138 
2139   // For NEON intrinsics which are overloaded on vector element type, validate
2140   // the immediate which specifies which variant to emit.
2141   unsigned ImmArg = TheCall->getNumArgs()-1;
2142   if (mask) {
2143     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
2144       return true;
2145 
2146     TV = Result.getLimitedValue(64);
2147     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
2148       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
2149              << TheCall->getArg(ImmArg)->getSourceRange();
2150   }
2151 
2152   if (PtrArgNum >= 0) {
2153     // Check that pointer arguments have the specified type.
2154     Expr *Arg = TheCall->getArg(PtrArgNum);
2155     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
2156       Arg = ICE->getSubExpr();
2157     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
2158     QualType RHSTy = RHS.get()->getType();
2159 
2160     llvm::Triple::ArchType Arch = TI.getTriple().getArch();
2161     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2162                           Arch == llvm::Triple::aarch64_32 ||
2163                           Arch == llvm::Triple::aarch64_be;
2164     bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
2165     QualType EltTy =
2166         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2167     if (HasConstPtr)
2168       EltTy = EltTy.withConst();
2169     QualType LHSTy = Context.getPointerType(EltTy);
2170     AssignConvertType ConvTy;
2171     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2172     if (RHS.isInvalid())
2173       return true;
2174     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2175                                  RHS.get(), AA_Assigning))
2176       return true;
2177   }
2178 
2179   // For NEON intrinsics which take an immediate value as part of the
2180   // instruction, range check them here.
2181   unsigned i = 0, l = 0, u = 0;
2182   switch (BuiltinID) {
2183   default:
2184     return false;
2185   #define GET_NEON_IMMEDIATE_CHECK
2186   #include "clang/Basic/arm_neon.inc"
2187   #include "clang/Basic/arm_fp16.inc"
2188   #undef GET_NEON_IMMEDIATE_CHECK
2189   }
2190 
2191   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2192 }
2193 
2194 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2195   switch (BuiltinID) {
2196   default:
2197     return false;
2198   #include "clang/Basic/arm_mve_builtin_sema.inc"
2199   }
2200 }
2201 
2202 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2203                                        CallExpr *TheCall) {
2204   bool Err = false;
2205   switch (BuiltinID) {
2206   default:
2207     return false;
2208 #include "clang/Basic/arm_cde_builtin_sema.inc"
2209   }
2210 
2211   if (Err)
2212     return true;
2213 
2214   return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
2215 }
2216 
2217 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
2218                                         const Expr *CoprocArg, bool WantCDE) {
2219   if (isConstantEvaluated())
2220     return false;
2221 
2222   // We can't check the value of a dependent argument.
2223   if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
2224     return false;
2225 
2226   llvm::APSInt CoprocNoAP;
2227   bool IsICE = CoprocArg->isIntegerConstantExpr(CoprocNoAP, Context);
2228   (void)IsICE;
2229   assert(IsICE && "Coprocossor immediate is not a constant expression");
2230   int64_t CoprocNo = CoprocNoAP.getExtValue();
2231   assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
2232 
2233   uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
2234   bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
2235 
2236   if (IsCDECoproc != WantCDE)
2237     return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
2238            << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
2239 
2240   return false;
2241 }
2242 
2243 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2244                                         unsigned MaxWidth) {
2245   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
2246           BuiltinID == ARM::BI__builtin_arm_ldaex ||
2247           BuiltinID == ARM::BI__builtin_arm_strex ||
2248           BuiltinID == ARM::BI__builtin_arm_stlex ||
2249           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2250           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2251           BuiltinID == AArch64::BI__builtin_arm_strex ||
2252           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
2253          "unexpected ARM builtin");
2254   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2255                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
2256                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2257                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
2258 
2259   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2260 
2261   // Ensure that we have the proper number of arguments.
2262   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
2263     return true;
2264 
2265   // Inspect the pointer argument of the atomic builtin.  This should always be
2266   // a pointer type, whose element is an integral scalar or pointer type.
2267   // Because it is a pointer type, we don't have to worry about any implicit
2268   // casts here.
2269   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
2270   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
2271   if (PointerArgRes.isInvalid())
2272     return true;
2273   PointerArg = PointerArgRes.get();
2274 
2275   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2276   if (!pointerType) {
2277     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
2278         << PointerArg->getType() << PointerArg->getSourceRange();
2279     return true;
2280   }
2281 
2282   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
2283   // task is to insert the appropriate casts into the AST. First work out just
2284   // what the appropriate type is.
2285   QualType ValType = pointerType->getPointeeType();
2286   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
2287   if (IsLdrex)
2288     AddrType.addConst();
2289 
2290   // Issue a warning if the cast is dodgy.
2291   CastKind CastNeeded = CK_NoOp;
2292   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
2293     CastNeeded = CK_BitCast;
2294     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
2295         << PointerArg->getType() << Context.getPointerType(AddrType)
2296         << AA_Passing << PointerArg->getSourceRange();
2297   }
2298 
2299   // Finally, do the cast and replace the argument with the corrected version.
2300   AddrType = Context.getPointerType(AddrType);
2301   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
2302   if (PointerArgRes.isInvalid())
2303     return true;
2304   PointerArg = PointerArgRes.get();
2305 
2306   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
2307 
2308   // In general, we allow ints, floats and pointers to be loaded and stored.
2309   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2310       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
2311     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
2312         << PointerArg->getType() << PointerArg->getSourceRange();
2313     return true;
2314   }
2315 
2316   // But ARM doesn't have instructions to deal with 128-bit versions.
2317   if (Context.getTypeSize(ValType) > MaxWidth) {
2318     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
2319     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
2320         << PointerArg->getType() << PointerArg->getSourceRange();
2321     return true;
2322   }
2323 
2324   switch (ValType.getObjCLifetime()) {
2325   case Qualifiers::OCL_None:
2326   case Qualifiers::OCL_ExplicitNone:
2327     // okay
2328     break;
2329 
2330   case Qualifiers::OCL_Weak:
2331   case Qualifiers::OCL_Strong:
2332   case Qualifiers::OCL_Autoreleasing:
2333     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
2334         << ValType << PointerArg->getSourceRange();
2335     return true;
2336   }
2337 
2338   if (IsLdrex) {
2339     TheCall->setType(ValType);
2340     return false;
2341   }
2342 
2343   // Initialize the argument to be stored.
2344   ExprResult ValArg = TheCall->getArg(0);
2345   InitializedEntity Entity = InitializedEntity::InitializeParameter(
2346       Context, ValType, /*consume*/ false);
2347   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2348   if (ValArg.isInvalid())
2349     return true;
2350   TheCall->setArg(0, ValArg.get());
2351 
2352   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
2353   // but the custom checker bypasses all default analysis.
2354   TheCall->setType(Context.IntTy);
2355   return false;
2356 }
2357 
2358 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2359                                        CallExpr *TheCall) {
2360   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
2361       BuiltinID == ARM::BI__builtin_arm_ldaex ||
2362       BuiltinID == ARM::BI__builtin_arm_strex ||
2363       BuiltinID == ARM::BI__builtin_arm_stlex) {
2364     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
2365   }
2366 
2367   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
2368     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2369       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
2370   }
2371 
2372   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2373       BuiltinID == ARM::BI__builtin_arm_wsr64)
2374     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
2375 
2376   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
2377       BuiltinID == ARM::BI__builtin_arm_rsrp ||
2378       BuiltinID == ARM::BI__builtin_arm_wsr ||
2379       BuiltinID == ARM::BI__builtin_arm_wsrp)
2380     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2381 
2382   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2383     return true;
2384   if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
2385     return true;
2386   if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
2387     return true;
2388 
2389   // For intrinsics which take an immediate value as part of the instruction,
2390   // range check them here.
2391   // FIXME: VFP Intrinsics should error if VFP not present.
2392   switch (BuiltinID) {
2393   default: return false;
2394   case ARM::BI__builtin_arm_ssat:
2395     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
2396   case ARM::BI__builtin_arm_usat:
2397     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
2398   case ARM::BI__builtin_arm_ssat16:
2399     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
2400   case ARM::BI__builtin_arm_usat16:
2401     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2402   case ARM::BI__builtin_arm_vcvtr_f:
2403   case ARM::BI__builtin_arm_vcvtr_d:
2404     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2405   case ARM::BI__builtin_arm_dmb:
2406   case ARM::BI__builtin_arm_dsb:
2407   case ARM::BI__builtin_arm_isb:
2408   case ARM::BI__builtin_arm_dbg:
2409     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
2410   case ARM::BI__builtin_arm_cdp:
2411   case ARM::BI__builtin_arm_cdp2:
2412   case ARM::BI__builtin_arm_mcr:
2413   case ARM::BI__builtin_arm_mcr2:
2414   case ARM::BI__builtin_arm_mrc:
2415   case ARM::BI__builtin_arm_mrc2:
2416   case ARM::BI__builtin_arm_mcrr:
2417   case ARM::BI__builtin_arm_mcrr2:
2418   case ARM::BI__builtin_arm_mrrc:
2419   case ARM::BI__builtin_arm_mrrc2:
2420   case ARM::BI__builtin_arm_ldc:
2421   case ARM::BI__builtin_arm_ldcl:
2422   case ARM::BI__builtin_arm_ldc2:
2423   case ARM::BI__builtin_arm_ldc2l:
2424   case ARM::BI__builtin_arm_stc:
2425   case ARM::BI__builtin_arm_stcl:
2426   case ARM::BI__builtin_arm_stc2:
2427   case ARM::BI__builtin_arm_stc2l:
2428     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
2429            CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
2430                                         /*WantCDE*/ false);
2431   }
2432 }
2433 
2434 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
2435                                            unsigned BuiltinID,
2436                                            CallExpr *TheCall) {
2437   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2438       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2439       BuiltinID == AArch64::BI__builtin_arm_strex ||
2440       BuiltinID == AArch64::BI__builtin_arm_stlex) {
2441     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
2442   }
2443 
2444   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
2445     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2446       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
2447       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2448       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2449   }
2450 
2451   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2452       BuiltinID == AArch64::BI__builtin_arm_wsr64)
2453     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2454 
2455   // Memory Tagging Extensions (MTE) Intrinsics
2456   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2457       BuiltinID == AArch64::BI__builtin_arm_addg ||
2458       BuiltinID == AArch64::BI__builtin_arm_gmi ||
2459       BuiltinID == AArch64::BI__builtin_arm_ldg ||
2460       BuiltinID == AArch64::BI__builtin_arm_stg ||
2461       BuiltinID == AArch64::BI__builtin_arm_subp) {
2462     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2463   }
2464 
2465   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2466       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2467       BuiltinID == AArch64::BI__builtin_arm_wsr ||
2468       BuiltinID == AArch64::BI__builtin_arm_wsrp)
2469     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2470 
2471   // Only check the valid encoding range. Any constant in this range would be
2472   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2473   // an exception for incorrect registers. This matches MSVC behavior.
2474   if (BuiltinID == AArch64::BI_ReadStatusReg ||
2475       BuiltinID == AArch64::BI_WriteStatusReg)
2476     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2477 
2478   if (BuiltinID == AArch64::BI__getReg)
2479     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2480 
2481   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2482     return true;
2483 
2484   if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
2485     return true;
2486 
2487   // For intrinsics which take an immediate value as part of the instruction,
2488   // range check them here.
2489   unsigned i = 0, l = 0, u = 0;
2490   switch (BuiltinID) {
2491   default: return false;
2492   case AArch64::BI__builtin_arm_dmb:
2493   case AArch64::BI__builtin_arm_dsb:
2494   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2495   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2496   }
2497 
2498   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2499 }
2500 
2501 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
2502                                        CallExpr *TheCall) {
2503   assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
2504           BuiltinID == BPF::BI__builtin_btf_type_id) &&
2505          "unexpected ARM builtin");
2506 
2507   if (checkArgCount(*this, TheCall, 2))
2508     return true;
2509 
2510   Expr *Arg;
2511   if (BuiltinID == BPF::BI__builtin_btf_type_id) {
2512     // The second argument needs to be a constant int
2513     llvm::APSInt Value;
2514     Arg = TheCall->getArg(1);
2515     if (!Arg->isIntegerConstantExpr(Value, Context)) {
2516       Diag(Arg->getBeginLoc(), diag::err_btf_type_id_not_const)
2517           << 2 << Arg->getSourceRange();
2518       return true;
2519     }
2520 
2521     TheCall->setType(Context.UnsignedIntTy);
2522     return false;
2523   }
2524 
2525   // The first argument needs to be a record field access.
2526   // If it is an array element access, we delay decision
2527   // to BPF backend to check whether the access is a
2528   // field access or not.
2529   Arg = TheCall->getArg(0);
2530   if (Arg->getType()->getAsPlaceholderType() ||
2531       (Arg->IgnoreParens()->getObjectKind() != OK_BitField &&
2532        !dyn_cast<MemberExpr>(Arg->IgnoreParens()) &&
2533        !dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()))) {
2534     Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_field)
2535         << 1 << Arg->getSourceRange();
2536     return true;
2537   }
2538 
2539   // The second argument needs to be a constant int
2540   Arg = TheCall->getArg(1);
2541   llvm::APSInt Value;
2542   if (!Arg->isIntegerConstantExpr(Value, Context)) {
2543     Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_const)
2544         << 2 << Arg->getSourceRange();
2545     return true;
2546   }
2547 
2548   TheCall->setType(Context.UnsignedIntTy);
2549   return false;
2550 }
2551 
2552 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2553   struct ArgInfo {
2554     uint8_t OpNum;
2555     bool IsSigned;
2556     uint8_t BitWidth;
2557     uint8_t Align;
2558   };
2559   struct BuiltinInfo {
2560     unsigned BuiltinID;
2561     ArgInfo Infos[2];
2562   };
2563 
2564   static BuiltinInfo Infos[] = {
2565     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2566     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2567     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2568     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  1 }} },
2569     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2570     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2571     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2572     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2573     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2574     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2575     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2576 
2577     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2578     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2579     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2580     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2581     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2582     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2583     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2584     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2585     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2586     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2587     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2588 
2589     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2590     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2591     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2592     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2593     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2594     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2595     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2596     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2597     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2598     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2599     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2600     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2601     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2602     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2603     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2604     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2605     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2606     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2607     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2608     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2609     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2610     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2611     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2612     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2613     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2614     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2615     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2616     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2617     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2618     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2619     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2620     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
2621     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
2622     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
2623     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
2624     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
2625     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
2626     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
2627     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
2628     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
2629     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
2630     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
2631     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
2632     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
2633     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
2634     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
2635     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
2636     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
2637     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
2638     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
2639     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
2640     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2641                                                       {{ 1, false, 6,  0 }} },
2642     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
2643     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
2644     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
2645     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
2646     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
2647     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
2648     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2649                                                       {{ 1, false, 5,  0 }} },
2650     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
2651     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
2652     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
2653     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
2654     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
2655     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
2656                                                        { 2, false, 5,  0 }} },
2657     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
2658                                                        { 2, false, 6,  0 }} },
2659     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
2660                                                        { 3, false, 5,  0 }} },
2661     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
2662                                                        { 3, false, 6,  0 }} },
2663     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
2664     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
2665     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
2666     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
2667     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
2668     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
2669     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
2670     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
2671     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
2672     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
2673     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
2674     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
2675     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
2676     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
2677     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
2678     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2679                                                       {{ 2, false, 4,  0 },
2680                                                        { 3, false, 5,  0 }} },
2681     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2682                                                       {{ 2, false, 4,  0 },
2683                                                        { 3, false, 5,  0 }} },
2684     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2685                                                       {{ 2, false, 4,  0 },
2686                                                        { 3, false, 5,  0 }} },
2687     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2688                                                       {{ 2, false, 4,  0 },
2689                                                        { 3, false, 5,  0 }} },
2690     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
2691     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
2692     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
2693     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
2694     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
2695     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
2696     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
2697     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
2698     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
2699     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
2700     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
2701                                                        { 2, false, 5,  0 }} },
2702     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
2703                                                        { 2, false, 6,  0 }} },
2704     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
2705     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
2706     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
2707     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
2708     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
2709     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
2710     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
2711     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
2712     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2713                                                       {{ 1, false, 4,  0 }} },
2714     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
2715     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2716                                                       {{ 1, false, 4,  0 }} },
2717     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
2718     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
2719     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
2720     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
2721     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
2722     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
2723     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
2724     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
2725     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
2726     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
2727     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
2728     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
2729     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
2730     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
2731     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
2732     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
2733     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
2734     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
2735     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
2736     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2737                                                       {{ 3, false, 1,  0 }} },
2738     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
2739     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
2740     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
2741     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2742                                                       {{ 3, false, 1,  0 }} },
2743     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
2744     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
2745     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
2746     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2747                                                       {{ 3, false, 1,  0 }} },
2748   };
2749 
2750   // Use a dynamically initialized static to sort the table exactly once on
2751   // first run.
2752   static const bool SortOnce =
2753       (llvm::sort(Infos,
2754                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
2755                    return LHS.BuiltinID < RHS.BuiltinID;
2756                  }),
2757        true);
2758   (void)SortOnce;
2759 
2760   const BuiltinInfo *F = llvm::partition_point(
2761       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
2762   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
2763     return false;
2764 
2765   bool Error = false;
2766 
2767   for (const ArgInfo &A : F->Infos) {
2768     // Ignore empty ArgInfo elements.
2769     if (A.BitWidth == 0)
2770       continue;
2771 
2772     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
2773     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
2774     if (!A.Align) {
2775       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2776     } else {
2777       unsigned M = 1 << A.Align;
2778       Min *= M;
2779       Max *= M;
2780       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
2781                SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
2782     }
2783   }
2784   return Error;
2785 }
2786 
2787 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
2788                                            CallExpr *TheCall) {
2789   return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
2790 }
2791 
2792 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
2793                                         unsigned BuiltinID, CallExpr *TheCall) {
2794   return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
2795          CheckMipsBuiltinArgument(BuiltinID, TheCall);
2796 }
2797 
2798 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
2799                                CallExpr *TheCall) {
2800 
2801   if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
2802       BuiltinID <= Mips::BI__builtin_mips_lwx) {
2803     if (!TI.hasFeature("dsp"))
2804       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
2805   }
2806 
2807   if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
2808       BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
2809     if (!TI.hasFeature("dspr2"))
2810       return Diag(TheCall->getBeginLoc(),
2811                   diag::err_mips_builtin_requires_dspr2);
2812   }
2813 
2814   if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
2815       BuiltinID <= Mips::BI__builtin_msa_xori_b) {
2816     if (!TI.hasFeature("msa"))
2817       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
2818   }
2819 
2820   return false;
2821 }
2822 
2823 // CheckMipsBuiltinArgument - Checks the constant value passed to the
2824 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
2825 // ordering for DSP is unspecified. MSA is ordered by the data format used
2826 // by the underlying instruction i.e., df/m, df/n and then by size.
2827 //
2828 // FIXME: The size tests here should instead be tablegen'd along with the
2829 //        definitions from include/clang/Basic/BuiltinsMips.def.
2830 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
2831 //        be too.
2832 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2833   unsigned i = 0, l = 0, u = 0, m = 0;
2834   switch (BuiltinID) {
2835   default: return false;
2836   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
2837   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
2838   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
2839   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
2840   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
2841   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
2842   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
2843   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
2844   // df/m field.
2845   // These intrinsics take an unsigned 3 bit immediate.
2846   case Mips::BI__builtin_msa_bclri_b:
2847   case Mips::BI__builtin_msa_bnegi_b:
2848   case Mips::BI__builtin_msa_bseti_b:
2849   case Mips::BI__builtin_msa_sat_s_b:
2850   case Mips::BI__builtin_msa_sat_u_b:
2851   case Mips::BI__builtin_msa_slli_b:
2852   case Mips::BI__builtin_msa_srai_b:
2853   case Mips::BI__builtin_msa_srari_b:
2854   case Mips::BI__builtin_msa_srli_b:
2855   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
2856   case Mips::BI__builtin_msa_binsli_b:
2857   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
2858   // These intrinsics take an unsigned 4 bit immediate.
2859   case Mips::BI__builtin_msa_bclri_h:
2860   case Mips::BI__builtin_msa_bnegi_h:
2861   case Mips::BI__builtin_msa_bseti_h:
2862   case Mips::BI__builtin_msa_sat_s_h:
2863   case Mips::BI__builtin_msa_sat_u_h:
2864   case Mips::BI__builtin_msa_slli_h:
2865   case Mips::BI__builtin_msa_srai_h:
2866   case Mips::BI__builtin_msa_srari_h:
2867   case Mips::BI__builtin_msa_srli_h:
2868   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
2869   case Mips::BI__builtin_msa_binsli_h:
2870   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
2871   // These intrinsics take an unsigned 5 bit immediate.
2872   // The first block of intrinsics actually have an unsigned 5 bit field,
2873   // not a df/n field.
2874   case Mips::BI__builtin_msa_cfcmsa:
2875   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
2876   case Mips::BI__builtin_msa_clei_u_b:
2877   case Mips::BI__builtin_msa_clei_u_h:
2878   case Mips::BI__builtin_msa_clei_u_w:
2879   case Mips::BI__builtin_msa_clei_u_d:
2880   case Mips::BI__builtin_msa_clti_u_b:
2881   case Mips::BI__builtin_msa_clti_u_h:
2882   case Mips::BI__builtin_msa_clti_u_w:
2883   case Mips::BI__builtin_msa_clti_u_d:
2884   case Mips::BI__builtin_msa_maxi_u_b:
2885   case Mips::BI__builtin_msa_maxi_u_h:
2886   case Mips::BI__builtin_msa_maxi_u_w:
2887   case Mips::BI__builtin_msa_maxi_u_d:
2888   case Mips::BI__builtin_msa_mini_u_b:
2889   case Mips::BI__builtin_msa_mini_u_h:
2890   case Mips::BI__builtin_msa_mini_u_w:
2891   case Mips::BI__builtin_msa_mini_u_d:
2892   case Mips::BI__builtin_msa_addvi_b:
2893   case Mips::BI__builtin_msa_addvi_h:
2894   case Mips::BI__builtin_msa_addvi_w:
2895   case Mips::BI__builtin_msa_addvi_d:
2896   case Mips::BI__builtin_msa_bclri_w:
2897   case Mips::BI__builtin_msa_bnegi_w:
2898   case Mips::BI__builtin_msa_bseti_w:
2899   case Mips::BI__builtin_msa_sat_s_w:
2900   case Mips::BI__builtin_msa_sat_u_w:
2901   case Mips::BI__builtin_msa_slli_w:
2902   case Mips::BI__builtin_msa_srai_w:
2903   case Mips::BI__builtin_msa_srari_w:
2904   case Mips::BI__builtin_msa_srli_w:
2905   case Mips::BI__builtin_msa_srlri_w:
2906   case Mips::BI__builtin_msa_subvi_b:
2907   case Mips::BI__builtin_msa_subvi_h:
2908   case Mips::BI__builtin_msa_subvi_w:
2909   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
2910   case Mips::BI__builtin_msa_binsli_w:
2911   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
2912   // These intrinsics take an unsigned 6 bit immediate.
2913   case Mips::BI__builtin_msa_bclri_d:
2914   case Mips::BI__builtin_msa_bnegi_d:
2915   case Mips::BI__builtin_msa_bseti_d:
2916   case Mips::BI__builtin_msa_sat_s_d:
2917   case Mips::BI__builtin_msa_sat_u_d:
2918   case Mips::BI__builtin_msa_slli_d:
2919   case Mips::BI__builtin_msa_srai_d:
2920   case Mips::BI__builtin_msa_srari_d:
2921   case Mips::BI__builtin_msa_srli_d:
2922   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
2923   case Mips::BI__builtin_msa_binsli_d:
2924   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
2925   // These intrinsics take a signed 5 bit immediate.
2926   case Mips::BI__builtin_msa_ceqi_b:
2927   case Mips::BI__builtin_msa_ceqi_h:
2928   case Mips::BI__builtin_msa_ceqi_w:
2929   case Mips::BI__builtin_msa_ceqi_d:
2930   case Mips::BI__builtin_msa_clti_s_b:
2931   case Mips::BI__builtin_msa_clti_s_h:
2932   case Mips::BI__builtin_msa_clti_s_w:
2933   case Mips::BI__builtin_msa_clti_s_d:
2934   case Mips::BI__builtin_msa_clei_s_b:
2935   case Mips::BI__builtin_msa_clei_s_h:
2936   case Mips::BI__builtin_msa_clei_s_w:
2937   case Mips::BI__builtin_msa_clei_s_d:
2938   case Mips::BI__builtin_msa_maxi_s_b:
2939   case Mips::BI__builtin_msa_maxi_s_h:
2940   case Mips::BI__builtin_msa_maxi_s_w:
2941   case Mips::BI__builtin_msa_maxi_s_d:
2942   case Mips::BI__builtin_msa_mini_s_b:
2943   case Mips::BI__builtin_msa_mini_s_h:
2944   case Mips::BI__builtin_msa_mini_s_w:
2945   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
2946   // These intrinsics take an unsigned 8 bit immediate.
2947   case Mips::BI__builtin_msa_andi_b:
2948   case Mips::BI__builtin_msa_nori_b:
2949   case Mips::BI__builtin_msa_ori_b:
2950   case Mips::BI__builtin_msa_shf_b:
2951   case Mips::BI__builtin_msa_shf_h:
2952   case Mips::BI__builtin_msa_shf_w:
2953   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
2954   case Mips::BI__builtin_msa_bseli_b:
2955   case Mips::BI__builtin_msa_bmnzi_b:
2956   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
2957   // df/n format
2958   // These intrinsics take an unsigned 4 bit immediate.
2959   case Mips::BI__builtin_msa_copy_s_b:
2960   case Mips::BI__builtin_msa_copy_u_b:
2961   case Mips::BI__builtin_msa_insve_b:
2962   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
2963   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
2964   // These intrinsics take an unsigned 3 bit immediate.
2965   case Mips::BI__builtin_msa_copy_s_h:
2966   case Mips::BI__builtin_msa_copy_u_h:
2967   case Mips::BI__builtin_msa_insve_h:
2968   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
2969   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
2970   // These intrinsics take an unsigned 2 bit immediate.
2971   case Mips::BI__builtin_msa_copy_s_w:
2972   case Mips::BI__builtin_msa_copy_u_w:
2973   case Mips::BI__builtin_msa_insve_w:
2974   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
2975   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
2976   // These intrinsics take an unsigned 1 bit immediate.
2977   case Mips::BI__builtin_msa_copy_s_d:
2978   case Mips::BI__builtin_msa_copy_u_d:
2979   case Mips::BI__builtin_msa_insve_d:
2980   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
2981   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
2982   // Memory offsets and immediate loads.
2983   // These intrinsics take a signed 10 bit immediate.
2984   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
2985   case Mips::BI__builtin_msa_ldi_h:
2986   case Mips::BI__builtin_msa_ldi_w:
2987   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
2988   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
2989   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
2990   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
2991   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
2992   case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
2993   case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
2994   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
2995   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
2996   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
2997   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
2998   case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
2999   case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
3000   }
3001 
3002   if (!m)
3003     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3004 
3005   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3006          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3007 }
3008 
3009 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3010                                        CallExpr *TheCall) {
3011   unsigned i = 0, l = 0, u = 0;
3012   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
3013                       BuiltinID == PPC::BI__builtin_divdeu ||
3014                       BuiltinID == PPC::BI__builtin_bpermd;
3015   bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
3016   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
3017                        BuiltinID == PPC::BI__builtin_divweu ||
3018                        BuiltinID == PPC::BI__builtin_divde ||
3019                        BuiltinID == PPC::BI__builtin_divdeu;
3020 
3021   if (Is64BitBltin && !IsTarget64Bit)
3022     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3023            << TheCall->getSourceRange();
3024 
3025   if ((IsBltinExtDiv && !TI.hasFeature("extdiv")) ||
3026       (BuiltinID == PPC::BI__builtin_bpermd && !TI.hasFeature("bpermd")))
3027     return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3028            << TheCall->getSourceRange();
3029 
3030   auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
3031     if (!TI.hasFeature("vsx"))
3032       return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3033              << TheCall->getSourceRange();
3034     return false;
3035   };
3036 
3037   switch (BuiltinID) {
3038   default: return false;
3039   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3040   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3041     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3042            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3043   case PPC::BI__builtin_altivec_dss:
3044     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3045   case PPC::BI__builtin_tbegin:
3046   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3047   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3048   case PPC::BI__builtin_tabortwc:
3049   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3050   case PPC::BI__builtin_tabortwci:
3051   case PPC::BI__builtin_tabortdci:
3052     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3053            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3054   case PPC::BI__builtin_altivec_dst:
3055   case PPC::BI__builtin_altivec_dstt:
3056   case PPC::BI__builtin_altivec_dstst:
3057   case PPC::BI__builtin_altivec_dststt:
3058     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3059   case PPC::BI__builtin_vsx_xxpermdi:
3060   case PPC::BI__builtin_vsx_xxsldwi:
3061     return SemaBuiltinVSX(TheCall);
3062   case PPC::BI__builtin_unpack_vector_int128:
3063     return SemaVSXCheck(TheCall) ||
3064            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3065   case PPC::BI__builtin_pack_vector_int128:
3066     return SemaVSXCheck(TheCall);
3067   }
3068   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3069 }
3070 
3071 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
3072                                           CallExpr *TheCall) {
3073   switch (BuiltinID) {
3074   case AMDGPU::BI__builtin_amdgcn_fence: {
3075     ExprResult Arg = TheCall->getArg(0);
3076     auto ArgExpr = Arg.get();
3077     Expr::EvalResult ArgResult;
3078 
3079     if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
3080       return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
3081              << ArgExpr->getType();
3082     int ord = ArgResult.Val.getInt().getZExtValue();
3083 
3084     // Check valididty of memory ordering as per C11 / C++11's memody model.
3085     switch (static_cast<llvm::AtomicOrderingCABI>(ord)) {
3086     case llvm::AtomicOrderingCABI::acquire:
3087     case llvm::AtomicOrderingCABI::release:
3088     case llvm::AtomicOrderingCABI::acq_rel:
3089     case llvm::AtomicOrderingCABI::seq_cst:
3090       break;
3091     default: {
3092       return Diag(ArgExpr->getBeginLoc(),
3093                   diag::warn_atomic_op_has_invalid_memory_order)
3094              << ArgExpr->getSourceRange();
3095     }
3096     }
3097 
3098     Arg = TheCall->getArg(1);
3099     ArgExpr = Arg.get();
3100     Expr::EvalResult ArgResult1;
3101     // Check that sync scope is a constant literal
3102     if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Expr::EvaluateForCodeGen,
3103                                          Context))
3104       return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
3105              << ArgExpr->getType();
3106   } break;
3107   }
3108   return false;
3109 }
3110 
3111 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3112                                            CallExpr *TheCall) {
3113   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3114     Expr *Arg = TheCall->getArg(0);
3115     llvm::APSInt AbortCode(32);
3116     if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
3117         AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
3118       return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3119              << Arg->getSourceRange();
3120   }
3121 
3122   // For intrinsics which take an immediate value as part of the instruction,
3123   // range check them here.
3124   unsigned i = 0, l = 0, u = 0;
3125   switch (BuiltinID) {
3126   default: return false;
3127   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3128   case SystemZ::BI__builtin_s390_verimb:
3129   case SystemZ::BI__builtin_s390_verimh:
3130   case SystemZ::BI__builtin_s390_verimf:
3131   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3132   case SystemZ::BI__builtin_s390_vfaeb:
3133   case SystemZ::BI__builtin_s390_vfaeh:
3134   case SystemZ::BI__builtin_s390_vfaef:
3135   case SystemZ::BI__builtin_s390_vfaebs:
3136   case SystemZ::BI__builtin_s390_vfaehs:
3137   case SystemZ::BI__builtin_s390_vfaefs:
3138   case SystemZ::BI__builtin_s390_vfaezb:
3139   case SystemZ::BI__builtin_s390_vfaezh:
3140   case SystemZ::BI__builtin_s390_vfaezf:
3141   case SystemZ::BI__builtin_s390_vfaezbs:
3142   case SystemZ::BI__builtin_s390_vfaezhs:
3143   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3144   case SystemZ::BI__builtin_s390_vfisb:
3145   case SystemZ::BI__builtin_s390_vfidb:
3146     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3147            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3148   case SystemZ::BI__builtin_s390_vftcisb:
3149   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3150   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3151   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3152   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3153   case SystemZ::BI__builtin_s390_vstrcb:
3154   case SystemZ::BI__builtin_s390_vstrch:
3155   case SystemZ::BI__builtin_s390_vstrcf:
3156   case SystemZ::BI__builtin_s390_vstrczb:
3157   case SystemZ::BI__builtin_s390_vstrczh:
3158   case SystemZ::BI__builtin_s390_vstrczf:
3159   case SystemZ::BI__builtin_s390_vstrcbs:
3160   case SystemZ::BI__builtin_s390_vstrchs:
3161   case SystemZ::BI__builtin_s390_vstrcfs:
3162   case SystemZ::BI__builtin_s390_vstrczbs:
3163   case SystemZ::BI__builtin_s390_vstrczhs:
3164   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3165   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3166   case SystemZ::BI__builtin_s390_vfminsb:
3167   case SystemZ::BI__builtin_s390_vfmaxsb:
3168   case SystemZ::BI__builtin_s390_vfmindb:
3169   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3170   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
3171   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
3172   }
3173   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3174 }
3175 
3176 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3177 /// This checks that the target supports __builtin_cpu_supports and
3178 /// that the string argument is constant and valid.
3179 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
3180                                    CallExpr *TheCall) {
3181   Expr *Arg = TheCall->getArg(0);
3182 
3183   // Check if the argument is a string literal.
3184   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3185     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3186            << Arg->getSourceRange();
3187 
3188   // Check the contents of the string.
3189   StringRef Feature =
3190       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3191   if (!TI.validateCpuSupports(Feature))
3192     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3193            << Arg->getSourceRange();
3194   return false;
3195 }
3196 
3197 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3198 /// This checks that the target supports __builtin_cpu_is and
3199 /// that the string argument is constant and valid.
3200 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
3201   Expr *Arg = TheCall->getArg(0);
3202 
3203   // Check if the argument is a string literal.
3204   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3205     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3206            << Arg->getSourceRange();
3207 
3208   // Check the contents of the string.
3209   StringRef Feature =
3210       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3211   if (!TI.validateCpuIs(Feature))
3212     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3213            << Arg->getSourceRange();
3214   return false;
3215 }
3216 
3217 // Check if the rounding mode is legal.
3218 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3219   // Indicates if this instruction has rounding control or just SAE.
3220   bool HasRC = false;
3221 
3222   unsigned ArgNum = 0;
3223   switch (BuiltinID) {
3224   default:
3225     return false;
3226   case X86::BI__builtin_ia32_vcvttsd2si32:
3227   case X86::BI__builtin_ia32_vcvttsd2si64:
3228   case X86::BI__builtin_ia32_vcvttsd2usi32:
3229   case X86::BI__builtin_ia32_vcvttsd2usi64:
3230   case X86::BI__builtin_ia32_vcvttss2si32:
3231   case X86::BI__builtin_ia32_vcvttss2si64:
3232   case X86::BI__builtin_ia32_vcvttss2usi32:
3233   case X86::BI__builtin_ia32_vcvttss2usi64:
3234     ArgNum = 1;
3235     break;
3236   case X86::BI__builtin_ia32_maxpd512:
3237   case X86::BI__builtin_ia32_maxps512:
3238   case X86::BI__builtin_ia32_minpd512:
3239   case X86::BI__builtin_ia32_minps512:
3240     ArgNum = 2;
3241     break;
3242   case X86::BI__builtin_ia32_cvtps2pd512_mask:
3243   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3244   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3245   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3246   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3247   case X86::BI__builtin_ia32_cvttps2dq512_mask:
3248   case X86::BI__builtin_ia32_cvttps2qq512_mask:
3249   case X86::BI__builtin_ia32_cvttps2udq512_mask:
3250   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3251   case X86::BI__builtin_ia32_exp2pd_mask:
3252   case X86::BI__builtin_ia32_exp2ps_mask:
3253   case X86::BI__builtin_ia32_getexppd512_mask:
3254   case X86::BI__builtin_ia32_getexpps512_mask:
3255   case X86::BI__builtin_ia32_rcp28pd_mask:
3256   case X86::BI__builtin_ia32_rcp28ps_mask:
3257   case X86::BI__builtin_ia32_rsqrt28pd_mask:
3258   case X86::BI__builtin_ia32_rsqrt28ps_mask:
3259   case X86::BI__builtin_ia32_vcomisd:
3260   case X86::BI__builtin_ia32_vcomiss:
3261   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3262     ArgNum = 3;
3263     break;
3264   case X86::BI__builtin_ia32_cmppd512_mask:
3265   case X86::BI__builtin_ia32_cmpps512_mask:
3266   case X86::BI__builtin_ia32_cmpsd_mask:
3267   case X86::BI__builtin_ia32_cmpss_mask:
3268   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3269   case X86::BI__builtin_ia32_getexpsd128_round_mask:
3270   case X86::BI__builtin_ia32_getexpss128_round_mask:
3271   case X86::BI__builtin_ia32_getmantpd512_mask:
3272   case X86::BI__builtin_ia32_getmantps512_mask:
3273   case X86::BI__builtin_ia32_maxsd_round_mask:
3274   case X86::BI__builtin_ia32_maxss_round_mask:
3275   case X86::BI__builtin_ia32_minsd_round_mask:
3276   case X86::BI__builtin_ia32_minss_round_mask:
3277   case X86::BI__builtin_ia32_rcp28sd_round_mask:
3278   case X86::BI__builtin_ia32_rcp28ss_round_mask:
3279   case X86::BI__builtin_ia32_reducepd512_mask:
3280   case X86::BI__builtin_ia32_reduceps512_mask:
3281   case X86::BI__builtin_ia32_rndscalepd_mask:
3282   case X86::BI__builtin_ia32_rndscaleps_mask:
3283   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3284   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3285     ArgNum = 4;
3286     break;
3287   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3288   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3289   case X86::BI__builtin_ia32_fixupimmps512_mask:
3290   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3291   case X86::BI__builtin_ia32_fixupimmsd_mask:
3292   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3293   case X86::BI__builtin_ia32_fixupimmss_mask:
3294   case X86::BI__builtin_ia32_fixupimmss_maskz:
3295   case X86::BI__builtin_ia32_getmantsd_round_mask:
3296   case X86::BI__builtin_ia32_getmantss_round_mask:
3297   case X86::BI__builtin_ia32_rangepd512_mask:
3298   case X86::BI__builtin_ia32_rangeps512_mask:
3299   case X86::BI__builtin_ia32_rangesd128_round_mask:
3300   case X86::BI__builtin_ia32_rangess128_round_mask:
3301   case X86::BI__builtin_ia32_reducesd_mask:
3302   case X86::BI__builtin_ia32_reducess_mask:
3303   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3304   case X86::BI__builtin_ia32_rndscaless_round_mask:
3305     ArgNum = 5;
3306     break;
3307   case X86::BI__builtin_ia32_vcvtsd2si64:
3308   case X86::BI__builtin_ia32_vcvtsd2si32:
3309   case X86::BI__builtin_ia32_vcvtsd2usi32:
3310   case X86::BI__builtin_ia32_vcvtsd2usi64:
3311   case X86::BI__builtin_ia32_vcvtss2si32:
3312   case X86::BI__builtin_ia32_vcvtss2si64:
3313   case X86::BI__builtin_ia32_vcvtss2usi32:
3314   case X86::BI__builtin_ia32_vcvtss2usi64:
3315   case X86::BI__builtin_ia32_sqrtpd512:
3316   case X86::BI__builtin_ia32_sqrtps512:
3317     ArgNum = 1;
3318     HasRC = true;
3319     break;
3320   case X86::BI__builtin_ia32_addpd512:
3321   case X86::BI__builtin_ia32_addps512:
3322   case X86::BI__builtin_ia32_divpd512:
3323   case X86::BI__builtin_ia32_divps512:
3324   case X86::BI__builtin_ia32_mulpd512:
3325   case X86::BI__builtin_ia32_mulps512:
3326   case X86::BI__builtin_ia32_subpd512:
3327   case X86::BI__builtin_ia32_subps512:
3328   case X86::BI__builtin_ia32_cvtsi2sd64:
3329   case X86::BI__builtin_ia32_cvtsi2ss32:
3330   case X86::BI__builtin_ia32_cvtsi2ss64:
3331   case X86::BI__builtin_ia32_cvtusi2sd64:
3332   case X86::BI__builtin_ia32_cvtusi2ss32:
3333   case X86::BI__builtin_ia32_cvtusi2ss64:
3334     ArgNum = 2;
3335     HasRC = true;
3336     break;
3337   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3338   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3339   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
3340   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
3341   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3342   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
3343   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3344   case X86::BI__builtin_ia32_cvtps2dq512_mask:
3345   case X86::BI__builtin_ia32_cvtps2qq512_mask:
3346   case X86::BI__builtin_ia32_cvtps2udq512_mask:
3347   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3348   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3349   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3350   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3351   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3352     ArgNum = 3;
3353     HasRC = true;
3354     break;
3355   case X86::BI__builtin_ia32_addss_round_mask:
3356   case X86::BI__builtin_ia32_addsd_round_mask:
3357   case X86::BI__builtin_ia32_divss_round_mask:
3358   case X86::BI__builtin_ia32_divsd_round_mask:
3359   case X86::BI__builtin_ia32_mulss_round_mask:
3360   case X86::BI__builtin_ia32_mulsd_round_mask:
3361   case X86::BI__builtin_ia32_subss_round_mask:
3362   case X86::BI__builtin_ia32_subsd_round_mask:
3363   case X86::BI__builtin_ia32_scalefpd512_mask:
3364   case X86::BI__builtin_ia32_scalefps512_mask:
3365   case X86::BI__builtin_ia32_scalefsd_round_mask:
3366   case X86::BI__builtin_ia32_scalefss_round_mask:
3367   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3368   case X86::BI__builtin_ia32_sqrtsd_round_mask:
3369   case X86::BI__builtin_ia32_sqrtss_round_mask:
3370   case X86::BI__builtin_ia32_vfmaddsd3_mask:
3371   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3372   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
3373   case X86::BI__builtin_ia32_vfmaddss3_mask:
3374   case X86::BI__builtin_ia32_vfmaddss3_maskz:
3375   case X86::BI__builtin_ia32_vfmaddss3_mask3:
3376   case X86::BI__builtin_ia32_vfmaddpd512_mask:
3377   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
3378   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
3379   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
3380   case X86::BI__builtin_ia32_vfmaddps512_mask:
3381   case X86::BI__builtin_ia32_vfmaddps512_maskz:
3382   case X86::BI__builtin_ia32_vfmaddps512_mask3:
3383   case X86::BI__builtin_ia32_vfmsubps512_mask3:
3384   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
3385   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
3386   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
3387   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
3388   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
3389   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
3390   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
3391   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
3392     ArgNum = 4;
3393     HasRC = true;
3394     break;
3395   }
3396 
3397   llvm::APSInt Result;
3398 
3399   // We can't check the value of a dependent argument.
3400   Expr *Arg = TheCall->getArg(ArgNum);
3401   if (Arg->isTypeDependent() || Arg->isValueDependent())
3402     return false;
3403 
3404   // Check constant-ness first.
3405   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3406     return true;
3407 
3408   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
3409   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
3410   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
3411   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
3412   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
3413       Result == 8/*ROUND_NO_EXC*/ ||
3414       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
3415       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
3416     return false;
3417 
3418   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
3419          << Arg->getSourceRange();
3420 }
3421 
3422 // Check if the gather/scatter scale is legal.
3423 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
3424                                              CallExpr *TheCall) {
3425   unsigned ArgNum = 0;
3426   switch (BuiltinID) {
3427   default:
3428     return false;
3429   case X86::BI__builtin_ia32_gatherpfdpd:
3430   case X86::BI__builtin_ia32_gatherpfdps:
3431   case X86::BI__builtin_ia32_gatherpfqpd:
3432   case X86::BI__builtin_ia32_gatherpfqps:
3433   case X86::BI__builtin_ia32_scatterpfdpd:
3434   case X86::BI__builtin_ia32_scatterpfdps:
3435   case X86::BI__builtin_ia32_scatterpfqpd:
3436   case X86::BI__builtin_ia32_scatterpfqps:
3437     ArgNum = 3;
3438     break;
3439   case X86::BI__builtin_ia32_gatherd_pd:
3440   case X86::BI__builtin_ia32_gatherd_pd256:
3441   case X86::BI__builtin_ia32_gatherq_pd:
3442   case X86::BI__builtin_ia32_gatherq_pd256:
3443   case X86::BI__builtin_ia32_gatherd_ps:
3444   case X86::BI__builtin_ia32_gatherd_ps256:
3445   case X86::BI__builtin_ia32_gatherq_ps:
3446   case X86::BI__builtin_ia32_gatherq_ps256:
3447   case X86::BI__builtin_ia32_gatherd_q:
3448   case X86::BI__builtin_ia32_gatherd_q256:
3449   case X86::BI__builtin_ia32_gatherq_q:
3450   case X86::BI__builtin_ia32_gatherq_q256:
3451   case X86::BI__builtin_ia32_gatherd_d:
3452   case X86::BI__builtin_ia32_gatherd_d256:
3453   case X86::BI__builtin_ia32_gatherq_d:
3454   case X86::BI__builtin_ia32_gatherq_d256:
3455   case X86::BI__builtin_ia32_gather3div2df:
3456   case X86::BI__builtin_ia32_gather3div2di:
3457   case X86::BI__builtin_ia32_gather3div4df:
3458   case X86::BI__builtin_ia32_gather3div4di:
3459   case X86::BI__builtin_ia32_gather3div4sf:
3460   case X86::BI__builtin_ia32_gather3div4si:
3461   case X86::BI__builtin_ia32_gather3div8sf:
3462   case X86::BI__builtin_ia32_gather3div8si:
3463   case X86::BI__builtin_ia32_gather3siv2df:
3464   case X86::BI__builtin_ia32_gather3siv2di:
3465   case X86::BI__builtin_ia32_gather3siv4df:
3466   case X86::BI__builtin_ia32_gather3siv4di:
3467   case X86::BI__builtin_ia32_gather3siv4sf:
3468   case X86::BI__builtin_ia32_gather3siv4si:
3469   case X86::BI__builtin_ia32_gather3siv8sf:
3470   case X86::BI__builtin_ia32_gather3siv8si:
3471   case X86::BI__builtin_ia32_gathersiv8df:
3472   case X86::BI__builtin_ia32_gathersiv16sf:
3473   case X86::BI__builtin_ia32_gatherdiv8df:
3474   case X86::BI__builtin_ia32_gatherdiv16sf:
3475   case X86::BI__builtin_ia32_gathersiv8di:
3476   case X86::BI__builtin_ia32_gathersiv16si:
3477   case X86::BI__builtin_ia32_gatherdiv8di:
3478   case X86::BI__builtin_ia32_gatherdiv16si:
3479   case X86::BI__builtin_ia32_scatterdiv2df:
3480   case X86::BI__builtin_ia32_scatterdiv2di:
3481   case X86::BI__builtin_ia32_scatterdiv4df:
3482   case X86::BI__builtin_ia32_scatterdiv4di:
3483   case X86::BI__builtin_ia32_scatterdiv4sf:
3484   case X86::BI__builtin_ia32_scatterdiv4si:
3485   case X86::BI__builtin_ia32_scatterdiv8sf:
3486   case X86::BI__builtin_ia32_scatterdiv8si:
3487   case X86::BI__builtin_ia32_scattersiv2df:
3488   case X86::BI__builtin_ia32_scattersiv2di:
3489   case X86::BI__builtin_ia32_scattersiv4df:
3490   case X86::BI__builtin_ia32_scattersiv4di:
3491   case X86::BI__builtin_ia32_scattersiv4sf:
3492   case X86::BI__builtin_ia32_scattersiv4si:
3493   case X86::BI__builtin_ia32_scattersiv8sf:
3494   case X86::BI__builtin_ia32_scattersiv8si:
3495   case X86::BI__builtin_ia32_scattersiv8df:
3496   case X86::BI__builtin_ia32_scattersiv16sf:
3497   case X86::BI__builtin_ia32_scatterdiv8df:
3498   case X86::BI__builtin_ia32_scatterdiv16sf:
3499   case X86::BI__builtin_ia32_scattersiv8di:
3500   case X86::BI__builtin_ia32_scattersiv16si:
3501   case X86::BI__builtin_ia32_scatterdiv8di:
3502   case X86::BI__builtin_ia32_scatterdiv16si:
3503     ArgNum = 4;
3504     break;
3505   }
3506 
3507   llvm::APSInt Result;
3508 
3509   // We can't check the value of a dependent argument.
3510   Expr *Arg = TheCall->getArg(ArgNum);
3511   if (Arg->isTypeDependent() || Arg->isValueDependent())
3512     return false;
3513 
3514   // Check constant-ness first.
3515   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3516     return true;
3517 
3518   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
3519     return false;
3520 
3521   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
3522          << Arg->getSourceRange();
3523 }
3524 
3525 static bool isX86_32Builtin(unsigned BuiltinID) {
3526   // These builtins only work on x86-32 targets.
3527   switch (BuiltinID) {
3528   case X86::BI__builtin_ia32_readeflags_u32:
3529   case X86::BI__builtin_ia32_writeeflags_u32:
3530     return true;
3531   }
3532 
3533   return false;
3534 }
3535 
3536 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3537                                        CallExpr *TheCall) {
3538   if (BuiltinID == X86::BI__builtin_cpu_supports)
3539     return SemaBuiltinCpuSupports(*this, TI, TheCall);
3540 
3541   if (BuiltinID == X86::BI__builtin_cpu_is)
3542     return SemaBuiltinCpuIs(*this, TI, TheCall);
3543 
3544   // Check for 32-bit only builtins on a 64-bit target.
3545   const llvm::Triple &TT = TI.getTriple();
3546   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
3547     return Diag(TheCall->getCallee()->getBeginLoc(),
3548                 diag::err_32_bit_builtin_64_bit_tgt);
3549 
3550   // If the intrinsic has rounding or SAE make sure its valid.
3551   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
3552     return true;
3553 
3554   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
3555   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
3556     return true;
3557 
3558   // For intrinsics which take an immediate value as part of the instruction,
3559   // range check them here.
3560   int i = 0, l = 0, u = 0;
3561   switch (BuiltinID) {
3562   default:
3563     return false;
3564   case X86::BI__builtin_ia32_vec_ext_v2si:
3565   case X86::BI__builtin_ia32_vec_ext_v2di:
3566   case X86::BI__builtin_ia32_vextractf128_pd256:
3567   case X86::BI__builtin_ia32_vextractf128_ps256:
3568   case X86::BI__builtin_ia32_vextractf128_si256:
3569   case X86::BI__builtin_ia32_extract128i256:
3570   case X86::BI__builtin_ia32_extractf64x4_mask:
3571   case X86::BI__builtin_ia32_extracti64x4_mask:
3572   case X86::BI__builtin_ia32_extractf32x8_mask:
3573   case X86::BI__builtin_ia32_extracti32x8_mask:
3574   case X86::BI__builtin_ia32_extractf64x2_256_mask:
3575   case X86::BI__builtin_ia32_extracti64x2_256_mask:
3576   case X86::BI__builtin_ia32_extractf32x4_256_mask:
3577   case X86::BI__builtin_ia32_extracti32x4_256_mask:
3578     i = 1; l = 0; u = 1;
3579     break;
3580   case X86::BI__builtin_ia32_vec_set_v2di:
3581   case X86::BI__builtin_ia32_vinsertf128_pd256:
3582   case X86::BI__builtin_ia32_vinsertf128_ps256:
3583   case X86::BI__builtin_ia32_vinsertf128_si256:
3584   case X86::BI__builtin_ia32_insert128i256:
3585   case X86::BI__builtin_ia32_insertf32x8:
3586   case X86::BI__builtin_ia32_inserti32x8:
3587   case X86::BI__builtin_ia32_insertf64x4:
3588   case X86::BI__builtin_ia32_inserti64x4:
3589   case X86::BI__builtin_ia32_insertf64x2_256:
3590   case X86::BI__builtin_ia32_inserti64x2_256:
3591   case X86::BI__builtin_ia32_insertf32x4_256:
3592   case X86::BI__builtin_ia32_inserti32x4_256:
3593     i = 2; l = 0; u = 1;
3594     break;
3595   case X86::BI__builtin_ia32_vpermilpd:
3596   case X86::BI__builtin_ia32_vec_ext_v4hi:
3597   case X86::BI__builtin_ia32_vec_ext_v4si:
3598   case X86::BI__builtin_ia32_vec_ext_v4sf:
3599   case X86::BI__builtin_ia32_vec_ext_v4di:
3600   case X86::BI__builtin_ia32_extractf32x4_mask:
3601   case X86::BI__builtin_ia32_extracti32x4_mask:
3602   case X86::BI__builtin_ia32_extractf64x2_512_mask:
3603   case X86::BI__builtin_ia32_extracti64x2_512_mask:
3604     i = 1; l = 0; u = 3;
3605     break;
3606   case X86::BI_mm_prefetch:
3607   case X86::BI__builtin_ia32_vec_ext_v8hi:
3608   case X86::BI__builtin_ia32_vec_ext_v8si:
3609     i = 1; l = 0; u = 7;
3610     break;
3611   case X86::BI__builtin_ia32_sha1rnds4:
3612   case X86::BI__builtin_ia32_blendpd:
3613   case X86::BI__builtin_ia32_shufpd:
3614   case X86::BI__builtin_ia32_vec_set_v4hi:
3615   case X86::BI__builtin_ia32_vec_set_v4si:
3616   case X86::BI__builtin_ia32_vec_set_v4di:
3617   case X86::BI__builtin_ia32_shuf_f32x4_256:
3618   case X86::BI__builtin_ia32_shuf_f64x2_256:
3619   case X86::BI__builtin_ia32_shuf_i32x4_256:
3620   case X86::BI__builtin_ia32_shuf_i64x2_256:
3621   case X86::BI__builtin_ia32_insertf64x2_512:
3622   case X86::BI__builtin_ia32_inserti64x2_512:
3623   case X86::BI__builtin_ia32_insertf32x4:
3624   case X86::BI__builtin_ia32_inserti32x4:
3625     i = 2; l = 0; u = 3;
3626     break;
3627   case X86::BI__builtin_ia32_vpermil2pd:
3628   case X86::BI__builtin_ia32_vpermil2pd256:
3629   case X86::BI__builtin_ia32_vpermil2ps:
3630   case X86::BI__builtin_ia32_vpermil2ps256:
3631     i = 3; l = 0; u = 3;
3632     break;
3633   case X86::BI__builtin_ia32_cmpb128_mask:
3634   case X86::BI__builtin_ia32_cmpw128_mask:
3635   case X86::BI__builtin_ia32_cmpd128_mask:
3636   case X86::BI__builtin_ia32_cmpq128_mask:
3637   case X86::BI__builtin_ia32_cmpb256_mask:
3638   case X86::BI__builtin_ia32_cmpw256_mask:
3639   case X86::BI__builtin_ia32_cmpd256_mask:
3640   case X86::BI__builtin_ia32_cmpq256_mask:
3641   case X86::BI__builtin_ia32_cmpb512_mask:
3642   case X86::BI__builtin_ia32_cmpw512_mask:
3643   case X86::BI__builtin_ia32_cmpd512_mask:
3644   case X86::BI__builtin_ia32_cmpq512_mask:
3645   case X86::BI__builtin_ia32_ucmpb128_mask:
3646   case X86::BI__builtin_ia32_ucmpw128_mask:
3647   case X86::BI__builtin_ia32_ucmpd128_mask:
3648   case X86::BI__builtin_ia32_ucmpq128_mask:
3649   case X86::BI__builtin_ia32_ucmpb256_mask:
3650   case X86::BI__builtin_ia32_ucmpw256_mask:
3651   case X86::BI__builtin_ia32_ucmpd256_mask:
3652   case X86::BI__builtin_ia32_ucmpq256_mask:
3653   case X86::BI__builtin_ia32_ucmpb512_mask:
3654   case X86::BI__builtin_ia32_ucmpw512_mask:
3655   case X86::BI__builtin_ia32_ucmpd512_mask:
3656   case X86::BI__builtin_ia32_ucmpq512_mask:
3657   case X86::BI__builtin_ia32_vpcomub:
3658   case X86::BI__builtin_ia32_vpcomuw:
3659   case X86::BI__builtin_ia32_vpcomud:
3660   case X86::BI__builtin_ia32_vpcomuq:
3661   case X86::BI__builtin_ia32_vpcomb:
3662   case X86::BI__builtin_ia32_vpcomw:
3663   case X86::BI__builtin_ia32_vpcomd:
3664   case X86::BI__builtin_ia32_vpcomq:
3665   case X86::BI__builtin_ia32_vec_set_v8hi:
3666   case X86::BI__builtin_ia32_vec_set_v8si:
3667     i = 2; l = 0; u = 7;
3668     break;
3669   case X86::BI__builtin_ia32_vpermilpd256:
3670   case X86::BI__builtin_ia32_roundps:
3671   case X86::BI__builtin_ia32_roundpd:
3672   case X86::BI__builtin_ia32_roundps256:
3673   case X86::BI__builtin_ia32_roundpd256:
3674   case X86::BI__builtin_ia32_getmantpd128_mask:
3675   case X86::BI__builtin_ia32_getmantpd256_mask:
3676   case X86::BI__builtin_ia32_getmantps128_mask:
3677   case X86::BI__builtin_ia32_getmantps256_mask:
3678   case X86::BI__builtin_ia32_getmantpd512_mask:
3679   case X86::BI__builtin_ia32_getmantps512_mask:
3680   case X86::BI__builtin_ia32_vec_ext_v16qi:
3681   case X86::BI__builtin_ia32_vec_ext_v16hi:
3682     i = 1; l = 0; u = 15;
3683     break;
3684   case X86::BI__builtin_ia32_pblendd128:
3685   case X86::BI__builtin_ia32_blendps:
3686   case X86::BI__builtin_ia32_blendpd256:
3687   case X86::BI__builtin_ia32_shufpd256:
3688   case X86::BI__builtin_ia32_roundss:
3689   case X86::BI__builtin_ia32_roundsd:
3690   case X86::BI__builtin_ia32_rangepd128_mask:
3691   case X86::BI__builtin_ia32_rangepd256_mask:
3692   case X86::BI__builtin_ia32_rangepd512_mask:
3693   case X86::BI__builtin_ia32_rangeps128_mask:
3694   case X86::BI__builtin_ia32_rangeps256_mask:
3695   case X86::BI__builtin_ia32_rangeps512_mask:
3696   case X86::BI__builtin_ia32_getmantsd_round_mask:
3697   case X86::BI__builtin_ia32_getmantss_round_mask:
3698   case X86::BI__builtin_ia32_vec_set_v16qi:
3699   case X86::BI__builtin_ia32_vec_set_v16hi:
3700     i = 2; l = 0; u = 15;
3701     break;
3702   case X86::BI__builtin_ia32_vec_ext_v32qi:
3703     i = 1; l = 0; u = 31;
3704     break;
3705   case X86::BI__builtin_ia32_cmpps:
3706   case X86::BI__builtin_ia32_cmpss:
3707   case X86::BI__builtin_ia32_cmppd:
3708   case X86::BI__builtin_ia32_cmpsd:
3709   case X86::BI__builtin_ia32_cmpps256:
3710   case X86::BI__builtin_ia32_cmppd256:
3711   case X86::BI__builtin_ia32_cmpps128_mask:
3712   case X86::BI__builtin_ia32_cmppd128_mask:
3713   case X86::BI__builtin_ia32_cmpps256_mask:
3714   case X86::BI__builtin_ia32_cmppd256_mask:
3715   case X86::BI__builtin_ia32_cmpps512_mask:
3716   case X86::BI__builtin_ia32_cmppd512_mask:
3717   case X86::BI__builtin_ia32_cmpsd_mask:
3718   case X86::BI__builtin_ia32_cmpss_mask:
3719   case X86::BI__builtin_ia32_vec_set_v32qi:
3720     i = 2; l = 0; u = 31;
3721     break;
3722   case X86::BI__builtin_ia32_permdf256:
3723   case X86::BI__builtin_ia32_permdi256:
3724   case X86::BI__builtin_ia32_permdf512:
3725   case X86::BI__builtin_ia32_permdi512:
3726   case X86::BI__builtin_ia32_vpermilps:
3727   case X86::BI__builtin_ia32_vpermilps256:
3728   case X86::BI__builtin_ia32_vpermilpd512:
3729   case X86::BI__builtin_ia32_vpermilps512:
3730   case X86::BI__builtin_ia32_pshufd:
3731   case X86::BI__builtin_ia32_pshufd256:
3732   case X86::BI__builtin_ia32_pshufd512:
3733   case X86::BI__builtin_ia32_pshufhw:
3734   case X86::BI__builtin_ia32_pshufhw256:
3735   case X86::BI__builtin_ia32_pshufhw512:
3736   case X86::BI__builtin_ia32_pshuflw:
3737   case X86::BI__builtin_ia32_pshuflw256:
3738   case X86::BI__builtin_ia32_pshuflw512:
3739   case X86::BI__builtin_ia32_vcvtps2ph:
3740   case X86::BI__builtin_ia32_vcvtps2ph_mask:
3741   case X86::BI__builtin_ia32_vcvtps2ph256:
3742   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
3743   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
3744   case X86::BI__builtin_ia32_rndscaleps_128_mask:
3745   case X86::BI__builtin_ia32_rndscalepd_128_mask:
3746   case X86::BI__builtin_ia32_rndscaleps_256_mask:
3747   case X86::BI__builtin_ia32_rndscalepd_256_mask:
3748   case X86::BI__builtin_ia32_rndscaleps_mask:
3749   case X86::BI__builtin_ia32_rndscalepd_mask:
3750   case X86::BI__builtin_ia32_reducepd128_mask:
3751   case X86::BI__builtin_ia32_reducepd256_mask:
3752   case X86::BI__builtin_ia32_reducepd512_mask:
3753   case X86::BI__builtin_ia32_reduceps128_mask:
3754   case X86::BI__builtin_ia32_reduceps256_mask:
3755   case X86::BI__builtin_ia32_reduceps512_mask:
3756   case X86::BI__builtin_ia32_prold512:
3757   case X86::BI__builtin_ia32_prolq512:
3758   case X86::BI__builtin_ia32_prold128:
3759   case X86::BI__builtin_ia32_prold256:
3760   case X86::BI__builtin_ia32_prolq128:
3761   case X86::BI__builtin_ia32_prolq256:
3762   case X86::BI__builtin_ia32_prord512:
3763   case X86::BI__builtin_ia32_prorq512:
3764   case X86::BI__builtin_ia32_prord128:
3765   case X86::BI__builtin_ia32_prord256:
3766   case X86::BI__builtin_ia32_prorq128:
3767   case X86::BI__builtin_ia32_prorq256:
3768   case X86::BI__builtin_ia32_fpclasspd128_mask:
3769   case X86::BI__builtin_ia32_fpclasspd256_mask:
3770   case X86::BI__builtin_ia32_fpclassps128_mask:
3771   case X86::BI__builtin_ia32_fpclassps256_mask:
3772   case X86::BI__builtin_ia32_fpclassps512_mask:
3773   case X86::BI__builtin_ia32_fpclasspd512_mask:
3774   case X86::BI__builtin_ia32_fpclasssd_mask:
3775   case X86::BI__builtin_ia32_fpclassss_mask:
3776   case X86::BI__builtin_ia32_pslldqi128_byteshift:
3777   case X86::BI__builtin_ia32_pslldqi256_byteshift:
3778   case X86::BI__builtin_ia32_pslldqi512_byteshift:
3779   case X86::BI__builtin_ia32_psrldqi128_byteshift:
3780   case X86::BI__builtin_ia32_psrldqi256_byteshift:
3781   case X86::BI__builtin_ia32_psrldqi512_byteshift:
3782   case X86::BI__builtin_ia32_kshiftliqi:
3783   case X86::BI__builtin_ia32_kshiftlihi:
3784   case X86::BI__builtin_ia32_kshiftlisi:
3785   case X86::BI__builtin_ia32_kshiftlidi:
3786   case X86::BI__builtin_ia32_kshiftriqi:
3787   case X86::BI__builtin_ia32_kshiftrihi:
3788   case X86::BI__builtin_ia32_kshiftrisi:
3789   case X86::BI__builtin_ia32_kshiftridi:
3790     i = 1; l = 0; u = 255;
3791     break;
3792   case X86::BI__builtin_ia32_vperm2f128_pd256:
3793   case X86::BI__builtin_ia32_vperm2f128_ps256:
3794   case X86::BI__builtin_ia32_vperm2f128_si256:
3795   case X86::BI__builtin_ia32_permti256:
3796   case X86::BI__builtin_ia32_pblendw128:
3797   case X86::BI__builtin_ia32_pblendw256:
3798   case X86::BI__builtin_ia32_blendps256:
3799   case X86::BI__builtin_ia32_pblendd256:
3800   case X86::BI__builtin_ia32_palignr128:
3801   case X86::BI__builtin_ia32_palignr256:
3802   case X86::BI__builtin_ia32_palignr512:
3803   case X86::BI__builtin_ia32_alignq512:
3804   case X86::BI__builtin_ia32_alignd512:
3805   case X86::BI__builtin_ia32_alignd128:
3806   case X86::BI__builtin_ia32_alignd256:
3807   case X86::BI__builtin_ia32_alignq128:
3808   case X86::BI__builtin_ia32_alignq256:
3809   case X86::BI__builtin_ia32_vcomisd:
3810   case X86::BI__builtin_ia32_vcomiss:
3811   case X86::BI__builtin_ia32_shuf_f32x4:
3812   case X86::BI__builtin_ia32_shuf_f64x2:
3813   case X86::BI__builtin_ia32_shuf_i32x4:
3814   case X86::BI__builtin_ia32_shuf_i64x2:
3815   case X86::BI__builtin_ia32_shufpd512:
3816   case X86::BI__builtin_ia32_shufps:
3817   case X86::BI__builtin_ia32_shufps256:
3818   case X86::BI__builtin_ia32_shufps512:
3819   case X86::BI__builtin_ia32_dbpsadbw128:
3820   case X86::BI__builtin_ia32_dbpsadbw256:
3821   case X86::BI__builtin_ia32_dbpsadbw512:
3822   case X86::BI__builtin_ia32_vpshldd128:
3823   case X86::BI__builtin_ia32_vpshldd256:
3824   case X86::BI__builtin_ia32_vpshldd512:
3825   case X86::BI__builtin_ia32_vpshldq128:
3826   case X86::BI__builtin_ia32_vpshldq256:
3827   case X86::BI__builtin_ia32_vpshldq512:
3828   case X86::BI__builtin_ia32_vpshldw128:
3829   case X86::BI__builtin_ia32_vpshldw256:
3830   case X86::BI__builtin_ia32_vpshldw512:
3831   case X86::BI__builtin_ia32_vpshrdd128:
3832   case X86::BI__builtin_ia32_vpshrdd256:
3833   case X86::BI__builtin_ia32_vpshrdd512:
3834   case X86::BI__builtin_ia32_vpshrdq128:
3835   case X86::BI__builtin_ia32_vpshrdq256:
3836   case X86::BI__builtin_ia32_vpshrdq512:
3837   case X86::BI__builtin_ia32_vpshrdw128:
3838   case X86::BI__builtin_ia32_vpshrdw256:
3839   case X86::BI__builtin_ia32_vpshrdw512:
3840     i = 2; l = 0; u = 255;
3841     break;
3842   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3843   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3844   case X86::BI__builtin_ia32_fixupimmps512_mask:
3845   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3846   case X86::BI__builtin_ia32_fixupimmsd_mask:
3847   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3848   case X86::BI__builtin_ia32_fixupimmss_mask:
3849   case X86::BI__builtin_ia32_fixupimmss_maskz:
3850   case X86::BI__builtin_ia32_fixupimmpd128_mask:
3851   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
3852   case X86::BI__builtin_ia32_fixupimmpd256_mask:
3853   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
3854   case X86::BI__builtin_ia32_fixupimmps128_mask:
3855   case X86::BI__builtin_ia32_fixupimmps128_maskz:
3856   case X86::BI__builtin_ia32_fixupimmps256_mask:
3857   case X86::BI__builtin_ia32_fixupimmps256_maskz:
3858   case X86::BI__builtin_ia32_pternlogd512_mask:
3859   case X86::BI__builtin_ia32_pternlogd512_maskz:
3860   case X86::BI__builtin_ia32_pternlogq512_mask:
3861   case X86::BI__builtin_ia32_pternlogq512_maskz:
3862   case X86::BI__builtin_ia32_pternlogd128_mask:
3863   case X86::BI__builtin_ia32_pternlogd128_maskz:
3864   case X86::BI__builtin_ia32_pternlogd256_mask:
3865   case X86::BI__builtin_ia32_pternlogd256_maskz:
3866   case X86::BI__builtin_ia32_pternlogq128_mask:
3867   case X86::BI__builtin_ia32_pternlogq128_maskz:
3868   case X86::BI__builtin_ia32_pternlogq256_mask:
3869   case X86::BI__builtin_ia32_pternlogq256_maskz:
3870     i = 3; l = 0; u = 255;
3871     break;
3872   case X86::BI__builtin_ia32_gatherpfdpd:
3873   case X86::BI__builtin_ia32_gatherpfdps:
3874   case X86::BI__builtin_ia32_gatherpfqpd:
3875   case X86::BI__builtin_ia32_gatherpfqps:
3876   case X86::BI__builtin_ia32_scatterpfdpd:
3877   case X86::BI__builtin_ia32_scatterpfdps:
3878   case X86::BI__builtin_ia32_scatterpfqpd:
3879   case X86::BI__builtin_ia32_scatterpfqps:
3880     i = 4; l = 2; u = 3;
3881     break;
3882   case X86::BI__builtin_ia32_reducesd_mask:
3883   case X86::BI__builtin_ia32_reducess_mask:
3884   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3885   case X86::BI__builtin_ia32_rndscaless_round_mask:
3886     i = 4; l = 0; u = 255;
3887     break;
3888   }
3889 
3890   // Note that we don't force a hard error on the range check here, allowing
3891   // template-generated or macro-generated dead code to potentially have out-of-
3892   // range values. These need to code generate, but don't need to necessarily
3893   // make any sense. We use a warning that defaults to an error.
3894   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
3895 }
3896 
3897 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
3898 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
3899 /// Returns true when the format fits the function and the FormatStringInfo has
3900 /// been populated.
3901 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
3902                                FormatStringInfo *FSI) {
3903   FSI->HasVAListArg = Format->getFirstArg() == 0;
3904   FSI->FormatIdx = Format->getFormatIdx() - 1;
3905   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
3906 
3907   // The way the format attribute works in GCC, the implicit this argument
3908   // of member functions is counted. However, it doesn't appear in our own
3909   // lists, so decrement format_idx in that case.
3910   if (IsCXXMember) {
3911     if(FSI->FormatIdx == 0)
3912       return false;
3913     --FSI->FormatIdx;
3914     if (FSI->FirstDataArg != 0)
3915       --FSI->FirstDataArg;
3916   }
3917   return true;
3918 }
3919 
3920 /// Checks if a the given expression evaluates to null.
3921 ///
3922 /// Returns true if the value evaluates to null.
3923 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
3924   // If the expression has non-null type, it doesn't evaluate to null.
3925   if (auto nullability
3926         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
3927     if (*nullability == NullabilityKind::NonNull)
3928       return false;
3929   }
3930 
3931   // As a special case, transparent unions initialized with zero are
3932   // considered null for the purposes of the nonnull attribute.
3933   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
3934     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
3935       if (const CompoundLiteralExpr *CLE =
3936           dyn_cast<CompoundLiteralExpr>(Expr))
3937         if (const InitListExpr *ILE =
3938             dyn_cast<InitListExpr>(CLE->getInitializer()))
3939           Expr = ILE->getInit(0);
3940   }
3941 
3942   bool Result;
3943   return (!Expr->isValueDependent() &&
3944           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
3945           !Result);
3946 }
3947 
3948 static void CheckNonNullArgument(Sema &S,
3949                                  const Expr *ArgExpr,
3950                                  SourceLocation CallSiteLoc) {
3951   if (CheckNonNullExpr(S, ArgExpr))
3952     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
3953                           S.PDiag(diag::warn_null_arg)
3954                               << ArgExpr->getSourceRange());
3955 }
3956 
3957 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
3958   FormatStringInfo FSI;
3959   if ((GetFormatStringType(Format) == FST_NSString) &&
3960       getFormatStringInfo(Format, false, &FSI)) {
3961     Idx = FSI.FormatIdx;
3962     return true;
3963   }
3964   return false;
3965 }
3966 
3967 /// Diagnose use of %s directive in an NSString which is being passed
3968 /// as formatting string to formatting method.
3969 static void
3970 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
3971                                         const NamedDecl *FDecl,
3972                                         Expr **Args,
3973                                         unsigned NumArgs) {
3974   unsigned Idx = 0;
3975   bool Format = false;
3976   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
3977   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
3978     Idx = 2;
3979     Format = true;
3980   }
3981   else
3982     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
3983       if (S.GetFormatNSStringIdx(I, Idx)) {
3984         Format = true;
3985         break;
3986       }
3987     }
3988   if (!Format || NumArgs <= Idx)
3989     return;
3990   const Expr *FormatExpr = Args[Idx];
3991   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
3992     FormatExpr = CSCE->getSubExpr();
3993   const StringLiteral *FormatString;
3994   if (const ObjCStringLiteral *OSL =
3995       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
3996     FormatString = OSL->getString();
3997   else
3998     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
3999   if (!FormatString)
4000     return;
4001   if (S.FormatStringHasSArg(FormatString)) {
4002     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4003       << "%s" << 1 << 1;
4004     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4005       << FDecl->getDeclName();
4006   }
4007 }
4008 
4009 /// Determine whether the given type has a non-null nullability annotation.
4010 static bool isNonNullType(ASTContext &ctx, QualType type) {
4011   if (auto nullability = type->getNullability(ctx))
4012     return *nullability == NullabilityKind::NonNull;
4013 
4014   return false;
4015 }
4016 
4017 static void CheckNonNullArguments(Sema &S,
4018                                   const NamedDecl *FDecl,
4019                                   const FunctionProtoType *Proto,
4020                                   ArrayRef<const Expr *> Args,
4021                                   SourceLocation CallSiteLoc) {
4022   assert((FDecl || Proto) && "Need a function declaration or prototype");
4023 
4024   // Already checked by by constant evaluator.
4025   if (S.isConstantEvaluated())
4026     return;
4027   // Check the attributes attached to the method/function itself.
4028   llvm::SmallBitVector NonNullArgs;
4029   if (FDecl) {
4030     // Handle the nonnull attribute on the function/method declaration itself.
4031     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4032       if (!NonNull->args_size()) {
4033         // Easy case: all pointer arguments are nonnull.
4034         for (const auto *Arg : Args)
4035           if (S.isValidPointerAttrType(Arg->getType()))
4036             CheckNonNullArgument(S, Arg, CallSiteLoc);
4037         return;
4038       }
4039 
4040       for (const ParamIdx &Idx : NonNull->args()) {
4041         unsigned IdxAST = Idx.getASTIndex();
4042         if (IdxAST >= Args.size())
4043           continue;
4044         if (NonNullArgs.empty())
4045           NonNullArgs.resize(Args.size());
4046         NonNullArgs.set(IdxAST);
4047       }
4048     }
4049   }
4050 
4051   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4052     // Handle the nonnull attribute on the parameters of the
4053     // function/method.
4054     ArrayRef<ParmVarDecl*> parms;
4055     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4056       parms = FD->parameters();
4057     else
4058       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4059 
4060     unsigned ParamIndex = 0;
4061     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4062          I != E; ++I, ++ParamIndex) {
4063       const ParmVarDecl *PVD = *I;
4064       if (PVD->hasAttr<NonNullAttr>() ||
4065           isNonNullType(S.Context, PVD->getType())) {
4066         if (NonNullArgs.empty())
4067           NonNullArgs.resize(Args.size());
4068 
4069         NonNullArgs.set(ParamIndex);
4070       }
4071     }
4072   } else {
4073     // If we have a non-function, non-method declaration but no
4074     // function prototype, try to dig out the function prototype.
4075     if (!Proto) {
4076       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4077         QualType type = VD->getType().getNonReferenceType();
4078         if (auto pointerType = type->getAs<PointerType>())
4079           type = pointerType->getPointeeType();
4080         else if (auto blockType = type->getAs<BlockPointerType>())
4081           type = blockType->getPointeeType();
4082         // FIXME: data member pointers?
4083 
4084         // Dig out the function prototype, if there is one.
4085         Proto = type->getAs<FunctionProtoType>();
4086       }
4087     }
4088 
4089     // Fill in non-null argument information from the nullability
4090     // information on the parameter types (if we have them).
4091     if (Proto) {
4092       unsigned Index = 0;
4093       for (auto paramType : Proto->getParamTypes()) {
4094         if (isNonNullType(S.Context, paramType)) {
4095           if (NonNullArgs.empty())
4096             NonNullArgs.resize(Args.size());
4097 
4098           NonNullArgs.set(Index);
4099         }
4100 
4101         ++Index;
4102       }
4103     }
4104   }
4105 
4106   // Check for non-null arguments.
4107   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4108        ArgIndex != ArgIndexEnd; ++ArgIndex) {
4109     if (NonNullArgs[ArgIndex])
4110       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4111   }
4112 }
4113 
4114 /// Handles the checks for format strings, non-POD arguments to vararg
4115 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4116 /// attributes.
4117 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4118                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
4119                      bool IsMemberFunction, SourceLocation Loc,
4120                      SourceRange Range, VariadicCallType CallType) {
4121   // FIXME: We should check as much as we can in the template definition.
4122   if (CurContext->isDependentContext())
4123     return;
4124 
4125   // Printf and scanf checking.
4126   llvm::SmallBitVector CheckedVarArgs;
4127   if (FDecl) {
4128     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4129       // Only create vector if there are format attributes.
4130       CheckedVarArgs.resize(Args.size());
4131 
4132       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4133                            CheckedVarArgs);
4134     }
4135   }
4136 
4137   // Refuse POD arguments that weren't caught by the format string
4138   // checks above.
4139   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4140   if (CallType != VariadicDoesNotApply &&
4141       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4142     unsigned NumParams = Proto ? Proto->getNumParams()
4143                        : FDecl && isa<FunctionDecl>(FDecl)
4144                            ? cast<FunctionDecl>(FDecl)->getNumParams()
4145                        : FDecl && isa<ObjCMethodDecl>(FDecl)
4146                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
4147                        : 0;
4148 
4149     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4150       // Args[ArgIdx] can be null in malformed code.
4151       if (const Expr *Arg = Args[ArgIdx]) {
4152         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4153           checkVariadicArgument(Arg, CallType);
4154       }
4155     }
4156   }
4157 
4158   if (FDecl || Proto) {
4159     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4160 
4161     // Type safety checking.
4162     if (FDecl) {
4163       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4164         CheckArgumentWithTypeTag(I, Args, Loc);
4165     }
4166   }
4167 
4168   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4169     auto *AA = FDecl->getAttr<AllocAlignAttr>();
4170     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4171     if (!Arg->isValueDependent()) {
4172       Expr::EvalResult Align;
4173       if (Arg->EvaluateAsInt(Align, Context)) {
4174         const llvm::APSInt &I = Align.Val.getInt();
4175         if (!I.isPowerOf2())
4176           Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
4177               << Arg->getSourceRange();
4178 
4179         if (I > Sema::MaximumAlignment)
4180           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
4181               << Arg->getSourceRange() << Sema::MaximumAlignment;
4182       }
4183     }
4184   }
4185 
4186   if (FD)
4187     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4188 }
4189 
4190 /// CheckConstructorCall - Check a constructor call for correctness and safety
4191 /// properties not enforced by the C type system.
4192 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
4193                                 ArrayRef<const Expr *> Args,
4194                                 const FunctionProtoType *Proto,
4195                                 SourceLocation Loc) {
4196   VariadicCallType CallType =
4197     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4198   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4199             Loc, SourceRange(), CallType);
4200 }
4201 
4202 /// CheckFunctionCall - Check a direct function call for various correctness
4203 /// and safety properties not strictly enforced by the C type system.
4204 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4205                              const FunctionProtoType *Proto) {
4206   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4207                               isa<CXXMethodDecl>(FDecl);
4208   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4209                           IsMemberOperatorCall;
4210   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4211                                                   TheCall->getCallee());
4212   Expr** Args = TheCall->getArgs();
4213   unsigned NumArgs = TheCall->getNumArgs();
4214 
4215   Expr *ImplicitThis = nullptr;
4216   if (IsMemberOperatorCall) {
4217     // If this is a call to a member operator, hide the first argument
4218     // from checkCall.
4219     // FIXME: Our choice of AST representation here is less than ideal.
4220     ImplicitThis = Args[0];
4221     ++Args;
4222     --NumArgs;
4223   } else if (IsMemberFunction)
4224     ImplicitThis =
4225         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4226 
4227   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
4228             IsMemberFunction, TheCall->getRParenLoc(),
4229             TheCall->getCallee()->getSourceRange(), CallType);
4230 
4231   IdentifierInfo *FnInfo = FDecl->getIdentifier();
4232   // None of the checks below are needed for functions that don't have
4233   // simple names (e.g., C++ conversion functions).
4234   if (!FnInfo)
4235     return false;
4236 
4237   CheckAbsoluteValueFunction(TheCall, FDecl);
4238   CheckMaxUnsignedZero(TheCall, FDecl);
4239 
4240   if (getLangOpts().ObjC)
4241     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
4242 
4243   unsigned CMId = FDecl->getMemoryFunctionKind();
4244   if (CMId == 0)
4245     return false;
4246 
4247   // Handle memory setting and copying functions.
4248   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
4249     CheckStrlcpycatArguments(TheCall, FnInfo);
4250   else if (CMId == Builtin::BIstrncat)
4251     CheckStrncatArguments(TheCall, FnInfo);
4252   else
4253     CheckMemaccessArguments(TheCall, CMId, FnInfo);
4254 
4255   return false;
4256 }
4257 
4258 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
4259                                ArrayRef<const Expr *> Args) {
4260   VariadicCallType CallType =
4261       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
4262 
4263   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
4264             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
4265             CallType);
4266 
4267   return false;
4268 }
4269 
4270 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4271                             const FunctionProtoType *Proto) {
4272   QualType Ty;
4273   if (const auto *V = dyn_cast<VarDecl>(NDecl))
4274     Ty = V->getType().getNonReferenceType();
4275   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4276     Ty = F->getType().getNonReferenceType();
4277   else
4278     return false;
4279 
4280   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4281       !Ty->isFunctionProtoType())
4282     return false;
4283 
4284   VariadicCallType CallType;
4285   if (!Proto || !Proto->isVariadic()) {
4286     CallType = VariadicDoesNotApply;
4287   } else if (Ty->isBlockPointerType()) {
4288     CallType = VariadicBlock;
4289   } else { // Ty->isFunctionPointerType()
4290     CallType = VariadicFunction;
4291   }
4292 
4293   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4294             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4295             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4296             TheCall->getCallee()->getSourceRange(), CallType);
4297 
4298   return false;
4299 }
4300 
4301 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
4302 /// such as function pointers returned from functions.
4303 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4304   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4305                                                   TheCall->getCallee());
4306   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4307             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4308             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4309             TheCall->getCallee()->getSourceRange(), CallType);
4310 
4311   return false;
4312 }
4313 
4314 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4315   if (!llvm::isValidAtomicOrderingCABI(Ordering))
4316     return false;
4317 
4318   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4319   switch (Op) {
4320   case AtomicExpr::AO__c11_atomic_init:
4321   case AtomicExpr::AO__opencl_atomic_init:
4322     llvm_unreachable("There is no ordering argument for an init");
4323 
4324   case AtomicExpr::AO__c11_atomic_load:
4325   case AtomicExpr::AO__opencl_atomic_load:
4326   case AtomicExpr::AO__atomic_load_n:
4327   case AtomicExpr::AO__atomic_load:
4328     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4329            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4330 
4331   case AtomicExpr::AO__c11_atomic_store:
4332   case AtomicExpr::AO__opencl_atomic_store:
4333   case AtomicExpr::AO__atomic_store:
4334   case AtomicExpr::AO__atomic_store_n:
4335     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4336            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4337            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4338 
4339   default:
4340     return true;
4341   }
4342 }
4343 
4344 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
4345                                          AtomicExpr::AtomicOp Op) {
4346   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4347   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4348   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4349   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
4350                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
4351                          Op);
4352 }
4353 
4354 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
4355                                  SourceLocation RParenLoc, MultiExprArg Args,
4356                                  AtomicExpr::AtomicOp Op,
4357                                  AtomicArgumentOrder ArgOrder) {
4358   // All the non-OpenCL operations take one of the following forms.
4359   // The OpenCL operations take the __c11 forms with one extra argument for
4360   // synchronization scope.
4361   enum {
4362     // C    __c11_atomic_init(A *, C)
4363     Init,
4364 
4365     // C    __c11_atomic_load(A *, int)
4366     Load,
4367 
4368     // void __atomic_load(A *, CP, int)
4369     LoadCopy,
4370 
4371     // void __atomic_store(A *, CP, int)
4372     Copy,
4373 
4374     // C    __c11_atomic_add(A *, M, int)
4375     Arithmetic,
4376 
4377     // C    __atomic_exchange_n(A *, CP, int)
4378     Xchg,
4379 
4380     // void __atomic_exchange(A *, C *, CP, int)
4381     GNUXchg,
4382 
4383     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4384     C11CmpXchg,
4385 
4386     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4387     GNUCmpXchg
4388   } Form = Init;
4389 
4390   const unsigned NumForm = GNUCmpXchg + 1;
4391   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
4392   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
4393   // where:
4394   //   C is an appropriate type,
4395   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4396   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4397   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4398   //   the int parameters are for orderings.
4399 
4400   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4401       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4402       "need to update code for modified forms");
4403   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
4404                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
4405                         AtomicExpr::AO__atomic_load,
4406                 "need to update code for modified C11 atomics");
4407   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
4408                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
4409   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
4410                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
4411                IsOpenCL;
4412   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4413              Op == AtomicExpr::AO__atomic_store_n ||
4414              Op == AtomicExpr::AO__atomic_exchange_n ||
4415              Op == AtomicExpr::AO__atomic_compare_exchange_n;
4416   bool IsAddSub = false;
4417 
4418   switch (Op) {
4419   case AtomicExpr::AO__c11_atomic_init:
4420   case AtomicExpr::AO__opencl_atomic_init:
4421     Form = Init;
4422     break;
4423 
4424   case AtomicExpr::AO__c11_atomic_load:
4425   case AtomicExpr::AO__opencl_atomic_load:
4426   case AtomicExpr::AO__atomic_load_n:
4427     Form = Load;
4428     break;
4429 
4430   case AtomicExpr::AO__atomic_load:
4431     Form = LoadCopy;
4432     break;
4433 
4434   case AtomicExpr::AO__c11_atomic_store:
4435   case AtomicExpr::AO__opencl_atomic_store:
4436   case AtomicExpr::AO__atomic_store:
4437   case AtomicExpr::AO__atomic_store_n:
4438     Form = Copy;
4439     break;
4440 
4441   case AtomicExpr::AO__c11_atomic_fetch_add:
4442   case AtomicExpr::AO__c11_atomic_fetch_sub:
4443   case AtomicExpr::AO__opencl_atomic_fetch_add:
4444   case AtomicExpr::AO__opencl_atomic_fetch_sub:
4445   case AtomicExpr::AO__atomic_fetch_add:
4446   case AtomicExpr::AO__atomic_fetch_sub:
4447   case AtomicExpr::AO__atomic_add_fetch:
4448   case AtomicExpr::AO__atomic_sub_fetch:
4449     IsAddSub = true;
4450     LLVM_FALLTHROUGH;
4451   case AtomicExpr::AO__c11_atomic_fetch_and:
4452   case AtomicExpr::AO__c11_atomic_fetch_or:
4453   case AtomicExpr::AO__c11_atomic_fetch_xor:
4454   case AtomicExpr::AO__opencl_atomic_fetch_and:
4455   case AtomicExpr::AO__opencl_atomic_fetch_or:
4456   case AtomicExpr::AO__opencl_atomic_fetch_xor:
4457   case AtomicExpr::AO__atomic_fetch_and:
4458   case AtomicExpr::AO__atomic_fetch_or:
4459   case AtomicExpr::AO__atomic_fetch_xor:
4460   case AtomicExpr::AO__atomic_fetch_nand:
4461   case AtomicExpr::AO__atomic_and_fetch:
4462   case AtomicExpr::AO__atomic_or_fetch:
4463   case AtomicExpr::AO__atomic_xor_fetch:
4464   case AtomicExpr::AO__atomic_nand_fetch:
4465   case AtomicExpr::AO__c11_atomic_fetch_min:
4466   case AtomicExpr::AO__c11_atomic_fetch_max:
4467   case AtomicExpr::AO__opencl_atomic_fetch_min:
4468   case AtomicExpr::AO__opencl_atomic_fetch_max:
4469   case AtomicExpr::AO__atomic_min_fetch:
4470   case AtomicExpr::AO__atomic_max_fetch:
4471   case AtomicExpr::AO__atomic_fetch_min:
4472   case AtomicExpr::AO__atomic_fetch_max:
4473     Form = Arithmetic;
4474     break;
4475 
4476   case AtomicExpr::AO__c11_atomic_exchange:
4477   case AtomicExpr::AO__opencl_atomic_exchange:
4478   case AtomicExpr::AO__atomic_exchange_n:
4479     Form = Xchg;
4480     break;
4481 
4482   case AtomicExpr::AO__atomic_exchange:
4483     Form = GNUXchg;
4484     break;
4485 
4486   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4487   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4488   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4489   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4490     Form = C11CmpXchg;
4491     break;
4492 
4493   case AtomicExpr::AO__atomic_compare_exchange:
4494   case AtomicExpr::AO__atomic_compare_exchange_n:
4495     Form = GNUCmpXchg;
4496     break;
4497   }
4498 
4499   unsigned AdjustedNumArgs = NumArgs[Form];
4500   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
4501     ++AdjustedNumArgs;
4502   // Check we have the right number of arguments.
4503   if (Args.size() < AdjustedNumArgs) {
4504     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
4505         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4506         << ExprRange;
4507     return ExprError();
4508   } else if (Args.size() > AdjustedNumArgs) {
4509     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
4510          diag::err_typecheck_call_too_many_args)
4511         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4512         << ExprRange;
4513     return ExprError();
4514   }
4515 
4516   // Inspect the first argument of the atomic operation.
4517   Expr *Ptr = Args[0];
4518   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
4519   if (ConvertedPtr.isInvalid())
4520     return ExprError();
4521 
4522   Ptr = ConvertedPtr.get();
4523   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4524   if (!pointerType) {
4525     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
4526         << Ptr->getType() << Ptr->getSourceRange();
4527     return ExprError();
4528   }
4529 
4530   // For a __c11 builtin, this should be a pointer to an _Atomic type.
4531   QualType AtomTy = pointerType->getPointeeType(); // 'A'
4532   QualType ValType = AtomTy; // 'C'
4533   if (IsC11) {
4534     if (!AtomTy->isAtomicType()) {
4535       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
4536           << Ptr->getType() << Ptr->getSourceRange();
4537       return ExprError();
4538     }
4539     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
4540         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
4541       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
4542           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4543           << Ptr->getSourceRange();
4544       return ExprError();
4545     }
4546     ValType = AtomTy->castAs<AtomicType>()->getValueType();
4547   } else if (Form != Load && Form != LoadCopy) {
4548     if (ValType.isConstQualified()) {
4549       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
4550           << Ptr->getType() << Ptr->getSourceRange();
4551       return ExprError();
4552     }
4553   }
4554 
4555   // For an arithmetic operation, the implied arithmetic must be well-formed.
4556   if (Form == Arithmetic) {
4557     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
4558     if (IsAddSub && !ValType->isIntegerType()
4559         && !ValType->isPointerType()) {
4560       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4561           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4562       return ExprError();
4563     }
4564     if (!IsAddSub && !ValType->isIntegerType()) {
4565       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
4566           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4567       return ExprError();
4568     }
4569     if (IsC11 && ValType->isPointerType() &&
4570         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
4571                             diag::err_incomplete_type)) {
4572       return ExprError();
4573     }
4574   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
4575     // For __atomic_*_n operations, the value type must be a scalar integral or
4576     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
4577     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4578         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4579     return ExprError();
4580   }
4581 
4582   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4583       !AtomTy->isScalarType()) {
4584     // For GNU atomics, require a trivially-copyable type. This is not part of
4585     // the GNU atomics specification, but we enforce it for sanity.
4586     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
4587         << Ptr->getType() << Ptr->getSourceRange();
4588     return ExprError();
4589   }
4590 
4591   switch (ValType.getObjCLifetime()) {
4592   case Qualifiers::OCL_None:
4593   case Qualifiers::OCL_ExplicitNone:
4594     // okay
4595     break;
4596 
4597   case Qualifiers::OCL_Weak:
4598   case Qualifiers::OCL_Strong:
4599   case Qualifiers::OCL_Autoreleasing:
4600     // FIXME: Can this happen? By this point, ValType should be known
4601     // to be trivially copyable.
4602     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
4603         << ValType << Ptr->getSourceRange();
4604     return ExprError();
4605   }
4606 
4607   // All atomic operations have an overload which takes a pointer to a volatile
4608   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
4609   // into the result or the other operands. Similarly atomic_load takes a
4610   // pointer to a const 'A'.
4611   ValType.removeLocalVolatile();
4612   ValType.removeLocalConst();
4613   QualType ResultType = ValType;
4614   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
4615       Form == Init)
4616     ResultType = Context.VoidTy;
4617   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
4618     ResultType = Context.BoolTy;
4619 
4620   // The type of a parameter passed 'by value'. In the GNU atomics, such
4621   // arguments are actually passed as pointers.
4622   QualType ByValType = ValType; // 'CP'
4623   bool IsPassedByAddress = false;
4624   if (!IsC11 && !IsN) {
4625     ByValType = Ptr->getType();
4626     IsPassedByAddress = true;
4627   }
4628 
4629   SmallVector<Expr *, 5> APIOrderedArgs;
4630   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
4631     APIOrderedArgs.push_back(Args[0]);
4632     switch (Form) {
4633     case Init:
4634     case Load:
4635       APIOrderedArgs.push_back(Args[1]); // Val1/Order
4636       break;
4637     case LoadCopy:
4638     case Copy:
4639     case Arithmetic:
4640     case Xchg:
4641       APIOrderedArgs.push_back(Args[2]); // Val1
4642       APIOrderedArgs.push_back(Args[1]); // Order
4643       break;
4644     case GNUXchg:
4645       APIOrderedArgs.push_back(Args[2]); // Val1
4646       APIOrderedArgs.push_back(Args[3]); // Val2
4647       APIOrderedArgs.push_back(Args[1]); // Order
4648       break;
4649     case C11CmpXchg:
4650       APIOrderedArgs.push_back(Args[2]); // Val1
4651       APIOrderedArgs.push_back(Args[4]); // Val2
4652       APIOrderedArgs.push_back(Args[1]); // Order
4653       APIOrderedArgs.push_back(Args[3]); // OrderFail
4654       break;
4655     case GNUCmpXchg:
4656       APIOrderedArgs.push_back(Args[2]); // Val1
4657       APIOrderedArgs.push_back(Args[4]); // Val2
4658       APIOrderedArgs.push_back(Args[5]); // Weak
4659       APIOrderedArgs.push_back(Args[1]); // Order
4660       APIOrderedArgs.push_back(Args[3]); // OrderFail
4661       break;
4662     }
4663   } else
4664     APIOrderedArgs.append(Args.begin(), Args.end());
4665 
4666   // The first argument's non-CV pointer type is used to deduce the type of
4667   // subsequent arguments, except for:
4668   //  - weak flag (always converted to bool)
4669   //  - memory order (always converted to int)
4670   //  - scope  (always converted to int)
4671   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
4672     QualType Ty;
4673     if (i < NumVals[Form] + 1) {
4674       switch (i) {
4675       case 0:
4676         // The first argument is always a pointer. It has a fixed type.
4677         // It is always dereferenced, a nullptr is undefined.
4678         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4679         // Nothing else to do: we already know all we want about this pointer.
4680         continue;
4681       case 1:
4682         // The second argument is the non-atomic operand. For arithmetic, this
4683         // is always passed by value, and for a compare_exchange it is always
4684         // passed by address. For the rest, GNU uses by-address and C11 uses
4685         // by-value.
4686         assert(Form != Load);
4687         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
4688           Ty = ValType;
4689         else if (Form == Copy || Form == Xchg) {
4690           if (IsPassedByAddress) {
4691             // The value pointer is always dereferenced, a nullptr is undefined.
4692             CheckNonNullArgument(*this, APIOrderedArgs[i],
4693                                  ExprRange.getBegin());
4694           }
4695           Ty = ByValType;
4696         } else if (Form == Arithmetic)
4697           Ty = Context.getPointerDiffType();
4698         else {
4699           Expr *ValArg = APIOrderedArgs[i];
4700           // The value pointer is always dereferenced, a nullptr is undefined.
4701           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
4702           LangAS AS = LangAS::Default;
4703           // Keep address space of non-atomic pointer type.
4704           if (const PointerType *PtrTy =
4705                   ValArg->getType()->getAs<PointerType>()) {
4706             AS = PtrTy->getPointeeType().getAddressSpace();
4707           }
4708           Ty = Context.getPointerType(
4709               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
4710         }
4711         break;
4712       case 2:
4713         // The third argument to compare_exchange / GNU exchange is the desired
4714         // value, either by-value (for the C11 and *_n variant) or as a pointer.
4715         if (IsPassedByAddress)
4716           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4717         Ty = ByValType;
4718         break;
4719       case 3:
4720         // The fourth argument to GNU compare_exchange is a 'weak' flag.
4721         Ty = Context.BoolTy;
4722         break;
4723       }
4724     } else {
4725       // The order(s) and scope are always converted to int.
4726       Ty = Context.IntTy;
4727     }
4728 
4729     InitializedEntity Entity =
4730         InitializedEntity::InitializeParameter(Context, Ty, false);
4731     ExprResult Arg = APIOrderedArgs[i];
4732     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4733     if (Arg.isInvalid())
4734       return true;
4735     APIOrderedArgs[i] = Arg.get();
4736   }
4737 
4738   // Permute the arguments into a 'consistent' order.
4739   SmallVector<Expr*, 5> SubExprs;
4740   SubExprs.push_back(Ptr);
4741   switch (Form) {
4742   case Init:
4743     // Note, AtomicExpr::getVal1() has a special case for this atomic.
4744     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4745     break;
4746   case Load:
4747     SubExprs.push_back(APIOrderedArgs[1]); // Order
4748     break;
4749   case LoadCopy:
4750   case Copy:
4751   case Arithmetic:
4752   case Xchg:
4753     SubExprs.push_back(APIOrderedArgs[2]); // Order
4754     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4755     break;
4756   case GNUXchg:
4757     // Note, AtomicExpr::getVal2() has a special case for this atomic.
4758     SubExprs.push_back(APIOrderedArgs[3]); // Order
4759     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4760     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4761     break;
4762   case C11CmpXchg:
4763     SubExprs.push_back(APIOrderedArgs[3]); // Order
4764     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4765     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
4766     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4767     break;
4768   case GNUCmpXchg:
4769     SubExprs.push_back(APIOrderedArgs[4]); // Order
4770     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4771     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
4772     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4773     SubExprs.push_back(APIOrderedArgs[3]); // Weak
4774     break;
4775   }
4776 
4777   if (SubExprs.size() >= 2 && Form != Init) {
4778     llvm::APSInt Result(32);
4779     if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
4780         !isValidOrderingForOp(Result.getSExtValue(), Op))
4781       Diag(SubExprs[1]->getBeginLoc(),
4782            diag::warn_atomic_op_has_invalid_memory_order)
4783           << SubExprs[1]->getSourceRange();
4784   }
4785 
4786   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
4787     auto *Scope = Args[Args.size() - 1];
4788     llvm::APSInt Result(32);
4789     if (Scope->isIntegerConstantExpr(Result, Context) &&
4790         !ScopeModel->isValid(Result.getZExtValue())) {
4791       Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
4792           << Scope->getSourceRange();
4793     }
4794     SubExprs.push_back(Scope);
4795   }
4796 
4797   AtomicExpr *AE = new (Context)
4798       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
4799 
4800   if ((Op == AtomicExpr::AO__c11_atomic_load ||
4801        Op == AtomicExpr::AO__c11_atomic_store ||
4802        Op == AtomicExpr::AO__opencl_atomic_load ||
4803        Op == AtomicExpr::AO__opencl_atomic_store ) &&
4804       Context.AtomicUsesUnsupportedLibcall(AE))
4805     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
4806         << ((Op == AtomicExpr::AO__c11_atomic_load ||
4807              Op == AtomicExpr::AO__opencl_atomic_load)
4808                 ? 0
4809                 : 1);
4810 
4811   return AE;
4812 }
4813 
4814 /// checkBuiltinArgument - Given a call to a builtin function, perform
4815 /// normal type-checking on the given argument, updating the call in
4816 /// place.  This is useful when a builtin function requires custom
4817 /// type-checking for some of its arguments but not necessarily all of
4818 /// them.
4819 ///
4820 /// Returns true on error.
4821 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
4822   FunctionDecl *Fn = E->getDirectCallee();
4823   assert(Fn && "builtin call without direct callee!");
4824 
4825   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
4826   InitializedEntity Entity =
4827     InitializedEntity::InitializeParameter(S.Context, Param);
4828 
4829   ExprResult Arg = E->getArg(0);
4830   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
4831   if (Arg.isInvalid())
4832     return true;
4833 
4834   E->setArg(ArgIndex, Arg.get());
4835   return false;
4836 }
4837 
4838 /// We have a call to a function like __sync_fetch_and_add, which is an
4839 /// overloaded function based on the pointer type of its first argument.
4840 /// The main BuildCallExpr routines have already promoted the types of
4841 /// arguments because all of these calls are prototyped as void(...).
4842 ///
4843 /// This function goes through and does final semantic checking for these
4844 /// builtins, as well as generating any warnings.
4845 ExprResult
4846 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
4847   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
4848   Expr *Callee = TheCall->getCallee();
4849   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
4850   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4851 
4852   // Ensure that we have at least one argument to do type inference from.
4853   if (TheCall->getNumArgs() < 1) {
4854     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
4855         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
4856     return ExprError();
4857   }
4858 
4859   // Inspect the first argument of the atomic builtin.  This should always be
4860   // a pointer type, whose element is an integral scalar or pointer type.
4861   // Because it is a pointer type, we don't have to worry about any implicit
4862   // casts here.
4863   // FIXME: We don't allow floating point scalars as input.
4864   Expr *FirstArg = TheCall->getArg(0);
4865   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
4866   if (FirstArgResult.isInvalid())
4867     return ExprError();
4868   FirstArg = FirstArgResult.get();
4869   TheCall->setArg(0, FirstArg);
4870 
4871   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
4872   if (!pointerType) {
4873     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
4874         << FirstArg->getType() << FirstArg->getSourceRange();
4875     return ExprError();
4876   }
4877 
4878   QualType ValType = pointerType->getPointeeType();
4879   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
4880       !ValType->isBlockPointerType()) {
4881     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
4882         << FirstArg->getType() << FirstArg->getSourceRange();
4883     return ExprError();
4884   }
4885 
4886   if (ValType.isConstQualified()) {
4887     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
4888         << FirstArg->getType() << FirstArg->getSourceRange();
4889     return ExprError();
4890   }
4891 
4892   switch (ValType.getObjCLifetime()) {
4893   case Qualifiers::OCL_None:
4894   case Qualifiers::OCL_ExplicitNone:
4895     // okay
4896     break;
4897 
4898   case Qualifiers::OCL_Weak:
4899   case Qualifiers::OCL_Strong:
4900   case Qualifiers::OCL_Autoreleasing:
4901     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
4902         << ValType << FirstArg->getSourceRange();
4903     return ExprError();
4904   }
4905 
4906   // Strip any qualifiers off ValType.
4907   ValType = ValType.getUnqualifiedType();
4908 
4909   // The majority of builtins return a value, but a few have special return
4910   // types, so allow them to override appropriately below.
4911   QualType ResultType = ValType;
4912 
4913   // We need to figure out which concrete builtin this maps onto.  For example,
4914   // __sync_fetch_and_add with a 2 byte object turns into
4915   // __sync_fetch_and_add_2.
4916 #define BUILTIN_ROW(x) \
4917   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
4918     Builtin::BI##x##_8, Builtin::BI##x##_16 }
4919 
4920   static const unsigned BuiltinIndices[][5] = {
4921     BUILTIN_ROW(__sync_fetch_and_add),
4922     BUILTIN_ROW(__sync_fetch_and_sub),
4923     BUILTIN_ROW(__sync_fetch_and_or),
4924     BUILTIN_ROW(__sync_fetch_and_and),
4925     BUILTIN_ROW(__sync_fetch_and_xor),
4926     BUILTIN_ROW(__sync_fetch_and_nand),
4927 
4928     BUILTIN_ROW(__sync_add_and_fetch),
4929     BUILTIN_ROW(__sync_sub_and_fetch),
4930     BUILTIN_ROW(__sync_and_and_fetch),
4931     BUILTIN_ROW(__sync_or_and_fetch),
4932     BUILTIN_ROW(__sync_xor_and_fetch),
4933     BUILTIN_ROW(__sync_nand_and_fetch),
4934 
4935     BUILTIN_ROW(__sync_val_compare_and_swap),
4936     BUILTIN_ROW(__sync_bool_compare_and_swap),
4937     BUILTIN_ROW(__sync_lock_test_and_set),
4938     BUILTIN_ROW(__sync_lock_release),
4939     BUILTIN_ROW(__sync_swap)
4940   };
4941 #undef BUILTIN_ROW
4942 
4943   // Determine the index of the size.
4944   unsigned SizeIndex;
4945   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
4946   case 1: SizeIndex = 0; break;
4947   case 2: SizeIndex = 1; break;
4948   case 4: SizeIndex = 2; break;
4949   case 8: SizeIndex = 3; break;
4950   case 16: SizeIndex = 4; break;
4951   default:
4952     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
4953         << FirstArg->getType() << FirstArg->getSourceRange();
4954     return ExprError();
4955   }
4956 
4957   // Each of these builtins has one pointer argument, followed by some number of
4958   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
4959   // that we ignore.  Find out which row of BuiltinIndices to read from as well
4960   // as the number of fixed args.
4961   unsigned BuiltinID = FDecl->getBuiltinID();
4962   unsigned BuiltinIndex, NumFixed = 1;
4963   bool WarnAboutSemanticsChange = false;
4964   switch (BuiltinID) {
4965   default: llvm_unreachable("Unknown overloaded atomic builtin!");
4966   case Builtin::BI__sync_fetch_and_add:
4967   case Builtin::BI__sync_fetch_and_add_1:
4968   case Builtin::BI__sync_fetch_and_add_2:
4969   case Builtin::BI__sync_fetch_and_add_4:
4970   case Builtin::BI__sync_fetch_and_add_8:
4971   case Builtin::BI__sync_fetch_and_add_16:
4972     BuiltinIndex = 0;
4973     break;
4974 
4975   case Builtin::BI__sync_fetch_and_sub:
4976   case Builtin::BI__sync_fetch_and_sub_1:
4977   case Builtin::BI__sync_fetch_and_sub_2:
4978   case Builtin::BI__sync_fetch_and_sub_4:
4979   case Builtin::BI__sync_fetch_and_sub_8:
4980   case Builtin::BI__sync_fetch_and_sub_16:
4981     BuiltinIndex = 1;
4982     break;
4983 
4984   case Builtin::BI__sync_fetch_and_or:
4985   case Builtin::BI__sync_fetch_and_or_1:
4986   case Builtin::BI__sync_fetch_and_or_2:
4987   case Builtin::BI__sync_fetch_and_or_4:
4988   case Builtin::BI__sync_fetch_and_or_8:
4989   case Builtin::BI__sync_fetch_and_or_16:
4990     BuiltinIndex = 2;
4991     break;
4992 
4993   case Builtin::BI__sync_fetch_and_and:
4994   case Builtin::BI__sync_fetch_and_and_1:
4995   case Builtin::BI__sync_fetch_and_and_2:
4996   case Builtin::BI__sync_fetch_and_and_4:
4997   case Builtin::BI__sync_fetch_and_and_8:
4998   case Builtin::BI__sync_fetch_and_and_16:
4999     BuiltinIndex = 3;
5000     break;
5001 
5002   case Builtin::BI__sync_fetch_and_xor:
5003   case Builtin::BI__sync_fetch_and_xor_1:
5004   case Builtin::BI__sync_fetch_and_xor_2:
5005   case Builtin::BI__sync_fetch_and_xor_4:
5006   case Builtin::BI__sync_fetch_and_xor_8:
5007   case Builtin::BI__sync_fetch_and_xor_16:
5008     BuiltinIndex = 4;
5009     break;
5010 
5011   case Builtin::BI__sync_fetch_and_nand:
5012   case Builtin::BI__sync_fetch_and_nand_1:
5013   case Builtin::BI__sync_fetch_and_nand_2:
5014   case Builtin::BI__sync_fetch_and_nand_4:
5015   case Builtin::BI__sync_fetch_and_nand_8:
5016   case Builtin::BI__sync_fetch_and_nand_16:
5017     BuiltinIndex = 5;
5018     WarnAboutSemanticsChange = true;
5019     break;
5020 
5021   case Builtin::BI__sync_add_and_fetch:
5022   case Builtin::BI__sync_add_and_fetch_1:
5023   case Builtin::BI__sync_add_and_fetch_2:
5024   case Builtin::BI__sync_add_and_fetch_4:
5025   case Builtin::BI__sync_add_and_fetch_8:
5026   case Builtin::BI__sync_add_and_fetch_16:
5027     BuiltinIndex = 6;
5028     break;
5029 
5030   case Builtin::BI__sync_sub_and_fetch:
5031   case Builtin::BI__sync_sub_and_fetch_1:
5032   case Builtin::BI__sync_sub_and_fetch_2:
5033   case Builtin::BI__sync_sub_and_fetch_4:
5034   case Builtin::BI__sync_sub_and_fetch_8:
5035   case Builtin::BI__sync_sub_and_fetch_16:
5036     BuiltinIndex = 7;
5037     break;
5038 
5039   case Builtin::BI__sync_and_and_fetch:
5040   case Builtin::BI__sync_and_and_fetch_1:
5041   case Builtin::BI__sync_and_and_fetch_2:
5042   case Builtin::BI__sync_and_and_fetch_4:
5043   case Builtin::BI__sync_and_and_fetch_8:
5044   case Builtin::BI__sync_and_and_fetch_16:
5045     BuiltinIndex = 8;
5046     break;
5047 
5048   case Builtin::BI__sync_or_and_fetch:
5049   case Builtin::BI__sync_or_and_fetch_1:
5050   case Builtin::BI__sync_or_and_fetch_2:
5051   case Builtin::BI__sync_or_and_fetch_4:
5052   case Builtin::BI__sync_or_and_fetch_8:
5053   case Builtin::BI__sync_or_and_fetch_16:
5054     BuiltinIndex = 9;
5055     break;
5056 
5057   case Builtin::BI__sync_xor_and_fetch:
5058   case Builtin::BI__sync_xor_and_fetch_1:
5059   case Builtin::BI__sync_xor_and_fetch_2:
5060   case Builtin::BI__sync_xor_and_fetch_4:
5061   case Builtin::BI__sync_xor_and_fetch_8:
5062   case Builtin::BI__sync_xor_and_fetch_16:
5063     BuiltinIndex = 10;
5064     break;
5065 
5066   case Builtin::BI__sync_nand_and_fetch:
5067   case Builtin::BI__sync_nand_and_fetch_1:
5068   case Builtin::BI__sync_nand_and_fetch_2:
5069   case Builtin::BI__sync_nand_and_fetch_4:
5070   case Builtin::BI__sync_nand_and_fetch_8:
5071   case Builtin::BI__sync_nand_and_fetch_16:
5072     BuiltinIndex = 11;
5073     WarnAboutSemanticsChange = true;
5074     break;
5075 
5076   case Builtin::BI__sync_val_compare_and_swap:
5077   case Builtin::BI__sync_val_compare_and_swap_1:
5078   case Builtin::BI__sync_val_compare_and_swap_2:
5079   case Builtin::BI__sync_val_compare_and_swap_4:
5080   case Builtin::BI__sync_val_compare_and_swap_8:
5081   case Builtin::BI__sync_val_compare_and_swap_16:
5082     BuiltinIndex = 12;
5083     NumFixed = 2;
5084     break;
5085 
5086   case Builtin::BI__sync_bool_compare_and_swap:
5087   case Builtin::BI__sync_bool_compare_and_swap_1:
5088   case Builtin::BI__sync_bool_compare_and_swap_2:
5089   case Builtin::BI__sync_bool_compare_and_swap_4:
5090   case Builtin::BI__sync_bool_compare_and_swap_8:
5091   case Builtin::BI__sync_bool_compare_and_swap_16:
5092     BuiltinIndex = 13;
5093     NumFixed = 2;
5094     ResultType = Context.BoolTy;
5095     break;
5096 
5097   case Builtin::BI__sync_lock_test_and_set:
5098   case Builtin::BI__sync_lock_test_and_set_1:
5099   case Builtin::BI__sync_lock_test_and_set_2:
5100   case Builtin::BI__sync_lock_test_and_set_4:
5101   case Builtin::BI__sync_lock_test_and_set_8:
5102   case Builtin::BI__sync_lock_test_and_set_16:
5103     BuiltinIndex = 14;
5104     break;
5105 
5106   case Builtin::BI__sync_lock_release:
5107   case Builtin::BI__sync_lock_release_1:
5108   case Builtin::BI__sync_lock_release_2:
5109   case Builtin::BI__sync_lock_release_4:
5110   case Builtin::BI__sync_lock_release_8:
5111   case Builtin::BI__sync_lock_release_16:
5112     BuiltinIndex = 15;
5113     NumFixed = 0;
5114     ResultType = Context.VoidTy;
5115     break;
5116 
5117   case Builtin::BI__sync_swap:
5118   case Builtin::BI__sync_swap_1:
5119   case Builtin::BI__sync_swap_2:
5120   case Builtin::BI__sync_swap_4:
5121   case Builtin::BI__sync_swap_8:
5122   case Builtin::BI__sync_swap_16:
5123     BuiltinIndex = 16;
5124     break;
5125   }
5126 
5127   // Now that we know how many fixed arguments we expect, first check that we
5128   // have at least that many.
5129   if (TheCall->getNumArgs() < 1+NumFixed) {
5130     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5131         << 0 << 1 + NumFixed << TheCall->getNumArgs()
5132         << Callee->getSourceRange();
5133     return ExprError();
5134   }
5135 
5136   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5137       << Callee->getSourceRange();
5138 
5139   if (WarnAboutSemanticsChange) {
5140     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5141         << Callee->getSourceRange();
5142   }
5143 
5144   // Get the decl for the concrete builtin from this, we can tell what the
5145   // concrete integer type we should convert to is.
5146   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5147   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5148   FunctionDecl *NewBuiltinDecl;
5149   if (NewBuiltinID == BuiltinID)
5150     NewBuiltinDecl = FDecl;
5151   else {
5152     // Perform builtin lookup to avoid redeclaring it.
5153     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5154     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5155     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5156     assert(Res.getFoundDecl());
5157     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5158     if (!NewBuiltinDecl)
5159       return ExprError();
5160   }
5161 
5162   // The first argument --- the pointer --- has a fixed type; we
5163   // deduce the types of the rest of the arguments accordingly.  Walk
5164   // the remaining arguments, converting them to the deduced value type.
5165   for (unsigned i = 0; i != NumFixed; ++i) {
5166     ExprResult Arg = TheCall->getArg(i+1);
5167 
5168     // GCC does an implicit conversion to the pointer or integer ValType.  This
5169     // can fail in some cases (1i -> int**), check for this error case now.
5170     // Initialize the argument.
5171     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5172                                                    ValType, /*consume*/ false);
5173     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5174     if (Arg.isInvalid())
5175       return ExprError();
5176 
5177     // Okay, we have something that *can* be converted to the right type.  Check
5178     // to see if there is a potentially weird extension going on here.  This can
5179     // happen when you do an atomic operation on something like an char* and
5180     // pass in 42.  The 42 gets converted to char.  This is even more strange
5181     // for things like 45.123 -> char, etc.
5182     // FIXME: Do this check.
5183     TheCall->setArg(i+1, Arg.get());
5184   }
5185 
5186   // Create a new DeclRefExpr to refer to the new decl.
5187   DeclRefExpr *NewDRE = DeclRefExpr::Create(
5188       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5189       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5190       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
5191 
5192   // Set the callee in the CallExpr.
5193   // FIXME: This loses syntactic information.
5194   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5195   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5196                                               CK_BuiltinFnToFnPtr);
5197   TheCall->setCallee(PromotedCall.get());
5198 
5199   // Change the result type of the call to match the original value type. This
5200   // is arbitrary, but the codegen for these builtins ins design to handle it
5201   // gracefully.
5202   TheCall->setType(ResultType);
5203 
5204   return TheCallResult;
5205 }
5206 
5207 /// SemaBuiltinNontemporalOverloaded - We have a call to
5208 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
5209 /// overloaded function based on the pointer type of its last argument.
5210 ///
5211 /// This function goes through and does final semantic checking for these
5212 /// builtins.
5213 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5214   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5215   DeclRefExpr *DRE =
5216       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5217   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5218   unsigned BuiltinID = FDecl->getBuiltinID();
5219   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5220           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5221          "Unexpected nontemporal load/store builtin!");
5222   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5223   unsigned numArgs = isStore ? 2 : 1;
5224 
5225   // Ensure that we have the proper number of arguments.
5226   if (checkArgCount(*this, TheCall, numArgs))
5227     return ExprError();
5228 
5229   // Inspect the last argument of the nontemporal builtin.  This should always
5230   // be a pointer type, from which we imply the type of the memory access.
5231   // Because it is a pointer type, we don't have to worry about any implicit
5232   // casts here.
5233   Expr *PointerArg = TheCall->getArg(numArgs - 1);
5234   ExprResult PointerArgResult =
5235       DefaultFunctionArrayLvalueConversion(PointerArg);
5236 
5237   if (PointerArgResult.isInvalid())
5238     return ExprError();
5239   PointerArg = PointerArgResult.get();
5240   TheCall->setArg(numArgs - 1, PointerArg);
5241 
5242   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5243   if (!pointerType) {
5244     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5245         << PointerArg->getType() << PointerArg->getSourceRange();
5246     return ExprError();
5247   }
5248 
5249   QualType ValType = pointerType->getPointeeType();
5250 
5251   // Strip any qualifiers off ValType.
5252   ValType = ValType.getUnqualifiedType();
5253   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5254       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5255       !ValType->isVectorType()) {
5256     Diag(DRE->getBeginLoc(),
5257          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5258         << PointerArg->getType() << PointerArg->getSourceRange();
5259     return ExprError();
5260   }
5261 
5262   if (!isStore) {
5263     TheCall->setType(ValType);
5264     return TheCallResult;
5265   }
5266 
5267   ExprResult ValArg = TheCall->getArg(0);
5268   InitializedEntity Entity = InitializedEntity::InitializeParameter(
5269       Context, ValType, /*consume*/ false);
5270   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5271   if (ValArg.isInvalid())
5272     return ExprError();
5273 
5274   TheCall->setArg(0, ValArg.get());
5275   TheCall->setType(Context.VoidTy);
5276   return TheCallResult;
5277 }
5278 
5279 /// CheckObjCString - Checks that the argument to the builtin
5280 /// CFString constructor is correct
5281 /// Note: It might also make sense to do the UTF-16 conversion here (would
5282 /// simplify the backend).
5283 bool Sema::CheckObjCString(Expr *Arg) {
5284   Arg = Arg->IgnoreParenCasts();
5285   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
5286 
5287   if (!Literal || !Literal->isAscii()) {
5288     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
5289         << Arg->getSourceRange();
5290     return true;
5291   }
5292 
5293   if (Literal->containsNonAsciiOrNull()) {
5294     StringRef String = Literal->getString();
5295     unsigned NumBytes = String.size();
5296     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
5297     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5298     llvm::UTF16 *ToPtr = &ToBuf[0];
5299 
5300     llvm::ConversionResult Result =
5301         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5302                                  ToPtr + NumBytes, llvm::strictConversion);
5303     // Check for conversion failure.
5304     if (Result != llvm::conversionOK)
5305       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
5306           << Arg->getSourceRange();
5307   }
5308   return false;
5309 }
5310 
5311 /// CheckObjCString - Checks that the format string argument to the os_log()
5312 /// and os_trace() functions is correct, and converts it to const char *.
5313 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5314   Arg = Arg->IgnoreParenCasts();
5315   auto *Literal = dyn_cast<StringLiteral>(Arg);
5316   if (!Literal) {
5317     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5318       Literal = ObjcLiteral->getString();
5319     }
5320   }
5321 
5322   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
5323     return ExprError(
5324         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5325         << Arg->getSourceRange());
5326   }
5327 
5328   ExprResult Result(Literal);
5329   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5330   InitializedEntity Entity =
5331       InitializedEntity::InitializeParameter(Context, ResultTy, false);
5332   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5333   return Result;
5334 }
5335 
5336 /// Check that the user is calling the appropriate va_start builtin for the
5337 /// target and calling convention.
5338 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5339   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5340   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5341   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
5342                     TT.getArch() == llvm::Triple::aarch64_32);
5343   bool IsWindows = TT.isOSWindows();
5344   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5345   if (IsX64 || IsAArch64) {
5346     CallingConv CC = CC_C;
5347     if (const FunctionDecl *FD = S.getCurFunctionDecl())
5348       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
5349     if (IsMSVAStart) {
5350       // Don't allow this in System V ABI functions.
5351       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
5352         return S.Diag(Fn->getBeginLoc(),
5353                       diag::err_ms_va_start_used_in_sysv_function);
5354     } else {
5355       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5356       // On x64 Windows, don't allow this in System V ABI functions.
5357       // (Yes, that means there's no corresponding way to support variadic
5358       // System V ABI functions on Windows.)
5359       if ((IsWindows && CC == CC_X86_64SysV) ||
5360           (!IsWindows && CC == CC_Win64))
5361         return S.Diag(Fn->getBeginLoc(),
5362                       diag::err_va_start_used_in_wrong_abi_function)
5363                << !IsWindows;
5364     }
5365     return false;
5366   }
5367 
5368   if (IsMSVAStart)
5369     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5370   return false;
5371 }
5372 
5373 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
5374                                              ParmVarDecl **LastParam = nullptr) {
5375   // Determine whether the current function, block, or obj-c method is variadic
5376   // and get its parameter list.
5377   bool IsVariadic = false;
5378   ArrayRef<ParmVarDecl *> Params;
5379   DeclContext *Caller = S.CurContext;
5380   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5381     IsVariadic = Block->isVariadic();
5382     Params = Block->parameters();
5383   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5384     IsVariadic = FD->isVariadic();
5385     Params = FD->parameters();
5386   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5387     IsVariadic = MD->isVariadic();
5388     // FIXME: This isn't correct for methods (results in bogus warning).
5389     Params = MD->parameters();
5390   } else if (isa<CapturedDecl>(Caller)) {
5391     // We don't support va_start in a CapturedDecl.
5392     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5393     return true;
5394   } else {
5395     // This must be some other declcontext that parses exprs.
5396     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5397     return true;
5398   }
5399 
5400   if (!IsVariadic) {
5401     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
5402     return true;
5403   }
5404 
5405   if (LastParam)
5406     *LastParam = Params.empty() ? nullptr : Params.back();
5407 
5408   return false;
5409 }
5410 
5411 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
5412 /// for validity.  Emit an error and return true on failure; return false
5413 /// on success.
5414 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5415   Expr *Fn = TheCall->getCallee();
5416 
5417   if (checkVAStartABI(*this, BuiltinID, Fn))
5418     return true;
5419 
5420   if (TheCall->getNumArgs() > 2) {
5421     Diag(TheCall->getArg(2)->getBeginLoc(),
5422          diag::err_typecheck_call_too_many_args)
5423         << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5424         << Fn->getSourceRange()
5425         << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5426                        (*(TheCall->arg_end() - 1))->getEndLoc());
5427     return true;
5428   }
5429 
5430   if (TheCall->getNumArgs() < 2) {
5431     return Diag(TheCall->getEndLoc(),
5432                 diag::err_typecheck_call_too_few_args_at_least)
5433            << 0 /*function call*/ << 2 << TheCall->getNumArgs();
5434   }
5435 
5436   // Type-check the first argument normally.
5437   if (checkBuiltinArgument(*this, TheCall, 0))
5438     return true;
5439 
5440   // Check that the current function is variadic, and get its last parameter.
5441   ParmVarDecl *LastParam;
5442   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5443     return true;
5444 
5445   // Verify that the second argument to the builtin is the last argument of the
5446   // current function or method.
5447   bool SecondArgIsLastNamedArgument = false;
5448   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5449 
5450   // These are valid if SecondArgIsLastNamedArgument is false after the next
5451   // block.
5452   QualType Type;
5453   SourceLocation ParamLoc;
5454   bool IsCRegister = false;
5455 
5456   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5457     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5458       SecondArgIsLastNamedArgument = PV == LastParam;
5459 
5460       Type = PV->getType();
5461       ParamLoc = PV->getLocation();
5462       IsCRegister =
5463           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5464     }
5465   }
5466 
5467   if (!SecondArgIsLastNamedArgument)
5468     Diag(TheCall->getArg(1)->getBeginLoc(),
5469          diag::warn_second_arg_of_va_start_not_last_named_param);
5470   else if (IsCRegister || Type->isReferenceType() ||
5471            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5472              // Promotable integers are UB, but enumerations need a bit of
5473              // extra checking to see what their promotable type actually is.
5474              if (!Type->isPromotableIntegerType())
5475                return false;
5476              if (!Type->isEnumeralType())
5477                return true;
5478              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
5479              return !(ED &&
5480                       Context.typesAreCompatible(ED->getPromotionType(), Type));
5481            }()) {
5482     unsigned Reason = 0;
5483     if (Type->isReferenceType())  Reason = 1;
5484     else if (IsCRegister)         Reason = 2;
5485     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
5486     Diag(ParamLoc, diag::note_parameter_type) << Type;
5487   }
5488 
5489   TheCall->setType(Context.VoidTy);
5490   return false;
5491 }
5492 
5493 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
5494   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5495   //                 const char *named_addr);
5496 
5497   Expr *Func = Call->getCallee();
5498 
5499   if (Call->getNumArgs() < 3)
5500     return Diag(Call->getEndLoc(),
5501                 diag::err_typecheck_call_too_few_args_at_least)
5502            << 0 /*function call*/ << 3 << Call->getNumArgs();
5503 
5504   // Type-check the first argument normally.
5505   if (checkBuiltinArgument(*this, Call, 0))
5506     return true;
5507 
5508   // Check that the current function is variadic.
5509   if (checkVAStartIsInVariadicFunction(*this, Func))
5510     return true;
5511 
5512   // __va_start on Windows does not validate the parameter qualifiers
5513 
5514   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5515   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5516 
5517   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5518   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5519 
5520   const QualType &ConstCharPtrTy =
5521       Context.getPointerType(Context.CharTy.withConst());
5522   if (!Arg1Ty->isPointerType() ||
5523       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
5524     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5525         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5526         << 0                                      /* qualifier difference */
5527         << 3                                      /* parameter mismatch */
5528         << 2 << Arg1->getType() << ConstCharPtrTy;
5529 
5530   const QualType SizeTy = Context.getSizeType();
5531   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
5532     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5533         << Arg2->getType() << SizeTy << 1 /* different class */
5534         << 0                              /* qualifier difference */
5535         << 3                              /* parameter mismatch */
5536         << 3 << Arg2->getType() << SizeTy;
5537 
5538   return false;
5539 }
5540 
5541 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
5542 /// friends.  This is declared to take (...), so we have to check everything.
5543 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
5544   if (TheCall->getNumArgs() < 2)
5545     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5546            << 0 << 2 << TheCall->getNumArgs() /*function call*/;
5547   if (TheCall->getNumArgs() > 2)
5548     return Diag(TheCall->getArg(2)->getBeginLoc(),
5549                 diag::err_typecheck_call_too_many_args)
5550            << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5551            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5552                           (*(TheCall->arg_end() - 1))->getEndLoc());
5553 
5554   ExprResult OrigArg0 = TheCall->getArg(0);
5555   ExprResult OrigArg1 = TheCall->getArg(1);
5556 
5557   // Do standard promotions between the two arguments, returning their common
5558   // type.
5559   QualType Res = UsualArithmeticConversions(
5560       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
5561   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5562     return true;
5563 
5564   // Make sure any conversions are pushed back into the call; this is
5565   // type safe since unordered compare builtins are declared as "_Bool
5566   // foo(...)".
5567   TheCall->setArg(0, OrigArg0.get());
5568   TheCall->setArg(1, OrigArg1.get());
5569 
5570   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5571     return false;
5572 
5573   // If the common type isn't a real floating type, then the arguments were
5574   // invalid for this operation.
5575   if (Res.isNull() || !Res->isRealFloatingType())
5576     return Diag(OrigArg0.get()->getBeginLoc(),
5577                 diag::err_typecheck_call_invalid_ordered_compare)
5578            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5579            << SourceRange(OrigArg0.get()->getBeginLoc(),
5580                           OrigArg1.get()->getEndLoc());
5581 
5582   return false;
5583 }
5584 
5585 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
5586 /// __builtin_isnan and friends.  This is declared to take (...), so we have
5587 /// to check everything. We expect the last argument to be a floating point
5588 /// value.
5589 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
5590   if (TheCall->getNumArgs() < NumArgs)
5591     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5592            << 0 << NumArgs << TheCall->getNumArgs() /*function call*/;
5593   if (TheCall->getNumArgs() > NumArgs)
5594     return Diag(TheCall->getArg(NumArgs)->getBeginLoc(),
5595                 diag::err_typecheck_call_too_many_args)
5596            << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
5597            << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(),
5598                           (*(TheCall->arg_end() - 1))->getEndLoc());
5599 
5600   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
5601   // on all preceding parameters just being int.  Try all of those.
5602   for (unsigned i = 0; i < NumArgs - 1; ++i) {
5603     Expr *Arg = TheCall->getArg(i);
5604 
5605     if (Arg->isTypeDependent())
5606       return false;
5607 
5608     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
5609 
5610     if (Res.isInvalid())
5611       return true;
5612     TheCall->setArg(i, Res.get());
5613   }
5614 
5615   Expr *OrigArg = TheCall->getArg(NumArgs-1);
5616 
5617   if (OrigArg->isTypeDependent())
5618     return false;
5619 
5620   // Usual Unary Conversions will convert half to float, which we want for
5621   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
5622   // type how it is, but do normal L->Rvalue conversions.
5623   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
5624     OrigArg = UsualUnaryConversions(OrigArg).get();
5625   else
5626     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
5627   TheCall->setArg(NumArgs - 1, OrigArg);
5628 
5629   // This operation requires a non-_Complex floating-point number.
5630   if (!OrigArg->getType()->isRealFloatingType())
5631     return Diag(OrigArg->getBeginLoc(),
5632                 diag::err_typecheck_call_invalid_unary_fp)
5633            << OrigArg->getType() << OrigArg->getSourceRange();
5634 
5635   return false;
5636 }
5637 
5638 // Customized Sema Checking for VSX builtins that have the following signature:
5639 // vector [...] builtinName(vector [...], vector [...], const int);
5640 // Which takes the same type of vectors (any legal vector type) for the first
5641 // two arguments and takes compile time constant for the third argument.
5642 // Example builtins are :
5643 // vector double vec_xxpermdi(vector double, vector double, int);
5644 // vector short vec_xxsldwi(vector short, vector short, int);
5645 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
5646   unsigned ExpectedNumArgs = 3;
5647   if (TheCall->getNumArgs() < ExpectedNumArgs)
5648     return Diag(TheCall->getEndLoc(),
5649                 diag::err_typecheck_call_too_few_args_at_least)
5650            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5651            << TheCall->getSourceRange();
5652 
5653   if (TheCall->getNumArgs() > ExpectedNumArgs)
5654     return Diag(TheCall->getEndLoc(),
5655                 diag::err_typecheck_call_too_many_args_at_most)
5656            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5657            << TheCall->getSourceRange();
5658 
5659   // Check the third argument is a compile time constant
5660   llvm::APSInt Value;
5661   if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
5662     return Diag(TheCall->getBeginLoc(),
5663                 diag::err_vsx_builtin_nonconstant_argument)
5664            << 3 /* argument index */ << TheCall->getDirectCallee()
5665            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5666                           TheCall->getArg(2)->getEndLoc());
5667 
5668   QualType Arg1Ty = TheCall->getArg(0)->getType();
5669   QualType Arg2Ty = TheCall->getArg(1)->getType();
5670 
5671   // Check the type of argument 1 and argument 2 are vectors.
5672   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
5673   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
5674       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
5675     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
5676            << TheCall->getDirectCallee()
5677            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5678                           TheCall->getArg(1)->getEndLoc());
5679   }
5680 
5681   // Check the first two arguments are the same type.
5682   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
5683     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
5684            << TheCall->getDirectCallee()
5685            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5686                           TheCall->getArg(1)->getEndLoc());
5687   }
5688 
5689   // When default clang type checking is turned off and the customized type
5690   // checking is used, the returning type of the function must be explicitly
5691   // set. Otherwise it is _Bool by default.
5692   TheCall->setType(Arg1Ty);
5693 
5694   return false;
5695 }
5696 
5697 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
5698 // This is declared to take (...), so we have to check everything.
5699 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
5700   if (TheCall->getNumArgs() < 2)
5701     return ExprError(Diag(TheCall->getEndLoc(),
5702                           diag::err_typecheck_call_too_few_args_at_least)
5703                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5704                      << TheCall->getSourceRange());
5705 
5706   // Determine which of the following types of shufflevector we're checking:
5707   // 1) unary, vector mask: (lhs, mask)
5708   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
5709   QualType resType = TheCall->getArg(0)->getType();
5710   unsigned numElements = 0;
5711 
5712   if (!TheCall->getArg(0)->isTypeDependent() &&
5713       !TheCall->getArg(1)->isTypeDependent()) {
5714     QualType LHSType = TheCall->getArg(0)->getType();
5715     QualType RHSType = TheCall->getArg(1)->getType();
5716 
5717     if (!LHSType->isVectorType() || !RHSType->isVectorType())
5718       return ExprError(
5719           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
5720           << TheCall->getDirectCallee()
5721           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5722                          TheCall->getArg(1)->getEndLoc()));
5723 
5724     numElements = LHSType->castAs<VectorType>()->getNumElements();
5725     unsigned numResElements = TheCall->getNumArgs() - 2;
5726 
5727     // Check to see if we have a call with 2 vector arguments, the unary shuffle
5728     // with mask.  If so, verify that RHS is an integer vector type with the
5729     // same number of elts as lhs.
5730     if (TheCall->getNumArgs() == 2) {
5731       if (!RHSType->hasIntegerRepresentation() ||
5732           RHSType->castAs<VectorType>()->getNumElements() != numElements)
5733         return ExprError(Diag(TheCall->getBeginLoc(),
5734                               diag::err_vec_builtin_incompatible_vector)
5735                          << TheCall->getDirectCallee()
5736                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
5737                                         TheCall->getArg(1)->getEndLoc()));
5738     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
5739       return ExprError(Diag(TheCall->getBeginLoc(),
5740                             diag::err_vec_builtin_incompatible_vector)
5741                        << TheCall->getDirectCallee()
5742                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5743                                       TheCall->getArg(1)->getEndLoc()));
5744     } else if (numElements != numResElements) {
5745       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
5746       resType = Context.getVectorType(eltType, numResElements,
5747                                       VectorType::GenericVector);
5748     }
5749   }
5750 
5751   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
5752     if (TheCall->getArg(i)->isTypeDependent() ||
5753         TheCall->getArg(i)->isValueDependent())
5754       continue;
5755 
5756     llvm::APSInt Result(32);
5757     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
5758       return ExprError(Diag(TheCall->getBeginLoc(),
5759                             diag::err_shufflevector_nonconstant_argument)
5760                        << TheCall->getArg(i)->getSourceRange());
5761 
5762     // Allow -1 which will be translated to undef in the IR.
5763     if (Result.isSigned() && Result.isAllOnesValue())
5764       continue;
5765 
5766     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
5767       return ExprError(Diag(TheCall->getBeginLoc(),
5768                             diag::err_shufflevector_argument_too_large)
5769                        << TheCall->getArg(i)->getSourceRange());
5770   }
5771 
5772   SmallVector<Expr*, 32> exprs;
5773 
5774   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
5775     exprs.push_back(TheCall->getArg(i));
5776     TheCall->setArg(i, nullptr);
5777   }
5778 
5779   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
5780                                          TheCall->getCallee()->getBeginLoc(),
5781                                          TheCall->getRParenLoc());
5782 }
5783 
5784 /// SemaConvertVectorExpr - Handle __builtin_convertvector
5785 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
5786                                        SourceLocation BuiltinLoc,
5787                                        SourceLocation RParenLoc) {
5788   ExprValueKind VK = VK_RValue;
5789   ExprObjectKind OK = OK_Ordinary;
5790   QualType DstTy = TInfo->getType();
5791   QualType SrcTy = E->getType();
5792 
5793   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
5794     return ExprError(Diag(BuiltinLoc,
5795                           diag::err_convertvector_non_vector)
5796                      << E->getSourceRange());
5797   if (!DstTy->isVectorType() && !DstTy->isDependentType())
5798     return ExprError(Diag(BuiltinLoc,
5799                           diag::err_convertvector_non_vector_type));
5800 
5801   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
5802     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
5803     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
5804     if (SrcElts != DstElts)
5805       return ExprError(Diag(BuiltinLoc,
5806                             diag::err_convertvector_incompatible_vector)
5807                        << E->getSourceRange());
5808   }
5809 
5810   return new (Context)
5811       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5812 }
5813 
5814 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
5815 // This is declared to take (const void*, ...) and can take two
5816 // optional constant int args.
5817 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
5818   unsigned NumArgs = TheCall->getNumArgs();
5819 
5820   if (NumArgs > 3)
5821     return Diag(TheCall->getEndLoc(),
5822                 diag::err_typecheck_call_too_many_args_at_most)
5823            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
5824 
5825   // Argument 0 is checked for us and the remaining arguments must be
5826   // constant integers.
5827   for (unsigned i = 1; i != NumArgs; ++i)
5828     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
5829       return true;
5830 
5831   return false;
5832 }
5833 
5834 /// SemaBuiltinAssume - Handle __assume (MS Extension).
5835 // __assume does not evaluate its arguments, and should warn if its argument
5836 // has side effects.
5837 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
5838   Expr *Arg = TheCall->getArg(0);
5839   if (Arg->isInstantiationDependent()) return false;
5840 
5841   if (Arg->HasSideEffects(Context))
5842     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
5843         << Arg->getSourceRange()
5844         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
5845 
5846   return false;
5847 }
5848 
5849 /// Handle __builtin_alloca_with_align. This is declared
5850 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
5851 /// than 8.
5852 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
5853   // The alignment must be a constant integer.
5854   Expr *Arg = TheCall->getArg(1);
5855 
5856   // We can't check the value of a dependent argument.
5857   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5858     if (const auto *UE =
5859             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
5860       if (UE->getKind() == UETT_AlignOf ||
5861           UE->getKind() == UETT_PreferredAlignOf)
5862         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
5863             << Arg->getSourceRange();
5864 
5865     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
5866 
5867     if (!Result.isPowerOf2())
5868       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5869              << Arg->getSourceRange();
5870 
5871     if (Result < Context.getCharWidth())
5872       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
5873              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
5874 
5875     if (Result > std::numeric_limits<int32_t>::max())
5876       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
5877              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
5878   }
5879 
5880   return false;
5881 }
5882 
5883 /// Handle __builtin_assume_aligned. This is declared
5884 /// as (const void*, size_t, ...) and can take one optional constant int arg.
5885 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
5886   unsigned NumArgs = TheCall->getNumArgs();
5887 
5888   if (NumArgs > 3)
5889     return Diag(TheCall->getEndLoc(),
5890                 diag::err_typecheck_call_too_many_args_at_most)
5891            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
5892 
5893   // The alignment must be a constant integer.
5894   Expr *Arg = TheCall->getArg(1);
5895 
5896   // We can't check the value of a dependent argument.
5897   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5898     llvm::APSInt Result;
5899     if (SemaBuiltinConstantArg(TheCall, 1, Result))
5900       return true;
5901 
5902     if (!Result.isPowerOf2())
5903       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5904              << Arg->getSourceRange();
5905 
5906     if (Result > Sema::MaximumAlignment)
5907       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
5908           << Arg->getSourceRange() << Sema::MaximumAlignment;
5909   }
5910 
5911   if (NumArgs > 2) {
5912     ExprResult Arg(TheCall->getArg(2));
5913     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5914       Context.getSizeType(), false);
5915     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5916     if (Arg.isInvalid()) return true;
5917     TheCall->setArg(2, Arg.get());
5918   }
5919 
5920   return false;
5921 }
5922 
5923 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
5924   unsigned BuiltinID =
5925       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
5926   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
5927 
5928   unsigned NumArgs = TheCall->getNumArgs();
5929   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
5930   if (NumArgs < NumRequiredArgs) {
5931     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5932            << 0 /* function call */ << NumRequiredArgs << NumArgs
5933            << TheCall->getSourceRange();
5934   }
5935   if (NumArgs >= NumRequiredArgs + 0x100) {
5936     return Diag(TheCall->getEndLoc(),
5937                 diag::err_typecheck_call_too_many_args_at_most)
5938            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
5939            << TheCall->getSourceRange();
5940   }
5941   unsigned i = 0;
5942 
5943   // For formatting call, check buffer arg.
5944   if (!IsSizeCall) {
5945     ExprResult Arg(TheCall->getArg(i));
5946     InitializedEntity Entity = InitializedEntity::InitializeParameter(
5947         Context, Context.VoidPtrTy, false);
5948     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5949     if (Arg.isInvalid())
5950       return true;
5951     TheCall->setArg(i, Arg.get());
5952     i++;
5953   }
5954 
5955   // Check string literal arg.
5956   unsigned FormatIdx = i;
5957   {
5958     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
5959     if (Arg.isInvalid())
5960       return true;
5961     TheCall->setArg(i, Arg.get());
5962     i++;
5963   }
5964 
5965   // Make sure variadic args are scalar.
5966   unsigned FirstDataArg = i;
5967   while (i < NumArgs) {
5968     ExprResult Arg = DefaultVariadicArgumentPromotion(
5969         TheCall->getArg(i), VariadicFunction, nullptr);
5970     if (Arg.isInvalid())
5971       return true;
5972     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
5973     if (ArgSize.getQuantity() >= 0x100) {
5974       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
5975              << i << (int)ArgSize.getQuantity() << 0xff
5976              << TheCall->getSourceRange();
5977     }
5978     TheCall->setArg(i, Arg.get());
5979     i++;
5980   }
5981 
5982   // Check formatting specifiers. NOTE: We're only doing this for the non-size
5983   // call to avoid duplicate diagnostics.
5984   if (!IsSizeCall) {
5985     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
5986     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
5987     bool Success = CheckFormatArguments(
5988         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
5989         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
5990         CheckedVarArgs);
5991     if (!Success)
5992       return true;
5993   }
5994 
5995   if (IsSizeCall) {
5996     TheCall->setType(Context.getSizeType());
5997   } else {
5998     TheCall->setType(Context.VoidPtrTy);
5999   }
6000   return false;
6001 }
6002 
6003 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
6004 /// TheCall is a constant expression.
6005 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
6006                                   llvm::APSInt &Result) {
6007   Expr *Arg = TheCall->getArg(ArgNum);
6008   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6009   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6010 
6011   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
6012 
6013   if (!Arg->isIntegerConstantExpr(Result, Context))
6014     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6015            << FDecl->getDeclName() << Arg->getSourceRange();
6016 
6017   return false;
6018 }
6019 
6020 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
6021 /// TheCall is a constant expression in the range [Low, High].
6022 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
6023                                        int Low, int High, bool RangeIsError) {
6024   if (isConstantEvaluated())
6025     return false;
6026   llvm::APSInt Result;
6027 
6028   // We can't check the value of a dependent argument.
6029   Expr *Arg = TheCall->getArg(ArgNum);
6030   if (Arg->isTypeDependent() || Arg->isValueDependent())
6031     return false;
6032 
6033   // Check constant-ness first.
6034   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6035     return true;
6036 
6037   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6038     if (RangeIsError)
6039       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6040              << Result.toString(10) << Low << High << Arg->getSourceRange();
6041     else
6042       // Defer the warning until we know if the code will be emitted so that
6043       // dead code can ignore this.
6044       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6045                           PDiag(diag::warn_argument_invalid_range)
6046                               << Result.toString(10) << Low << High
6047                               << Arg->getSourceRange());
6048   }
6049 
6050   return false;
6051 }
6052 
6053 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
6054 /// TheCall is a constant expression is a multiple of Num..
6055 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
6056                                           unsigned Num) {
6057   llvm::APSInt Result;
6058 
6059   // We can't check the value of a dependent argument.
6060   Expr *Arg = TheCall->getArg(ArgNum);
6061   if (Arg->isTypeDependent() || Arg->isValueDependent())
6062     return false;
6063 
6064   // Check constant-ness first.
6065   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6066     return true;
6067 
6068   if (Result.getSExtValue() % Num != 0)
6069     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6070            << Num << Arg->getSourceRange();
6071 
6072   return false;
6073 }
6074 
6075 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
6076 /// constant expression representing a power of 2.
6077 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
6078   llvm::APSInt Result;
6079 
6080   // We can't check the value of a dependent argument.
6081   Expr *Arg = TheCall->getArg(ArgNum);
6082   if (Arg->isTypeDependent() || Arg->isValueDependent())
6083     return false;
6084 
6085   // Check constant-ness first.
6086   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6087     return true;
6088 
6089   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
6090   // and only if x is a power of 2.
6091   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
6092     return false;
6093 
6094   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
6095          << Arg->getSourceRange();
6096 }
6097 
6098 static bool IsShiftedByte(llvm::APSInt Value) {
6099   if (Value.isNegative())
6100     return false;
6101 
6102   // Check if it's a shifted byte, by shifting it down
6103   while (true) {
6104     // If the value fits in the bottom byte, the check passes.
6105     if (Value < 0x100)
6106       return true;
6107 
6108     // Otherwise, if the value has _any_ bits in the bottom byte, the check
6109     // fails.
6110     if ((Value & 0xFF) != 0)
6111       return false;
6112 
6113     // If the bottom 8 bits are all 0, but something above that is nonzero,
6114     // then shifting the value right by 8 bits won't affect whether it's a
6115     // shifted byte or not. So do that, and go round again.
6116     Value >>= 8;
6117   }
6118 }
6119 
6120 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
6121 /// a constant expression representing an arbitrary byte value shifted left by
6122 /// a multiple of 8 bits.
6123 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
6124                                              unsigned ArgBits) {
6125   llvm::APSInt Result;
6126 
6127   // We can't check the value of a dependent argument.
6128   Expr *Arg = TheCall->getArg(ArgNum);
6129   if (Arg->isTypeDependent() || Arg->isValueDependent())
6130     return false;
6131 
6132   // Check constant-ness first.
6133   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6134     return true;
6135 
6136   // Truncate to the given size.
6137   Result = Result.getLoBits(ArgBits);
6138   Result.setIsUnsigned(true);
6139 
6140   if (IsShiftedByte(Result))
6141     return false;
6142 
6143   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
6144          << Arg->getSourceRange();
6145 }
6146 
6147 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
6148 /// TheCall is a constant expression representing either a shifted byte value,
6149 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
6150 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
6151 /// Arm MVE intrinsics.
6152 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
6153                                                    int ArgNum,
6154                                                    unsigned ArgBits) {
6155   llvm::APSInt Result;
6156 
6157   // We can't check the value of a dependent argument.
6158   Expr *Arg = TheCall->getArg(ArgNum);
6159   if (Arg->isTypeDependent() || Arg->isValueDependent())
6160     return false;
6161 
6162   // Check constant-ness first.
6163   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6164     return true;
6165 
6166   // Truncate to the given size.
6167   Result = Result.getLoBits(ArgBits);
6168   Result.setIsUnsigned(true);
6169 
6170   // Check to see if it's in either of the required forms.
6171   if (IsShiftedByte(Result) ||
6172       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
6173     return false;
6174 
6175   return Diag(TheCall->getBeginLoc(),
6176               diag::err_argument_not_shifted_byte_or_xxff)
6177          << Arg->getSourceRange();
6178 }
6179 
6180 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
6181 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
6182   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
6183     if (checkArgCount(*this, TheCall, 2))
6184       return true;
6185     Expr *Arg0 = TheCall->getArg(0);
6186     Expr *Arg1 = TheCall->getArg(1);
6187 
6188     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6189     if (FirstArg.isInvalid())
6190       return true;
6191     QualType FirstArgType = FirstArg.get()->getType();
6192     if (!FirstArgType->isAnyPointerType())
6193       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6194                << "first" << FirstArgType << Arg0->getSourceRange();
6195     TheCall->setArg(0, FirstArg.get());
6196 
6197     ExprResult SecArg = DefaultLvalueConversion(Arg1);
6198     if (SecArg.isInvalid())
6199       return true;
6200     QualType SecArgType = SecArg.get()->getType();
6201     if (!SecArgType->isIntegerType())
6202       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6203                << "second" << SecArgType << Arg1->getSourceRange();
6204 
6205     // Derive the return type from the pointer argument.
6206     TheCall->setType(FirstArgType);
6207     return false;
6208   }
6209 
6210   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
6211     if (checkArgCount(*this, TheCall, 2))
6212       return true;
6213 
6214     Expr *Arg0 = TheCall->getArg(0);
6215     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6216     if (FirstArg.isInvalid())
6217       return true;
6218     QualType FirstArgType = FirstArg.get()->getType();
6219     if (!FirstArgType->isAnyPointerType())
6220       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6221                << "first" << FirstArgType << Arg0->getSourceRange();
6222     TheCall->setArg(0, FirstArg.get());
6223 
6224     // Derive the return type from the pointer argument.
6225     TheCall->setType(FirstArgType);
6226 
6227     // Second arg must be an constant in range [0,15]
6228     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6229   }
6230 
6231   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
6232     if (checkArgCount(*this, TheCall, 2))
6233       return true;
6234     Expr *Arg0 = TheCall->getArg(0);
6235     Expr *Arg1 = TheCall->getArg(1);
6236 
6237     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6238     if (FirstArg.isInvalid())
6239       return true;
6240     QualType FirstArgType = FirstArg.get()->getType();
6241     if (!FirstArgType->isAnyPointerType())
6242       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6243                << "first" << FirstArgType << Arg0->getSourceRange();
6244 
6245     QualType SecArgType = Arg1->getType();
6246     if (!SecArgType->isIntegerType())
6247       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6248                << "second" << SecArgType << Arg1->getSourceRange();
6249     TheCall->setType(Context.IntTy);
6250     return false;
6251   }
6252 
6253   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
6254       BuiltinID == AArch64::BI__builtin_arm_stg) {
6255     if (checkArgCount(*this, TheCall, 1))
6256       return true;
6257     Expr *Arg0 = TheCall->getArg(0);
6258     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6259     if (FirstArg.isInvalid())
6260       return true;
6261 
6262     QualType FirstArgType = FirstArg.get()->getType();
6263     if (!FirstArgType->isAnyPointerType())
6264       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6265                << "first" << FirstArgType << Arg0->getSourceRange();
6266     TheCall->setArg(0, FirstArg.get());
6267 
6268     // Derive the return type from the pointer argument.
6269     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
6270       TheCall->setType(FirstArgType);
6271     return false;
6272   }
6273 
6274   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
6275     Expr *ArgA = TheCall->getArg(0);
6276     Expr *ArgB = TheCall->getArg(1);
6277 
6278     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
6279     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
6280 
6281     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
6282       return true;
6283 
6284     QualType ArgTypeA = ArgExprA.get()->getType();
6285     QualType ArgTypeB = ArgExprB.get()->getType();
6286 
6287     auto isNull = [&] (Expr *E) -> bool {
6288       return E->isNullPointerConstant(
6289                         Context, Expr::NPC_ValueDependentIsNotNull); };
6290 
6291     // argument should be either a pointer or null
6292     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
6293       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6294         << "first" << ArgTypeA << ArgA->getSourceRange();
6295 
6296     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
6297       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6298         << "second" << ArgTypeB << ArgB->getSourceRange();
6299 
6300     // Ensure Pointee types are compatible
6301     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
6302         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
6303       QualType pointeeA = ArgTypeA->getPointeeType();
6304       QualType pointeeB = ArgTypeB->getPointeeType();
6305       if (!Context.typesAreCompatible(
6306              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
6307              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
6308         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
6309           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
6310           << ArgB->getSourceRange();
6311       }
6312     }
6313 
6314     // at least one argument should be pointer type
6315     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
6316       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
6317         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
6318 
6319     if (isNull(ArgA)) // adopt type of the other pointer
6320       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
6321 
6322     if (isNull(ArgB))
6323       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
6324 
6325     TheCall->setArg(0, ArgExprA.get());
6326     TheCall->setArg(1, ArgExprB.get());
6327     TheCall->setType(Context.LongLongTy);
6328     return false;
6329   }
6330   assert(false && "Unhandled ARM MTE intrinsic");
6331   return true;
6332 }
6333 
6334 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
6335 /// TheCall is an ARM/AArch64 special register string literal.
6336 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
6337                                     int ArgNum, unsigned ExpectedFieldNum,
6338                                     bool AllowName) {
6339   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
6340                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
6341                       BuiltinID == ARM::BI__builtin_arm_rsr ||
6342                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
6343                       BuiltinID == ARM::BI__builtin_arm_wsr ||
6344                       BuiltinID == ARM::BI__builtin_arm_wsrp;
6345   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
6346                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
6347                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
6348                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
6349                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
6350                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
6351   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
6352 
6353   // We can't check the value of a dependent argument.
6354   Expr *Arg = TheCall->getArg(ArgNum);
6355   if (Arg->isTypeDependent() || Arg->isValueDependent())
6356     return false;
6357 
6358   // Check if the argument is a string literal.
6359   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
6360     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
6361            << Arg->getSourceRange();
6362 
6363   // Check the type of special register given.
6364   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
6365   SmallVector<StringRef, 6> Fields;
6366   Reg.split(Fields, ":");
6367 
6368   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
6369     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6370            << Arg->getSourceRange();
6371 
6372   // If the string is the name of a register then we cannot check that it is
6373   // valid here but if the string is of one the forms described in ACLE then we
6374   // can check that the supplied fields are integers and within the valid
6375   // ranges.
6376   if (Fields.size() > 1) {
6377     bool FiveFields = Fields.size() == 5;
6378 
6379     bool ValidString = true;
6380     if (IsARMBuiltin) {
6381       ValidString &= Fields[0].startswith_lower("cp") ||
6382                      Fields[0].startswith_lower("p");
6383       if (ValidString)
6384         Fields[0] =
6385           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
6386 
6387       ValidString &= Fields[2].startswith_lower("c");
6388       if (ValidString)
6389         Fields[2] = Fields[2].drop_front(1);
6390 
6391       if (FiveFields) {
6392         ValidString &= Fields[3].startswith_lower("c");
6393         if (ValidString)
6394           Fields[3] = Fields[3].drop_front(1);
6395       }
6396     }
6397 
6398     SmallVector<int, 5> Ranges;
6399     if (FiveFields)
6400       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
6401     else
6402       Ranges.append({15, 7, 15});
6403 
6404     for (unsigned i=0; i<Fields.size(); ++i) {
6405       int IntField;
6406       ValidString &= !Fields[i].getAsInteger(10, IntField);
6407       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
6408     }
6409 
6410     if (!ValidString)
6411       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6412              << Arg->getSourceRange();
6413   } else if (IsAArch64Builtin && Fields.size() == 1) {
6414     // If the register name is one of those that appear in the condition below
6415     // and the special register builtin being used is one of the write builtins,
6416     // then we require that the argument provided for writing to the register
6417     // is an integer constant expression. This is because it will be lowered to
6418     // an MSR (immediate) instruction, so we need to know the immediate at
6419     // compile time.
6420     if (TheCall->getNumArgs() != 2)
6421       return false;
6422 
6423     std::string RegLower = Reg.lower();
6424     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
6425         RegLower != "pan" && RegLower != "uao")
6426       return false;
6427 
6428     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6429   }
6430 
6431   return false;
6432 }
6433 
6434 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
6435 /// This checks that the target supports __builtin_longjmp and
6436 /// that val is a constant 1.
6437 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
6438   if (!Context.getTargetInfo().hasSjLjLowering())
6439     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
6440            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6441 
6442   Expr *Arg = TheCall->getArg(1);
6443   llvm::APSInt Result;
6444 
6445   // TODO: This is less than ideal. Overload this to take a value.
6446   if (SemaBuiltinConstantArg(TheCall, 1, Result))
6447     return true;
6448 
6449   if (Result != 1)
6450     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
6451            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6452 
6453   return false;
6454 }
6455 
6456 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
6457 /// This checks that the target supports __builtin_setjmp.
6458 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
6459   if (!Context.getTargetInfo().hasSjLjLowering())
6460     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
6461            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6462   return false;
6463 }
6464 
6465 namespace {
6466 
6467 class UncoveredArgHandler {
6468   enum { Unknown = -1, AllCovered = -2 };
6469 
6470   signed FirstUncoveredArg = Unknown;
6471   SmallVector<const Expr *, 4> DiagnosticExprs;
6472 
6473 public:
6474   UncoveredArgHandler() = default;
6475 
6476   bool hasUncoveredArg() const {
6477     return (FirstUncoveredArg >= 0);
6478   }
6479 
6480   unsigned getUncoveredArg() const {
6481     assert(hasUncoveredArg() && "no uncovered argument");
6482     return FirstUncoveredArg;
6483   }
6484 
6485   void setAllCovered() {
6486     // A string has been found with all arguments covered, so clear out
6487     // the diagnostics.
6488     DiagnosticExprs.clear();
6489     FirstUncoveredArg = AllCovered;
6490   }
6491 
6492   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6493     assert(NewFirstUncoveredArg >= 0 && "Outside range");
6494 
6495     // Don't update if a previous string covers all arguments.
6496     if (FirstUncoveredArg == AllCovered)
6497       return;
6498 
6499     // UncoveredArgHandler tracks the highest uncovered argument index
6500     // and with it all the strings that match this index.
6501     if (NewFirstUncoveredArg == FirstUncoveredArg)
6502       DiagnosticExprs.push_back(StrExpr);
6503     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6504       DiagnosticExprs.clear();
6505       DiagnosticExprs.push_back(StrExpr);
6506       FirstUncoveredArg = NewFirstUncoveredArg;
6507     }
6508   }
6509 
6510   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6511 };
6512 
6513 enum StringLiteralCheckType {
6514   SLCT_NotALiteral,
6515   SLCT_UncheckedLiteral,
6516   SLCT_CheckedLiteral
6517 };
6518 
6519 } // namespace
6520 
6521 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6522                                      BinaryOperatorKind BinOpKind,
6523                                      bool AddendIsRight) {
6524   unsigned BitWidth = Offset.getBitWidth();
6525   unsigned AddendBitWidth = Addend.getBitWidth();
6526   // There might be negative interim results.
6527   if (Addend.isUnsigned()) {
6528     Addend = Addend.zext(++AddendBitWidth);
6529     Addend.setIsSigned(true);
6530   }
6531   // Adjust the bit width of the APSInts.
6532   if (AddendBitWidth > BitWidth) {
6533     Offset = Offset.sext(AddendBitWidth);
6534     BitWidth = AddendBitWidth;
6535   } else if (BitWidth > AddendBitWidth) {
6536     Addend = Addend.sext(BitWidth);
6537   }
6538 
6539   bool Ov = false;
6540   llvm::APSInt ResOffset = Offset;
6541   if (BinOpKind == BO_Add)
6542     ResOffset = Offset.sadd_ov(Addend, Ov);
6543   else {
6544     assert(AddendIsRight && BinOpKind == BO_Sub &&
6545            "operator must be add or sub with addend on the right");
6546     ResOffset = Offset.ssub_ov(Addend, Ov);
6547   }
6548 
6549   // We add an offset to a pointer here so we should support an offset as big as
6550   // possible.
6551   if (Ov) {
6552     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6553            "index (intermediate) result too big");
6554     Offset = Offset.sext(2 * BitWidth);
6555     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6556     return;
6557   }
6558 
6559   Offset = ResOffset;
6560 }
6561 
6562 namespace {
6563 
6564 // This is a wrapper class around StringLiteral to support offsetted string
6565 // literals as format strings. It takes the offset into account when returning
6566 // the string and its length or the source locations to display notes correctly.
6567 class FormatStringLiteral {
6568   const StringLiteral *FExpr;
6569   int64_t Offset;
6570 
6571  public:
6572   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
6573       : FExpr(fexpr), Offset(Offset) {}
6574 
6575   StringRef getString() const {
6576     return FExpr->getString().drop_front(Offset);
6577   }
6578 
6579   unsigned getByteLength() const {
6580     return FExpr->getByteLength() - getCharByteWidth() * Offset;
6581   }
6582 
6583   unsigned getLength() const { return FExpr->getLength() - Offset; }
6584   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
6585 
6586   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
6587 
6588   QualType getType() const { return FExpr->getType(); }
6589 
6590   bool isAscii() const { return FExpr->isAscii(); }
6591   bool isWide() const { return FExpr->isWide(); }
6592   bool isUTF8() const { return FExpr->isUTF8(); }
6593   bool isUTF16() const { return FExpr->isUTF16(); }
6594   bool isUTF32() const { return FExpr->isUTF32(); }
6595   bool isPascal() const { return FExpr->isPascal(); }
6596 
6597   SourceLocation getLocationOfByte(
6598       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
6599       const TargetInfo &Target, unsigned *StartToken = nullptr,
6600       unsigned *StartTokenByteOffset = nullptr) const {
6601     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
6602                                     StartToken, StartTokenByteOffset);
6603   }
6604 
6605   SourceLocation getBeginLoc() const LLVM_READONLY {
6606     return FExpr->getBeginLoc().getLocWithOffset(Offset);
6607   }
6608 
6609   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
6610 };
6611 
6612 }  // namespace
6613 
6614 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
6615                               const Expr *OrigFormatExpr,
6616                               ArrayRef<const Expr *> Args,
6617                               bool HasVAListArg, unsigned format_idx,
6618                               unsigned firstDataArg,
6619                               Sema::FormatStringType Type,
6620                               bool inFunctionCall,
6621                               Sema::VariadicCallType CallType,
6622                               llvm::SmallBitVector &CheckedVarArgs,
6623                               UncoveredArgHandler &UncoveredArg,
6624                               bool IgnoreStringsWithoutSpecifiers);
6625 
6626 // Determine if an expression is a string literal or constant string.
6627 // If this function returns false on the arguments to a function expecting a
6628 // format string, we will usually need to emit a warning.
6629 // True string literals are then checked by CheckFormatString.
6630 static StringLiteralCheckType
6631 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
6632                       bool HasVAListArg, unsigned format_idx,
6633                       unsigned firstDataArg, Sema::FormatStringType Type,
6634                       Sema::VariadicCallType CallType, bool InFunctionCall,
6635                       llvm::SmallBitVector &CheckedVarArgs,
6636                       UncoveredArgHandler &UncoveredArg,
6637                       llvm::APSInt Offset,
6638                       bool IgnoreStringsWithoutSpecifiers = false) {
6639   if (S.isConstantEvaluated())
6640     return SLCT_NotALiteral;
6641  tryAgain:
6642   assert(Offset.isSigned() && "invalid offset");
6643 
6644   if (E->isTypeDependent() || E->isValueDependent())
6645     return SLCT_NotALiteral;
6646 
6647   E = E->IgnoreParenCasts();
6648 
6649   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
6650     // Technically -Wformat-nonliteral does not warn about this case.
6651     // The behavior of printf and friends in this case is implementation
6652     // dependent.  Ideally if the format string cannot be null then
6653     // it should have a 'nonnull' attribute in the function prototype.
6654     return SLCT_UncheckedLiteral;
6655 
6656   switch (E->getStmtClass()) {
6657   case Stmt::BinaryConditionalOperatorClass:
6658   case Stmt::ConditionalOperatorClass: {
6659     // The expression is a literal if both sub-expressions were, and it was
6660     // completely checked only if both sub-expressions were checked.
6661     const AbstractConditionalOperator *C =
6662         cast<AbstractConditionalOperator>(E);
6663 
6664     // Determine whether it is necessary to check both sub-expressions, for
6665     // example, because the condition expression is a constant that can be
6666     // evaluated at compile time.
6667     bool CheckLeft = true, CheckRight = true;
6668 
6669     bool Cond;
6670     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
6671                                                  S.isConstantEvaluated())) {
6672       if (Cond)
6673         CheckRight = false;
6674       else
6675         CheckLeft = false;
6676     }
6677 
6678     // We need to maintain the offsets for the right and the left hand side
6679     // separately to check if every possible indexed expression is a valid
6680     // string literal. They might have different offsets for different string
6681     // literals in the end.
6682     StringLiteralCheckType Left;
6683     if (!CheckLeft)
6684       Left = SLCT_UncheckedLiteral;
6685     else {
6686       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
6687                                    HasVAListArg, format_idx, firstDataArg,
6688                                    Type, CallType, InFunctionCall,
6689                                    CheckedVarArgs, UncoveredArg, Offset,
6690                                    IgnoreStringsWithoutSpecifiers);
6691       if (Left == SLCT_NotALiteral || !CheckRight) {
6692         return Left;
6693       }
6694     }
6695 
6696     StringLiteralCheckType Right = checkFormatStringExpr(
6697         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
6698         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6699         IgnoreStringsWithoutSpecifiers);
6700 
6701     return (CheckLeft && Left < Right) ? Left : Right;
6702   }
6703 
6704   case Stmt::ImplicitCastExprClass:
6705     E = cast<ImplicitCastExpr>(E)->getSubExpr();
6706     goto tryAgain;
6707 
6708   case Stmt::OpaqueValueExprClass:
6709     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
6710       E = src;
6711       goto tryAgain;
6712     }
6713     return SLCT_NotALiteral;
6714 
6715   case Stmt::PredefinedExprClass:
6716     // While __func__, etc., are technically not string literals, they
6717     // cannot contain format specifiers and thus are not a security
6718     // liability.
6719     return SLCT_UncheckedLiteral;
6720 
6721   case Stmt::DeclRefExprClass: {
6722     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6723 
6724     // As an exception, do not flag errors for variables binding to
6725     // const string literals.
6726     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
6727       bool isConstant = false;
6728       QualType T = DR->getType();
6729 
6730       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
6731         isConstant = AT->getElementType().isConstant(S.Context);
6732       } else if (const PointerType *PT = T->getAs<PointerType>()) {
6733         isConstant = T.isConstant(S.Context) &&
6734                      PT->getPointeeType().isConstant(S.Context);
6735       } else if (T->isObjCObjectPointerType()) {
6736         // In ObjC, there is usually no "const ObjectPointer" type,
6737         // so don't check if the pointee type is constant.
6738         isConstant = T.isConstant(S.Context);
6739       }
6740 
6741       if (isConstant) {
6742         if (const Expr *Init = VD->getAnyInitializer()) {
6743           // Look through initializers like const char c[] = { "foo" }
6744           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
6745             if (InitList->isStringLiteralInit())
6746               Init = InitList->getInit(0)->IgnoreParenImpCasts();
6747           }
6748           return checkFormatStringExpr(S, Init, Args,
6749                                        HasVAListArg, format_idx,
6750                                        firstDataArg, Type, CallType,
6751                                        /*InFunctionCall*/ false, CheckedVarArgs,
6752                                        UncoveredArg, Offset);
6753         }
6754       }
6755 
6756       // For vprintf* functions (i.e., HasVAListArg==true), we add a
6757       // special check to see if the format string is a function parameter
6758       // of the function calling the printf function.  If the function
6759       // has an attribute indicating it is a printf-like function, then we
6760       // should suppress warnings concerning non-literals being used in a call
6761       // to a vprintf function.  For example:
6762       //
6763       // void
6764       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
6765       //      va_list ap;
6766       //      va_start(ap, fmt);
6767       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
6768       //      ...
6769       // }
6770       if (HasVAListArg) {
6771         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
6772           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
6773             int PVIndex = PV->getFunctionScopeIndex() + 1;
6774             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
6775               // adjust for implicit parameter
6776               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6777                 if (MD->isInstance())
6778                   ++PVIndex;
6779               // We also check if the formats are compatible.
6780               // We can't pass a 'scanf' string to a 'printf' function.
6781               if (PVIndex == PVFormat->getFormatIdx() &&
6782                   Type == S.GetFormatStringType(PVFormat))
6783                 return SLCT_UncheckedLiteral;
6784             }
6785           }
6786         }
6787       }
6788     }
6789 
6790     return SLCT_NotALiteral;
6791   }
6792 
6793   case Stmt::CallExprClass:
6794   case Stmt::CXXMemberCallExprClass: {
6795     const CallExpr *CE = cast<CallExpr>(E);
6796     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
6797       bool IsFirst = true;
6798       StringLiteralCheckType CommonResult;
6799       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
6800         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
6801         StringLiteralCheckType Result = checkFormatStringExpr(
6802             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6803             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6804             IgnoreStringsWithoutSpecifiers);
6805         if (IsFirst) {
6806           CommonResult = Result;
6807           IsFirst = false;
6808         }
6809       }
6810       if (!IsFirst)
6811         return CommonResult;
6812 
6813       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
6814         unsigned BuiltinID = FD->getBuiltinID();
6815         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
6816             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
6817           const Expr *Arg = CE->getArg(0);
6818           return checkFormatStringExpr(S, Arg, Args,
6819                                        HasVAListArg, format_idx,
6820                                        firstDataArg, Type, CallType,
6821                                        InFunctionCall, CheckedVarArgs,
6822                                        UncoveredArg, Offset,
6823                                        IgnoreStringsWithoutSpecifiers);
6824         }
6825       }
6826     }
6827 
6828     return SLCT_NotALiteral;
6829   }
6830   case Stmt::ObjCMessageExprClass: {
6831     const auto *ME = cast<ObjCMessageExpr>(E);
6832     if (const auto *MD = ME->getMethodDecl()) {
6833       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
6834         // As a special case heuristic, if we're using the method -[NSBundle
6835         // localizedStringForKey:value:table:], ignore any key strings that lack
6836         // format specifiers. The idea is that if the key doesn't have any
6837         // format specifiers then its probably just a key to map to the
6838         // localized strings. If it does have format specifiers though, then its
6839         // likely that the text of the key is the format string in the
6840         // programmer's language, and should be checked.
6841         const ObjCInterfaceDecl *IFace;
6842         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
6843             IFace->getIdentifier()->isStr("NSBundle") &&
6844             MD->getSelector().isKeywordSelector(
6845                 {"localizedStringForKey", "value", "table"})) {
6846           IgnoreStringsWithoutSpecifiers = true;
6847         }
6848 
6849         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
6850         return checkFormatStringExpr(
6851             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6852             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6853             IgnoreStringsWithoutSpecifiers);
6854       }
6855     }
6856 
6857     return SLCT_NotALiteral;
6858   }
6859   case Stmt::ObjCStringLiteralClass:
6860   case Stmt::StringLiteralClass: {
6861     const StringLiteral *StrE = nullptr;
6862 
6863     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
6864       StrE = ObjCFExpr->getString();
6865     else
6866       StrE = cast<StringLiteral>(E);
6867 
6868     if (StrE) {
6869       if (Offset.isNegative() || Offset > StrE->getLength()) {
6870         // TODO: It would be better to have an explicit warning for out of
6871         // bounds literals.
6872         return SLCT_NotALiteral;
6873       }
6874       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
6875       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
6876                         firstDataArg, Type, InFunctionCall, CallType,
6877                         CheckedVarArgs, UncoveredArg,
6878                         IgnoreStringsWithoutSpecifiers);
6879       return SLCT_CheckedLiteral;
6880     }
6881 
6882     return SLCT_NotALiteral;
6883   }
6884   case Stmt::BinaryOperatorClass: {
6885     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
6886 
6887     // A string literal + an int offset is still a string literal.
6888     if (BinOp->isAdditiveOp()) {
6889       Expr::EvalResult LResult, RResult;
6890 
6891       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
6892           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
6893       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
6894           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
6895 
6896       if (LIsInt != RIsInt) {
6897         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
6898 
6899         if (LIsInt) {
6900           if (BinOpKind == BO_Add) {
6901             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
6902             E = BinOp->getRHS();
6903             goto tryAgain;
6904           }
6905         } else {
6906           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
6907           E = BinOp->getLHS();
6908           goto tryAgain;
6909         }
6910       }
6911     }
6912 
6913     return SLCT_NotALiteral;
6914   }
6915   case Stmt::UnaryOperatorClass: {
6916     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
6917     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
6918     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
6919       Expr::EvalResult IndexResult;
6920       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
6921                                        Expr::SE_NoSideEffects,
6922                                        S.isConstantEvaluated())) {
6923         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
6924                    /*RHS is int*/ true);
6925         E = ASE->getBase();
6926         goto tryAgain;
6927       }
6928     }
6929 
6930     return SLCT_NotALiteral;
6931   }
6932 
6933   default:
6934     return SLCT_NotALiteral;
6935   }
6936 }
6937 
6938 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
6939   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
6940       .Case("scanf", FST_Scanf)
6941       .Cases("printf", "printf0", FST_Printf)
6942       .Cases("NSString", "CFString", FST_NSString)
6943       .Case("strftime", FST_Strftime)
6944       .Case("strfmon", FST_Strfmon)
6945       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
6946       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
6947       .Case("os_trace", FST_OSLog)
6948       .Case("os_log", FST_OSLog)
6949       .Default(FST_Unknown);
6950 }
6951 
6952 /// CheckFormatArguments - Check calls to printf and scanf (and similar
6953 /// functions) for correct use of format strings.
6954 /// Returns true if a format string has been fully checked.
6955 bool Sema::CheckFormatArguments(const FormatAttr *Format,
6956                                 ArrayRef<const Expr *> Args,
6957                                 bool IsCXXMember,
6958                                 VariadicCallType CallType,
6959                                 SourceLocation Loc, SourceRange Range,
6960                                 llvm::SmallBitVector &CheckedVarArgs) {
6961   FormatStringInfo FSI;
6962   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
6963     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
6964                                 FSI.FirstDataArg, GetFormatStringType(Format),
6965                                 CallType, Loc, Range, CheckedVarArgs);
6966   return false;
6967 }
6968 
6969 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
6970                                 bool HasVAListArg, unsigned format_idx,
6971                                 unsigned firstDataArg, FormatStringType Type,
6972                                 VariadicCallType CallType,
6973                                 SourceLocation Loc, SourceRange Range,
6974                                 llvm::SmallBitVector &CheckedVarArgs) {
6975   // CHECK: printf/scanf-like function is called with no format string.
6976   if (format_idx >= Args.size()) {
6977     Diag(Loc, diag::warn_missing_format_string) << Range;
6978     return false;
6979   }
6980 
6981   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
6982 
6983   // CHECK: format string is not a string literal.
6984   //
6985   // Dynamically generated format strings are difficult to
6986   // automatically vet at compile time.  Requiring that format strings
6987   // are string literals: (1) permits the checking of format strings by
6988   // the compiler and thereby (2) can practically remove the source of
6989   // many format string exploits.
6990 
6991   // Format string can be either ObjC string (e.g. @"%d") or
6992   // C string (e.g. "%d")
6993   // ObjC string uses the same format specifiers as C string, so we can use
6994   // the same format string checking logic for both ObjC and C strings.
6995   UncoveredArgHandler UncoveredArg;
6996   StringLiteralCheckType CT =
6997       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
6998                             format_idx, firstDataArg, Type, CallType,
6999                             /*IsFunctionCall*/ true, CheckedVarArgs,
7000                             UncoveredArg,
7001                             /*no string offset*/ llvm::APSInt(64, false) = 0);
7002 
7003   // Generate a diagnostic where an uncovered argument is detected.
7004   if (UncoveredArg.hasUncoveredArg()) {
7005     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
7006     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
7007     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
7008   }
7009 
7010   if (CT != SLCT_NotALiteral)
7011     // Literal format string found, check done!
7012     return CT == SLCT_CheckedLiteral;
7013 
7014   // Strftime is particular as it always uses a single 'time' argument,
7015   // so it is safe to pass a non-literal string.
7016   if (Type == FST_Strftime)
7017     return false;
7018 
7019   // Do not emit diag when the string param is a macro expansion and the
7020   // format is either NSString or CFString. This is a hack to prevent
7021   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
7022   // which are usually used in place of NS and CF string literals.
7023   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
7024   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
7025     return false;
7026 
7027   // If there are no arguments specified, warn with -Wformat-security, otherwise
7028   // warn only with -Wformat-nonliteral.
7029   if (Args.size() == firstDataArg) {
7030     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
7031       << OrigFormatExpr->getSourceRange();
7032     switch (Type) {
7033     default:
7034       break;
7035     case FST_Kprintf:
7036     case FST_FreeBSDKPrintf:
7037     case FST_Printf:
7038       Diag(FormatLoc, diag::note_format_security_fixit)
7039         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
7040       break;
7041     case FST_NSString:
7042       Diag(FormatLoc, diag::note_format_security_fixit)
7043         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
7044       break;
7045     }
7046   } else {
7047     Diag(FormatLoc, diag::warn_format_nonliteral)
7048       << OrigFormatExpr->getSourceRange();
7049   }
7050   return false;
7051 }
7052 
7053 namespace {
7054 
7055 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7056 protected:
7057   Sema &S;
7058   const FormatStringLiteral *FExpr;
7059   const Expr *OrigFormatExpr;
7060   const Sema::FormatStringType FSType;
7061   const unsigned FirstDataArg;
7062   const unsigned NumDataArgs;
7063   const char *Beg; // Start of format string.
7064   const bool HasVAListArg;
7065   ArrayRef<const Expr *> Args;
7066   unsigned FormatIdx;
7067   llvm::SmallBitVector CoveredArgs;
7068   bool usesPositionalArgs = false;
7069   bool atFirstArg = true;
7070   bool inFunctionCall;
7071   Sema::VariadicCallType CallType;
7072   llvm::SmallBitVector &CheckedVarArgs;
7073   UncoveredArgHandler &UncoveredArg;
7074 
7075 public:
7076   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
7077                      const Expr *origFormatExpr,
7078                      const Sema::FormatStringType type, unsigned firstDataArg,
7079                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
7080                      ArrayRef<const Expr *> Args, unsigned formatIdx,
7081                      bool inFunctionCall, Sema::VariadicCallType callType,
7082                      llvm::SmallBitVector &CheckedVarArgs,
7083                      UncoveredArgHandler &UncoveredArg)
7084       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7085         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7086         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
7087         inFunctionCall(inFunctionCall), CallType(callType),
7088         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
7089     CoveredArgs.resize(numDataArgs);
7090     CoveredArgs.reset();
7091   }
7092 
7093   void DoneProcessing();
7094 
7095   void HandleIncompleteSpecifier(const char *startSpecifier,
7096                                  unsigned specifierLen) override;
7097 
7098   void HandleInvalidLengthModifier(
7099                            const analyze_format_string::FormatSpecifier &FS,
7100                            const analyze_format_string::ConversionSpecifier &CS,
7101                            const char *startSpecifier, unsigned specifierLen,
7102                            unsigned DiagID);
7103 
7104   void HandleNonStandardLengthModifier(
7105                     const analyze_format_string::FormatSpecifier &FS,
7106                     const char *startSpecifier, unsigned specifierLen);
7107 
7108   void HandleNonStandardConversionSpecifier(
7109                     const analyze_format_string::ConversionSpecifier &CS,
7110                     const char *startSpecifier, unsigned specifierLen);
7111 
7112   void HandlePosition(const char *startPos, unsigned posLen) override;
7113 
7114   void HandleInvalidPosition(const char *startSpecifier,
7115                              unsigned specifierLen,
7116                              analyze_format_string::PositionContext p) override;
7117 
7118   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
7119 
7120   void HandleNullChar(const char *nullCharacter) override;
7121 
7122   template <typename Range>
7123   static void
7124   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
7125                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
7126                        bool IsStringLocation, Range StringRange,
7127                        ArrayRef<FixItHint> Fixit = None);
7128 
7129 protected:
7130   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
7131                                         const char *startSpec,
7132                                         unsigned specifierLen,
7133                                         const char *csStart, unsigned csLen);
7134 
7135   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7136                                          const char *startSpec,
7137                                          unsigned specifierLen);
7138 
7139   SourceRange getFormatStringRange();
7140   CharSourceRange getSpecifierRange(const char *startSpecifier,
7141                                     unsigned specifierLen);
7142   SourceLocation getLocationOfByte(const char *x);
7143 
7144   const Expr *getDataArg(unsigned i) const;
7145 
7146   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7147                     const analyze_format_string::ConversionSpecifier &CS,
7148                     const char *startSpecifier, unsigned specifierLen,
7149                     unsigned argIndex);
7150 
7151   template <typename Range>
7152   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7153                             bool IsStringLocation, Range StringRange,
7154                             ArrayRef<FixItHint> Fixit = None);
7155 };
7156 
7157 } // namespace
7158 
7159 SourceRange CheckFormatHandler::getFormatStringRange() {
7160   return OrigFormatExpr->getSourceRange();
7161 }
7162 
7163 CharSourceRange CheckFormatHandler::
7164 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
7165   SourceLocation Start = getLocationOfByte(startSpecifier);
7166   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
7167 
7168   // Advance the end SourceLocation by one due to half-open ranges.
7169   End = End.getLocWithOffset(1);
7170 
7171   return CharSourceRange::getCharRange(Start, End);
7172 }
7173 
7174 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
7175   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
7176                                   S.getLangOpts(), S.Context.getTargetInfo());
7177 }
7178 
7179 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7180                                                    unsigned specifierLen){
7181   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
7182                        getLocationOfByte(startSpecifier),
7183                        /*IsStringLocation*/true,
7184                        getSpecifierRange(startSpecifier, specifierLen));
7185 }
7186 
7187 void CheckFormatHandler::HandleInvalidLengthModifier(
7188     const analyze_format_string::FormatSpecifier &FS,
7189     const analyze_format_string::ConversionSpecifier &CS,
7190     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
7191   using namespace analyze_format_string;
7192 
7193   const LengthModifier &LM = FS.getLengthModifier();
7194   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7195 
7196   // See if we know how to fix this length modifier.
7197   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7198   if (FixedLM) {
7199     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7200                          getLocationOfByte(LM.getStart()),
7201                          /*IsStringLocation*/true,
7202                          getSpecifierRange(startSpecifier, specifierLen));
7203 
7204     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7205       << FixedLM->toString()
7206       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7207 
7208   } else {
7209     FixItHint Hint;
7210     if (DiagID == diag::warn_format_nonsensical_length)
7211       Hint = FixItHint::CreateRemoval(LMRange);
7212 
7213     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7214                          getLocationOfByte(LM.getStart()),
7215                          /*IsStringLocation*/true,
7216                          getSpecifierRange(startSpecifier, specifierLen),
7217                          Hint);
7218   }
7219 }
7220 
7221 void CheckFormatHandler::HandleNonStandardLengthModifier(
7222     const analyze_format_string::FormatSpecifier &FS,
7223     const char *startSpecifier, unsigned specifierLen) {
7224   using namespace analyze_format_string;
7225 
7226   const LengthModifier &LM = FS.getLengthModifier();
7227   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7228 
7229   // See if we know how to fix this length modifier.
7230   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7231   if (FixedLM) {
7232     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7233                            << LM.toString() << 0,
7234                          getLocationOfByte(LM.getStart()),
7235                          /*IsStringLocation*/true,
7236                          getSpecifierRange(startSpecifier, specifierLen));
7237 
7238     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7239       << FixedLM->toString()
7240       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7241 
7242   } else {
7243     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7244                            << LM.toString() << 0,
7245                          getLocationOfByte(LM.getStart()),
7246                          /*IsStringLocation*/true,
7247                          getSpecifierRange(startSpecifier, specifierLen));
7248   }
7249 }
7250 
7251 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
7252     const analyze_format_string::ConversionSpecifier &CS,
7253     const char *startSpecifier, unsigned specifierLen) {
7254   using namespace analyze_format_string;
7255 
7256   // See if we know how to fix this conversion specifier.
7257   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
7258   if (FixedCS) {
7259     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7260                           << CS.toString() << /*conversion specifier*/1,
7261                          getLocationOfByte(CS.getStart()),
7262                          /*IsStringLocation*/true,
7263                          getSpecifierRange(startSpecifier, specifierLen));
7264 
7265     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
7266     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
7267       << FixedCS->toString()
7268       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
7269   } else {
7270     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7271                           << CS.toString() << /*conversion specifier*/1,
7272                          getLocationOfByte(CS.getStart()),
7273                          /*IsStringLocation*/true,
7274                          getSpecifierRange(startSpecifier, specifierLen));
7275   }
7276 }
7277 
7278 void CheckFormatHandler::HandlePosition(const char *startPos,
7279                                         unsigned posLen) {
7280   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
7281                                getLocationOfByte(startPos),
7282                                /*IsStringLocation*/true,
7283                                getSpecifierRange(startPos, posLen));
7284 }
7285 
7286 void
7287 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
7288                                      analyze_format_string::PositionContext p) {
7289   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
7290                          << (unsigned) p,
7291                        getLocationOfByte(startPos), /*IsStringLocation*/true,
7292                        getSpecifierRange(startPos, posLen));
7293 }
7294 
7295 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
7296                                             unsigned posLen) {
7297   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
7298                                getLocationOfByte(startPos),
7299                                /*IsStringLocation*/true,
7300                                getSpecifierRange(startPos, posLen));
7301 }
7302 
7303 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
7304   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
7305     // The presence of a null character is likely an error.
7306     EmitFormatDiagnostic(
7307       S.PDiag(diag::warn_printf_format_string_contains_null_char),
7308       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
7309       getFormatStringRange());
7310   }
7311 }
7312 
7313 // Note that this may return NULL if there was an error parsing or building
7314 // one of the argument expressions.
7315 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
7316   return Args[FirstDataArg + i];
7317 }
7318 
7319 void CheckFormatHandler::DoneProcessing() {
7320   // Does the number of data arguments exceed the number of
7321   // format conversions in the format string?
7322   if (!HasVAListArg) {
7323       // Find any arguments that weren't covered.
7324     CoveredArgs.flip();
7325     signed notCoveredArg = CoveredArgs.find_first();
7326     if (notCoveredArg >= 0) {
7327       assert((unsigned)notCoveredArg < NumDataArgs);
7328       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
7329     } else {
7330       UncoveredArg.setAllCovered();
7331     }
7332   }
7333 }
7334 
7335 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7336                                    const Expr *ArgExpr) {
7337   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
7338          "Invalid state");
7339 
7340   if (!ArgExpr)
7341     return;
7342 
7343   SourceLocation Loc = ArgExpr->getBeginLoc();
7344 
7345   if (S.getSourceManager().isInSystemMacro(Loc))
7346     return;
7347 
7348   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
7349   for (auto E : DiagnosticExprs)
7350     PDiag << E->getSourceRange();
7351 
7352   CheckFormatHandler::EmitFormatDiagnostic(
7353                                   S, IsFunctionCall, DiagnosticExprs[0],
7354                                   PDiag, Loc, /*IsStringLocation*/false,
7355                                   DiagnosticExprs[0]->getSourceRange());
7356 }
7357 
7358 bool
7359 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7360                                                      SourceLocation Loc,
7361                                                      const char *startSpec,
7362                                                      unsigned specifierLen,
7363                                                      const char *csStart,
7364                                                      unsigned csLen) {
7365   bool keepGoing = true;
7366   if (argIndex < NumDataArgs) {
7367     // Consider the argument coverered, even though the specifier doesn't
7368     // make sense.
7369     CoveredArgs.set(argIndex);
7370   }
7371   else {
7372     // If argIndex exceeds the number of data arguments we
7373     // don't issue a warning because that is just a cascade of warnings (and
7374     // they may have intended '%%' anyway). We don't want to continue processing
7375     // the format string after this point, however, as we will like just get
7376     // gibberish when trying to match arguments.
7377     keepGoing = false;
7378   }
7379 
7380   StringRef Specifier(csStart, csLen);
7381 
7382   // If the specifier in non-printable, it could be the first byte of a UTF-8
7383   // sequence. In that case, print the UTF-8 code point. If not, print the byte
7384   // hex value.
7385   std::string CodePointStr;
7386   if (!llvm::sys::locale::isPrint(*csStart)) {
7387     llvm::UTF32 CodePoint;
7388     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7389     const llvm::UTF8 *E =
7390         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7391     llvm::ConversionResult Result =
7392         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
7393 
7394     if (Result != llvm::conversionOK) {
7395       unsigned char FirstChar = *csStart;
7396       CodePoint = (llvm::UTF32)FirstChar;
7397     }
7398 
7399     llvm::raw_string_ostream OS(CodePointStr);
7400     if (CodePoint < 256)
7401       OS << "\\x" << llvm::format("%02x", CodePoint);
7402     else if (CodePoint <= 0xFFFF)
7403       OS << "\\u" << llvm::format("%04x", CodePoint);
7404     else
7405       OS << "\\U" << llvm::format("%08x", CodePoint);
7406     OS.flush();
7407     Specifier = CodePointStr;
7408   }
7409 
7410   EmitFormatDiagnostic(
7411       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
7412       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
7413 
7414   return keepGoing;
7415 }
7416 
7417 void
7418 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7419                                                       const char *startSpec,
7420                                                       unsigned specifierLen) {
7421   EmitFormatDiagnostic(
7422     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
7423     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
7424 }
7425 
7426 bool
7427 CheckFormatHandler::CheckNumArgs(
7428   const analyze_format_string::FormatSpecifier &FS,
7429   const analyze_format_string::ConversionSpecifier &CS,
7430   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7431 
7432   if (argIndex >= NumDataArgs) {
7433     PartialDiagnostic PDiag = FS.usesPositionalArg()
7434       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
7435            << (argIndex+1) << NumDataArgs)
7436       : S.PDiag(diag::warn_printf_insufficient_data_args);
7437     EmitFormatDiagnostic(
7438       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
7439       getSpecifierRange(startSpecifier, specifierLen));
7440 
7441     // Since more arguments than conversion tokens are given, by extension
7442     // all arguments are covered, so mark this as so.
7443     UncoveredArg.setAllCovered();
7444     return false;
7445   }
7446   return true;
7447 }
7448 
7449 template<typename Range>
7450 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
7451                                               SourceLocation Loc,
7452                                               bool IsStringLocation,
7453                                               Range StringRange,
7454                                               ArrayRef<FixItHint> FixIt) {
7455   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
7456                        Loc, IsStringLocation, StringRange, FixIt);
7457 }
7458 
7459 /// If the format string is not within the function call, emit a note
7460 /// so that the function call and string are in diagnostic messages.
7461 ///
7462 /// \param InFunctionCall if true, the format string is within the function
7463 /// call and only one diagnostic message will be produced.  Otherwise, an
7464 /// extra note will be emitted pointing to location of the format string.
7465 ///
7466 /// \param ArgumentExpr the expression that is passed as the format string
7467 /// argument in the function call.  Used for getting locations when two
7468 /// diagnostics are emitted.
7469 ///
7470 /// \param PDiag the callee should already have provided any strings for the
7471 /// diagnostic message.  This function only adds locations and fixits
7472 /// to diagnostics.
7473 ///
7474 /// \param Loc primary location for diagnostic.  If two diagnostics are
7475 /// required, one will be at Loc and a new SourceLocation will be created for
7476 /// the other one.
7477 ///
7478 /// \param IsStringLocation if true, Loc points to the format string should be
7479 /// used for the note.  Otherwise, Loc points to the argument list and will
7480 /// be used with PDiag.
7481 ///
7482 /// \param StringRange some or all of the string to highlight.  This is
7483 /// templated so it can accept either a CharSourceRange or a SourceRange.
7484 ///
7485 /// \param FixIt optional fix it hint for the format string.
7486 template <typename Range>
7487 void CheckFormatHandler::EmitFormatDiagnostic(
7488     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
7489     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
7490     Range StringRange, ArrayRef<FixItHint> FixIt) {
7491   if (InFunctionCall) {
7492     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
7493     D << StringRange;
7494     D << FixIt;
7495   } else {
7496     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
7497       << ArgumentExpr->getSourceRange();
7498 
7499     const Sema::SemaDiagnosticBuilder &Note =
7500       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
7501              diag::note_format_string_defined);
7502 
7503     Note << StringRange;
7504     Note << FixIt;
7505   }
7506 }
7507 
7508 //===--- CHECK: Printf format string checking ------------------------------===//
7509 
7510 namespace {
7511 
7512 class CheckPrintfHandler : public CheckFormatHandler {
7513 public:
7514   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7515                      const Expr *origFormatExpr,
7516                      const Sema::FormatStringType type, unsigned firstDataArg,
7517                      unsigned numDataArgs, bool isObjC, const char *beg,
7518                      bool hasVAListArg, ArrayRef<const Expr *> Args,
7519                      unsigned formatIdx, bool inFunctionCall,
7520                      Sema::VariadicCallType CallType,
7521                      llvm::SmallBitVector &CheckedVarArgs,
7522                      UncoveredArgHandler &UncoveredArg)
7523       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7524                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
7525                            inFunctionCall, CallType, CheckedVarArgs,
7526                            UncoveredArg) {}
7527 
7528   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
7529 
7530   /// Returns true if '%@' specifiers are allowed in the format string.
7531   bool allowsObjCArg() const {
7532     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
7533            FSType == Sema::FST_OSTrace;
7534   }
7535 
7536   bool HandleInvalidPrintfConversionSpecifier(
7537                                       const analyze_printf::PrintfSpecifier &FS,
7538                                       const char *startSpecifier,
7539                                       unsigned specifierLen) override;
7540 
7541   void handleInvalidMaskType(StringRef MaskType) override;
7542 
7543   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7544                              const char *startSpecifier,
7545                              unsigned specifierLen) override;
7546   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7547                        const char *StartSpecifier,
7548                        unsigned SpecifierLen,
7549                        const Expr *E);
7550 
7551   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
7552                     const char *startSpecifier, unsigned specifierLen);
7553   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
7554                            const analyze_printf::OptionalAmount &Amt,
7555                            unsigned type,
7556                            const char *startSpecifier, unsigned specifierLen);
7557   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7558                   const analyze_printf::OptionalFlag &flag,
7559                   const char *startSpecifier, unsigned specifierLen);
7560   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
7561                          const analyze_printf::OptionalFlag &ignoredFlag,
7562                          const analyze_printf::OptionalFlag &flag,
7563                          const char *startSpecifier, unsigned specifierLen);
7564   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
7565                            const Expr *E);
7566 
7567   void HandleEmptyObjCModifierFlag(const char *startFlag,
7568                                    unsigned flagLen) override;
7569 
7570   void HandleInvalidObjCModifierFlag(const char *startFlag,
7571                                             unsigned flagLen) override;
7572 
7573   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
7574                                            const char *flagsEnd,
7575                                            const char *conversionPosition)
7576                                              override;
7577 };
7578 
7579 } // namespace
7580 
7581 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
7582                                       const analyze_printf::PrintfSpecifier &FS,
7583                                       const char *startSpecifier,
7584                                       unsigned specifierLen) {
7585   const analyze_printf::PrintfConversionSpecifier &CS =
7586     FS.getConversionSpecifier();
7587 
7588   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7589                                           getLocationOfByte(CS.getStart()),
7590                                           startSpecifier, specifierLen,
7591                                           CS.getStart(), CS.getLength());
7592 }
7593 
7594 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
7595   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
7596 }
7597 
7598 bool CheckPrintfHandler::HandleAmount(
7599                                const analyze_format_string::OptionalAmount &Amt,
7600                                unsigned k, const char *startSpecifier,
7601                                unsigned specifierLen) {
7602   if (Amt.hasDataArgument()) {
7603     if (!HasVAListArg) {
7604       unsigned argIndex = Amt.getArgIndex();
7605       if (argIndex >= NumDataArgs) {
7606         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
7607                                << k,
7608                              getLocationOfByte(Amt.getStart()),
7609                              /*IsStringLocation*/true,
7610                              getSpecifierRange(startSpecifier, specifierLen));
7611         // Don't do any more checking.  We will just emit
7612         // spurious errors.
7613         return false;
7614       }
7615 
7616       // Type check the data argument.  It should be an 'int'.
7617       // Although not in conformance with C99, we also allow the argument to be
7618       // an 'unsigned int' as that is a reasonably safe case.  GCC also
7619       // doesn't emit a warning for that case.
7620       CoveredArgs.set(argIndex);
7621       const Expr *Arg = getDataArg(argIndex);
7622       if (!Arg)
7623         return false;
7624 
7625       QualType T = Arg->getType();
7626 
7627       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
7628       assert(AT.isValid());
7629 
7630       if (!AT.matchesType(S.Context, T)) {
7631         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
7632                                << k << AT.getRepresentativeTypeName(S.Context)
7633                                << T << Arg->getSourceRange(),
7634                              getLocationOfByte(Amt.getStart()),
7635                              /*IsStringLocation*/true,
7636                              getSpecifierRange(startSpecifier, specifierLen));
7637         // Don't do any more checking.  We will just emit
7638         // spurious errors.
7639         return false;
7640       }
7641     }
7642   }
7643   return true;
7644 }
7645 
7646 void CheckPrintfHandler::HandleInvalidAmount(
7647                                       const analyze_printf::PrintfSpecifier &FS,
7648                                       const analyze_printf::OptionalAmount &Amt,
7649                                       unsigned type,
7650                                       const char *startSpecifier,
7651                                       unsigned specifierLen) {
7652   const analyze_printf::PrintfConversionSpecifier &CS =
7653     FS.getConversionSpecifier();
7654 
7655   FixItHint fixit =
7656     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
7657       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
7658                                  Amt.getConstantLength()))
7659       : FixItHint();
7660 
7661   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
7662                          << type << CS.toString(),
7663                        getLocationOfByte(Amt.getStart()),
7664                        /*IsStringLocation*/true,
7665                        getSpecifierRange(startSpecifier, specifierLen),
7666                        fixit);
7667 }
7668 
7669 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7670                                     const analyze_printf::OptionalFlag &flag,
7671                                     const char *startSpecifier,
7672                                     unsigned specifierLen) {
7673   // Warn about pointless flag with a fixit removal.
7674   const analyze_printf::PrintfConversionSpecifier &CS =
7675     FS.getConversionSpecifier();
7676   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
7677                          << flag.toString() << CS.toString(),
7678                        getLocationOfByte(flag.getPosition()),
7679                        /*IsStringLocation*/true,
7680                        getSpecifierRange(startSpecifier, specifierLen),
7681                        FixItHint::CreateRemoval(
7682                          getSpecifierRange(flag.getPosition(), 1)));
7683 }
7684 
7685 void CheckPrintfHandler::HandleIgnoredFlag(
7686                                 const analyze_printf::PrintfSpecifier &FS,
7687                                 const analyze_printf::OptionalFlag &ignoredFlag,
7688                                 const analyze_printf::OptionalFlag &flag,
7689                                 const char *startSpecifier,
7690                                 unsigned specifierLen) {
7691   // Warn about ignored flag with a fixit removal.
7692   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
7693                          << ignoredFlag.toString() << flag.toString(),
7694                        getLocationOfByte(ignoredFlag.getPosition()),
7695                        /*IsStringLocation*/true,
7696                        getSpecifierRange(startSpecifier, specifierLen),
7697                        FixItHint::CreateRemoval(
7698                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
7699 }
7700 
7701 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
7702                                                      unsigned flagLen) {
7703   // Warn about an empty flag.
7704   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
7705                        getLocationOfByte(startFlag),
7706                        /*IsStringLocation*/true,
7707                        getSpecifierRange(startFlag, flagLen));
7708 }
7709 
7710 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
7711                                                        unsigned flagLen) {
7712   // Warn about an invalid flag.
7713   auto Range = getSpecifierRange(startFlag, flagLen);
7714   StringRef flag(startFlag, flagLen);
7715   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
7716                       getLocationOfByte(startFlag),
7717                       /*IsStringLocation*/true,
7718                       Range, FixItHint::CreateRemoval(Range));
7719 }
7720 
7721 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
7722     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
7723     // Warn about using '[...]' without a '@' conversion.
7724     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
7725     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
7726     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
7727                          getLocationOfByte(conversionPosition),
7728                          /*IsStringLocation*/true,
7729                          Range, FixItHint::CreateRemoval(Range));
7730 }
7731 
7732 // Determines if the specified is a C++ class or struct containing
7733 // a member with the specified name and kind (e.g. a CXXMethodDecl named
7734 // "c_str()").
7735 template<typename MemberKind>
7736 static llvm::SmallPtrSet<MemberKind*, 1>
7737 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
7738   const RecordType *RT = Ty->getAs<RecordType>();
7739   llvm::SmallPtrSet<MemberKind*, 1> Results;
7740 
7741   if (!RT)
7742     return Results;
7743   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
7744   if (!RD || !RD->getDefinition())
7745     return Results;
7746 
7747   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
7748                  Sema::LookupMemberName);
7749   R.suppressDiagnostics();
7750 
7751   // We just need to include all members of the right kind turned up by the
7752   // filter, at this point.
7753   if (S.LookupQualifiedName(R, RT->getDecl()))
7754     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7755       NamedDecl *decl = (*I)->getUnderlyingDecl();
7756       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
7757         Results.insert(FK);
7758     }
7759   return Results;
7760 }
7761 
7762 /// Check if we could call '.c_str()' on an object.
7763 ///
7764 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
7765 /// allow the call, or if it would be ambiguous).
7766 bool Sema::hasCStrMethod(const Expr *E) {
7767   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7768 
7769   MethodSet Results =
7770       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
7771   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7772        MI != ME; ++MI)
7773     if ((*MI)->getMinRequiredArguments() == 0)
7774       return true;
7775   return false;
7776 }
7777 
7778 // Check if a (w)string was passed when a (w)char* was needed, and offer a
7779 // better diagnostic if so. AT is assumed to be valid.
7780 // Returns true when a c_str() conversion method is found.
7781 bool CheckPrintfHandler::checkForCStrMembers(
7782     const analyze_printf::ArgType &AT, const Expr *E) {
7783   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7784 
7785   MethodSet Results =
7786       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
7787 
7788   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7789        MI != ME; ++MI) {
7790     const CXXMethodDecl *Method = *MI;
7791     if (Method->getMinRequiredArguments() == 0 &&
7792         AT.matchesType(S.Context, Method->getReturnType())) {
7793       // FIXME: Suggest parens if the expression needs them.
7794       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
7795       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
7796           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
7797       return true;
7798     }
7799   }
7800 
7801   return false;
7802 }
7803 
7804 bool
7805 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
7806                                             &FS,
7807                                           const char *startSpecifier,
7808                                           unsigned specifierLen) {
7809   using namespace analyze_format_string;
7810   using namespace analyze_printf;
7811 
7812   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
7813 
7814   if (FS.consumesDataArgument()) {
7815     if (atFirstArg) {
7816         atFirstArg = false;
7817         usesPositionalArgs = FS.usesPositionalArg();
7818     }
7819     else if (usesPositionalArgs != FS.usesPositionalArg()) {
7820       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
7821                                         startSpecifier, specifierLen);
7822       return false;
7823     }
7824   }
7825 
7826   // First check if the field width, precision, and conversion specifier
7827   // have matching data arguments.
7828   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
7829                     startSpecifier, specifierLen)) {
7830     return false;
7831   }
7832 
7833   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
7834                     startSpecifier, specifierLen)) {
7835     return false;
7836   }
7837 
7838   if (!CS.consumesDataArgument()) {
7839     // FIXME: Technically specifying a precision or field width here
7840     // makes no sense.  Worth issuing a warning at some point.
7841     return true;
7842   }
7843 
7844   // Consume the argument.
7845   unsigned argIndex = FS.getArgIndex();
7846   if (argIndex < NumDataArgs) {
7847     // The check to see if the argIndex is valid will come later.
7848     // We set the bit here because we may exit early from this
7849     // function if we encounter some other error.
7850     CoveredArgs.set(argIndex);
7851   }
7852 
7853   // FreeBSD kernel extensions.
7854   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
7855       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
7856     // We need at least two arguments.
7857     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
7858       return false;
7859 
7860     // Claim the second argument.
7861     CoveredArgs.set(argIndex + 1);
7862 
7863     // Type check the first argument (int for %b, pointer for %D)
7864     const Expr *Ex = getDataArg(argIndex);
7865     const analyze_printf::ArgType &AT =
7866       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
7867         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
7868     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
7869       EmitFormatDiagnostic(
7870           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7871               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
7872               << false << Ex->getSourceRange(),
7873           Ex->getBeginLoc(), /*IsStringLocation*/ false,
7874           getSpecifierRange(startSpecifier, specifierLen));
7875 
7876     // Type check the second argument (char * for both %b and %D)
7877     Ex = getDataArg(argIndex + 1);
7878     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
7879     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
7880       EmitFormatDiagnostic(
7881           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7882               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
7883               << false << Ex->getSourceRange(),
7884           Ex->getBeginLoc(), /*IsStringLocation*/ false,
7885           getSpecifierRange(startSpecifier, specifierLen));
7886 
7887      return true;
7888   }
7889 
7890   // Check for using an Objective-C specific conversion specifier
7891   // in a non-ObjC literal.
7892   if (!allowsObjCArg() && CS.isObjCArg()) {
7893     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7894                                                   specifierLen);
7895   }
7896 
7897   // %P can only be used with os_log.
7898   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
7899     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7900                                                   specifierLen);
7901   }
7902 
7903   // %n is not allowed with os_log.
7904   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
7905     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
7906                          getLocationOfByte(CS.getStart()),
7907                          /*IsStringLocation*/ false,
7908                          getSpecifierRange(startSpecifier, specifierLen));
7909 
7910     return true;
7911   }
7912 
7913   // Only scalars are allowed for os_trace.
7914   if (FSType == Sema::FST_OSTrace &&
7915       (CS.getKind() == ConversionSpecifier::PArg ||
7916        CS.getKind() == ConversionSpecifier::sArg ||
7917        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
7918     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7919                                                   specifierLen);
7920   }
7921 
7922   // Check for use of public/private annotation outside of os_log().
7923   if (FSType != Sema::FST_OSLog) {
7924     if (FS.isPublic().isSet()) {
7925       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7926                                << "public",
7927                            getLocationOfByte(FS.isPublic().getPosition()),
7928                            /*IsStringLocation*/ false,
7929                            getSpecifierRange(startSpecifier, specifierLen));
7930     }
7931     if (FS.isPrivate().isSet()) {
7932       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7933                                << "private",
7934                            getLocationOfByte(FS.isPrivate().getPosition()),
7935                            /*IsStringLocation*/ false,
7936                            getSpecifierRange(startSpecifier, specifierLen));
7937     }
7938   }
7939 
7940   // Check for invalid use of field width
7941   if (!FS.hasValidFieldWidth()) {
7942     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
7943         startSpecifier, specifierLen);
7944   }
7945 
7946   // Check for invalid use of precision
7947   if (!FS.hasValidPrecision()) {
7948     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
7949         startSpecifier, specifierLen);
7950   }
7951 
7952   // Precision is mandatory for %P specifier.
7953   if (CS.getKind() == ConversionSpecifier::PArg &&
7954       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
7955     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
7956                          getLocationOfByte(startSpecifier),
7957                          /*IsStringLocation*/ false,
7958                          getSpecifierRange(startSpecifier, specifierLen));
7959   }
7960 
7961   // Check each flag does not conflict with any other component.
7962   if (!FS.hasValidThousandsGroupingPrefix())
7963     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
7964   if (!FS.hasValidLeadingZeros())
7965     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
7966   if (!FS.hasValidPlusPrefix())
7967     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
7968   if (!FS.hasValidSpacePrefix())
7969     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
7970   if (!FS.hasValidAlternativeForm())
7971     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
7972   if (!FS.hasValidLeftJustified())
7973     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
7974 
7975   // Check that flags are not ignored by another flag
7976   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
7977     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
7978         startSpecifier, specifierLen);
7979   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
7980     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
7981             startSpecifier, specifierLen);
7982 
7983   // Check the length modifier is valid with the given conversion specifier.
7984   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
7985                                  S.getLangOpts()))
7986     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7987                                 diag::warn_format_nonsensical_length);
7988   else if (!FS.hasStandardLengthModifier())
7989     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
7990   else if (!FS.hasStandardLengthConversionCombination())
7991     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7992                                 diag::warn_format_non_standard_conversion_spec);
7993 
7994   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
7995     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
7996 
7997   // The remaining checks depend on the data arguments.
7998   if (HasVAListArg)
7999     return true;
8000 
8001   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8002     return false;
8003 
8004   const Expr *Arg = getDataArg(argIndex);
8005   if (!Arg)
8006     return true;
8007 
8008   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
8009 }
8010 
8011 static bool requiresParensToAddCast(const Expr *E) {
8012   // FIXME: We should have a general way to reason about operator
8013   // precedence and whether parens are actually needed here.
8014   // Take care of a few common cases where they aren't.
8015   const Expr *Inside = E->IgnoreImpCasts();
8016   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
8017     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
8018 
8019   switch (Inside->getStmtClass()) {
8020   case Stmt::ArraySubscriptExprClass:
8021   case Stmt::CallExprClass:
8022   case Stmt::CharacterLiteralClass:
8023   case Stmt::CXXBoolLiteralExprClass:
8024   case Stmt::DeclRefExprClass:
8025   case Stmt::FloatingLiteralClass:
8026   case Stmt::IntegerLiteralClass:
8027   case Stmt::MemberExprClass:
8028   case Stmt::ObjCArrayLiteralClass:
8029   case Stmt::ObjCBoolLiteralExprClass:
8030   case Stmt::ObjCBoxedExprClass:
8031   case Stmt::ObjCDictionaryLiteralClass:
8032   case Stmt::ObjCEncodeExprClass:
8033   case Stmt::ObjCIvarRefExprClass:
8034   case Stmt::ObjCMessageExprClass:
8035   case Stmt::ObjCPropertyRefExprClass:
8036   case Stmt::ObjCStringLiteralClass:
8037   case Stmt::ObjCSubscriptRefExprClass:
8038   case Stmt::ParenExprClass:
8039   case Stmt::StringLiteralClass:
8040   case Stmt::UnaryOperatorClass:
8041     return false;
8042   default:
8043     return true;
8044   }
8045 }
8046 
8047 static std::pair<QualType, StringRef>
8048 shouldNotPrintDirectly(const ASTContext &Context,
8049                        QualType IntendedTy,
8050                        const Expr *E) {
8051   // Use a 'while' to peel off layers of typedefs.
8052   QualType TyTy = IntendedTy;
8053   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
8054     StringRef Name = UserTy->getDecl()->getName();
8055     QualType CastTy = llvm::StringSwitch<QualType>(Name)
8056       .Case("CFIndex", Context.getNSIntegerType())
8057       .Case("NSInteger", Context.getNSIntegerType())
8058       .Case("NSUInteger", Context.getNSUIntegerType())
8059       .Case("SInt32", Context.IntTy)
8060       .Case("UInt32", Context.UnsignedIntTy)
8061       .Default(QualType());
8062 
8063     if (!CastTy.isNull())
8064       return std::make_pair(CastTy, Name);
8065 
8066     TyTy = UserTy->desugar();
8067   }
8068 
8069   // Strip parens if necessary.
8070   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
8071     return shouldNotPrintDirectly(Context,
8072                                   PE->getSubExpr()->getType(),
8073                                   PE->getSubExpr());
8074 
8075   // If this is a conditional expression, then its result type is constructed
8076   // via usual arithmetic conversions and thus there might be no necessary
8077   // typedef sugar there.  Recurse to operands to check for NSInteger &
8078   // Co. usage condition.
8079   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8080     QualType TrueTy, FalseTy;
8081     StringRef TrueName, FalseName;
8082 
8083     std::tie(TrueTy, TrueName) =
8084       shouldNotPrintDirectly(Context,
8085                              CO->getTrueExpr()->getType(),
8086                              CO->getTrueExpr());
8087     std::tie(FalseTy, FalseName) =
8088       shouldNotPrintDirectly(Context,
8089                              CO->getFalseExpr()->getType(),
8090                              CO->getFalseExpr());
8091 
8092     if (TrueTy == FalseTy)
8093       return std::make_pair(TrueTy, TrueName);
8094     else if (TrueTy.isNull())
8095       return std::make_pair(FalseTy, FalseName);
8096     else if (FalseTy.isNull())
8097       return std::make_pair(TrueTy, TrueName);
8098   }
8099 
8100   return std::make_pair(QualType(), StringRef());
8101 }
8102 
8103 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
8104 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
8105 /// type do not count.
8106 static bool
8107 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
8108   QualType From = ICE->getSubExpr()->getType();
8109   QualType To = ICE->getType();
8110   // It's an integer promotion if the destination type is the promoted
8111   // source type.
8112   if (ICE->getCastKind() == CK_IntegralCast &&
8113       From->isPromotableIntegerType() &&
8114       S.Context.getPromotedIntegerType(From) == To)
8115     return true;
8116   // Look through vector types, since we do default argument promotion for
8117   // those in OpenCL.
8118   if (const auto *VecTy = From->getAs<ExtVectorType>())
8119     From = VecTy->getElementType();
8120   if (const auto *VecTy = To->getAs<ExtVectorType>())
8121     To = VecTy->getElementType();
8122   // It's a floating promotion if the source type is a lower rank.
8123   return ICE->getCastKind() == CK_FloatingCast &&
8124          S.Context.getFloatingTypeOrder(From, To) < 0;
8125 }
8126 
8127 bool
8128 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8129                                     const char *StartSpecifier,
8130                                     unsigned SpecifierLen,
8131                                     const Expr *E) {
8132   using namespace analyze_format_string;
8133   using namespace analyze_printf;
8134 
8135   // Now type check the data expression that matches the
8136   // format specifier.
8137   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
8138   if (!AT.isValid())
8139     return true;
8140 
8141   QualType ExprTy = E->getType();
8142   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
8143     ExprTy = TET->getUnderlyingExpr()->getType();
8144   }
8145 
8146   // Diagnose attempts to print a boolean value as a character. Unlike other
8147   // -Wformat diagnostics, this is fine from a type perspective, but it still
8148   // doesn't make sense.
8149   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
8150       E->isKnownToHaveBooleanValue()) {
8151     const CharSourceRange &CSR =
8152         getSpecifierRange(StartSpecifier, SpecifierLen);
8153     SmallString<4> FSString;
8154     llvm::raw_svector_ostream os(FSString);
8155     FS.toString(os);
8156     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
8157                              << FSString,
8158                          E->getExprLoc(), false, CSR);
8159     return true;
8160   }
8161 
8162   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
8163   if (Match == analyze_printf::ArgType::Match)
8164     return true;
8165 
8166   // Look through argument promotions for our error message's reported type.
8167   // This includes the integral and floating promotions, but excludes array
8168   // and function pointer decay (seeing that an argument intended to be a
8169   // string has type 'char [6]' is probably more confusing than 'char *') and
8170   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
8171   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8172     if (isArithmeticArgumentPromotion(S, ICE)) {
8173       E = ICE->getSubExpr();
8174       ExprTy = E->getType();
8175 
8176       // Check if we didn't match because of an implicit cast from a 'char'
8177       // or 'short' to an 'int'.  This is done because printf is a varargs
8178       // function.
8179       if (ICE->getType() == S.Context.IntTy ||
8180           ICE->getType() == S.Context.UnsignedIntTy) {
8181         // All further checking is done on the subexpression
8182         const analyze_printf::ArgType::MatchKind ImplicitMatch =
8183             AT.matchesType(S.Context, ExprTy);
8184         if (ImplicitMatch == analyze_printf::ArgType::Match)
8185           return true;
8186         if (ImplicitMatch == ArgType::NoMatchPedantic ||
8187             ImplicitMatch == ArgType::NoMatchTypeConfusion)
8188           Match = ImplicitMatch;
8189       }
8190     }
8191   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
8192     // Special case for 'a', which has type 'int' in C.
8193     // Note, however, that we do /not/ want to treat multibyte constants like
8194     // 'MooV' as characters! This form is deprecated but still exists.
8195     if (ExprTy == S.Context.IntTy)
8196       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
8197         ExprTy = S.Context.CharTy;
8198   }
8199 
8200   // Look through enums to their underlying type.
8201   bool IsEnum = false;
8202   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
8203     ExprTy = EnumTy->getDecl()->getIntegerType();
8204     IsEnum = true;
8205   }
8206 
8207   // %C in an Objective-C context prints a unichar, not a wchar_t.
8208   // If the argument is an integer of some kind, believe the %C and suggest
8209   // a cast instead of changing the conversion specifier.
8210   QualType IntendedTy = ExprTy;
8211   if (isObjCContext() &&
8212       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
8213     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
8214         !ExprTy->isCharType()) {
8215       // 'unichar' is defined as a typedef of unsigned short, but we should
8216       // prefer using the typedef if it is visible.
8217       IntendedTy = S.Context.UnsignedShortTy;
8218 
8219       // While we are here, check if the value is an IntegerLiteral that happens
8220       // to be within the valid range.
8221       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
8222         const llvm::APInt &V = IL->getValue();
8223         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
8224           return true;
8225       }
8226 
8227       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
8228                           Sema::LookupOrdinaryName);
8229       if (S.LookupName(Result, S.getCurScope())) {
8230         NamedDecl *ND = Result.getFoundDecl();
8231         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
8232           if (TD->getUnderlyingType() == IntendedTy)
8233             IntendedTy = S.Context.getTypedefType(TD);
8234       }
8235     }
8236   }
8237 
8238   // Special-case some of Darwin's platform-independence types by suggesting
8239   // casts to primitive types that are known to be large enough.
8240   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
8241   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
8242     QualType CastTy;
8243     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
8244     if (!CastTy.isNull()) {
8245       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
8246       // (long in ASTContext). Only complain to pedants.
8247       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
8248           (AT.isSizeT() || AT.isPtrdiffT()) &&
8249           AT.matchesType(S.Context, CastTy))
8250         Match = ArgType::NoMatchPedantic;
8251       IntendedTy = CastTy;
8252       ShouldNotPrintDirectly = true;
8253     }
8254   }
8255 
8256   // We may be able to offer a FixItHint if it is a supported type.
8257   PrintfSpecifier fixedFS = FS;
8258   bool Success =
8259       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
8260 
8261   if (Success) {
8262     // Get the fix string from the fixed format specifier
8263     SmallString<16> buf;
8264     llvm::raw_svector_ostream os(buf);
8265     fixedFS.toString(os);
8266 
8267     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
8268 
8269     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
8270       unsigned Diag;
8271       switch (Match) {
8272       case ArgType::Match: llvm_unreachable("expected non-matching");
8273       case ArgType::NoMatchPedantic:
8274         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8275         break;
8276       case ArgType::NoMatchTypeConfusion:
8277         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8278         break;
8279       case ArgType::NoMatch:
8280         Diag = diag::warn_format_conversion_argument_type_mismatch;
8281         break;
8282       }
8283 
8284       // In this case, the specifier is wrong and should be changed to match
8285       // the argument.
8286       EmitFormatDiagnostic(S.PDiag(Diag)
8287                                << AT.getRepresentativeTypeName(S.Context)
8288                                << IntendedTy << IsEnum << E->getSourceRange(),
8289                            E->getBeginLoc(),
8290                            /*IsStringLocation*/ false, SpecRange,
8291                            FixItHint::CreateReplacement(SpecRange, os.str()));
8292     } else {
8293       // The canonical type for formatting this value is different from the
8294       // actual type of the expression. (This occurs, for example, with Darwin's
8295       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
8296       // should be printed as 'long' for 64-bit compatibility.)
8297       // Rather than emitting a normal format/argument mismatch, we want to
8298       // add a cast to the recommended type (and correct the format string
8299       // if necessary).
8300       SmallString<16> CastBuf;
8301       llvm::raw_svector_ostream CastFix(CastBuf);
8302       CastFix << "(";
8303       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
8304       CastFix << ")";
8305 
8306       SmallVector<FixItHint,4> Hints;
8307       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
8308         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
8309 
8310       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
8311         // If there's already a cast present, just replace it.
8312         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
8313         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
8314 
8315       } else if (!requiresParensToAddCast(E)) {
8316         // If the expression has high enough precedence,
8317         // just write the C-style cast.
8318         Hints.push_back(
8319             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8320       } else {
8321         // Otherwise, add parens around the expression as well as the cast.
8322         CastFix << "(";
8323         Hints.push_back(
8324             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8325 
8326         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
8327         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
8328       }
8329 
8330       if (ShouldNotPrintDirectly) {
8331         // The expression has a type that should not be printed directly.
8332         // We extract the name from the typedef because we don't want to show
8333         // the underlying type in the diagnostic.
8334         StringRef Name;
8335         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
8336           Name = TypedefTy->getDecl()->getName();
8337         else
8338           Name = CastTyName;
8339         unsigned Diag = Match == ArgType::NoMatchPedantic
8340                             ? diag::warn_format_argument_needs_cast_pedantic
8341                             : diag::warn_format_argument_needs_cast;
8342         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
8343                                            << E->getSourceRange(),
8344                              E->getBeginLoc(), /*IsStringLocation=*/false,
8345                              SpecRange, Hints);
8346       } else {
8347         // In this case, the expression could be printed using a different
8348         // specifier, but we've decided that the specifier is probably correct
8349         // and we should cast instead. Just use the normal warning message.
8350         EmitFormatDiagnostic(
8351             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8352                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
8353                 << E->getSourceRange(),
8354             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
8355       }
8356     }
8357   } else {
8358     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
8359                                                    SpecifierLen);
8360     // Since the warning for passing non-POD types to variadic functions
8361     // was deferred until now, we emit a warning for non-POD
8362     // arguments here.
8363     switch (S.isValidVarArgType(ExprTy)) {
8364     case Sema::VAK_Valid:
8365     case Sema::VAK_ValidInCXX11: {
8366       unsigned Diag;
8367       switch (Match) {
8368       case ArgType::Match: llvm_unreachable("expected non-matching");
8369       case ArgType::NoMatchPedantic:
8370         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8371         break;
8372       case ArgType::NoMatchTypeConfusion:
8373         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8374         break;
8375       case ArgType::NoMatch:
8376         Diag = diag::warn_format_conversion_argument_type_mismatch;
8377         break;
8378       }
8379 
8380       EmitFormatDiagnostic(
8381           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
8382                         << IsEnum << CSR << E->getSourceRange(),
8383           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8384       break;
8385     }
8386     case Sema::VAK_Undefined:
8387     case Sema::VAK_MSVCUndefined:
8388       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
8389                                << S.getLangOpts().CPlusPlus11 << ExprTy
8390                                << CallType
8391                                << AT.getRepresentativeTypeName(S.Context) << CSR
8392                                << E->getSourceRange(),
8393                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8394       checkForCStrMembers(AT, E);
8395       break;
8396 
8397     case Sema::VAK_Invalid:
8398       if (ExprTy->isObjCObjectType())
8399         EmitFormatDiagnostic(
8400             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
8401                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
8402                 << AT.getRepresentativeTypeName(S.Context) << CSR
8403                 << E->getSourceRange(),
8404             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8405       else
8406         // FIXME: If this is an initializer list, suggest removing the braces
8407         // or inserting a cast to the target type.
8408         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
8409             << isa<InitListExpr>(E) << ExprTy << CallType
8410             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
8411       break;
8412     }
8413 
8414     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
8415            "format string specifier index out of range");
8416     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
8417   }
8418 
8419   return true;
8420 }
8421 
8422 //===--- CHECK: Scanf format string checking ------------------------------===//
8423 
8424 namespace {
8425 
8426 class CheckScanfHandler : public CheckFormatHandler {
8427 public:
8428   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
8429                     const Expr *origFormatExpr, Sema::FormatStringType type,
8430                     unsigned firstDataArg, unsigned numDataArgs,
8431                     const char *beg, bool hasVAListArg,
8432                     ArrayRef<const Expr *> Args, unsigned formatIdx,
8433                     bool inFunctionCall, Sema::VariadicCallType CallType,
8434                     llvm::SmallBitVector &CheckedVarArgs,
8435                     UncoveredArgHandler &UncoveredArg)
8436       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8437                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8438                            inFunctionCall, CallType, CheckedVarArgs,
8439                            UncoveredArg) {}
8440 
8441   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
8442                             const char *startSpecifier,
8443                             unsigned specifierLen) override;
8444 
8445   bool HandleInvalidScanfConversionSpecifier(
8446           const analyze_scanf::ScanfSpecifier &FS,
8447           const char *startSpecifier,
8448           unsigned specifierLen) override;
8449 
8450   void HandleIncompleteScanList(const char *start, const char *end) override;
8451 };
8452 
8453 } // namespace
8454 
8455 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
8456                                                  const char *end) {
8457   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
8458                        getLocationOfByte(end), /*IsStringLocation*/true,
8459                        getSpecifierRange(start, end - start));
8460 }
8461 
8462 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
8463                                         const analyze_scanf::ScanfSpecifier &FS,
8464                                         const char *startSpecifier,
8465                                         unsigned specifierLen) {
8466   const analyze_scanf::ScanfConversionSpecifier &CS =
8467     FS.getConversionSpecifier();
8468 
8469   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8470                                           getLocationOfByte(CS.getStart()),
8471                                           startSpecifier, specifierLen,
8472                                           CS.getStart(), CS.getLength());
8473 }
8474 
8475 bool CheckScanfHandler::HandleScanfSpecifier(
8476                                        const analyze_scanf::ScanfSpecifier &FS,
8477                                        const char *startSpecifier,
8478                                        unsigned specifierLen) {
8479   using namespace analyze_scanf;
8480   using namespace analyze_format_string;
8481 
8482   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
8483 
8484   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
8485   // be used to decide if we are using positional arguments consistently.
8486   if (FS.consumesDataArgument()) {
8487     if (atFirstArg) {
8488       atFirstArg = false;
8489       usesPositionalArgs = FS.usesPositionalArg();
8490     }
8491     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8492       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8493                                         startSpecifier, specifierLen);
8494       return false;
8495     }
8496   }
8497 
8498   // Check if the field with is non-zero.
8499   const OptionalAmount &Amt = FS.getFieldWidth();
8500   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
8501     if (Amt.getConstantAmount() == 0) {
8502       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
8503                                                    Amt.getConstantLength());
8504       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
8505                            getLocationOfByte(Amt.getStart()),
8506                            /*IsStringLocation*/true, R,
8507                            FixItHint::CreateRemoval(R));
8508     }
8509   }
8510 
8511   if (!FS.consumesDataArgument()) {
8512     // FIXME: Technically specifying a precision or field width here
8513     // makes no sense.  Worth issuing a warning at some point.
8514     return true;
8515   }
8516 
8517   // Consume the argument.
8518   unsigned argIndex = FS.getArgIndex();
8519   if (argIndex < NumDataArgs) {
8520       // The check to see if the argIndex is valid will come later.
8521       // We set the bit here because we may exit early from this
8522       // function if we encounter some other error.
8523     CoveredArgs.set(argIndex);
8524   }
8525 
8526   // Check the length modifier is valid with the given conversion specifier.
8527   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8528                                  S.getLangOpts()))
8529     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8530                                 diag::warn_format_nonsensical_length);
8531   else if (!FS.hasStandardLengthModifier())
8532     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8533   else if (!FS.hasStandardLengthConversionCombination())
8534     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8535                                 diag::warn_format_non_standard_conversion_spec);
8536 
8537   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8538     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8539 
8540   // The remaining checks depend on the data arguments.
8541   if (HasVAListArg)
8542     return true;
8543 
8544   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8545     return false;
8546 
8547   // Check that the argument type matches the format specifier.
8548   const Expr *Ex = getDataArg(argIndex);
8549   if (!Ex)
8550     return true;
8551 
8552   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
8553 
8554   if (!AT.isValid()) {
8555     return true;
8556   }
8557 
8558   analyze_format_string::ArgType::MatchKind Match =
8559       AT.matchesType(S.Context, Ex->getType());
8560   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
8561   if (Match == analyze_format_string::ArgType::Match)
8562     return true;
8563 
8564   ScanfSpecifier fixedFS = FS;
8565   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
8566                                  S.getLangOpts(), S.Context);
8567 
8568   unsigned Diag =
8569       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8570                : diag::warn_format_conversion_argument_type_mismatch;
8571 
8572   if (Success) {
8573     // Get the fix string from the fixed format specifier.
8574     SmallString<128> buf;
8575     llvm::raw_svector_ostream os(buf);
8576     fixedFS.toString(os);
8577 
8578     EmitFormatDiagnostic(
8579         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
8580                       << Ex->getType() << false << Ex->getSourceRange(),
8581         Ex->getBeginLoc(),
8582         /*IsStringLocation*/ false,
8583         getSpecifierRange(startSpecifier, specifierLen),
8584         FixItHint::CreateReplacement(
8585             getSpecifierRange(startSpecifier, specifierLen), os.str()));
8586   } else {
8587     EmitFormatDiagnostic(S.PDiag(Diag)
8588                              << AT.getRepresentativeTypeName(S.Context)
8589                              << Ex->getType() << false << Ex->getSourceRange(),
8590                          Ex->getBeginLoc(),
8591                          /*IsStringLocation*/ false,
8592                          getSpecifierRange(startSpecifier, specifierLen));
8593   }
8594 
8595   return true;
8596 }
8597 
8598 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
8599                               const Expr *OrigFormatExpr,
8600                               ArrayRef<const Expr *> Args,
8601                               bool HasVAListArg, unsigned format_idx,
8602                               unsigned firstDataArg,
8603                               Sema::FormatStringType Type,
8604                               bool inFunctionCall,
8605                               Sema::VariadicCallType CallType,
8606                               llvm::SmallBitVector &CheckedVarArgs,
8607                               UncoveredArgHandler &UncoveredArg,
8608                               bool IgnoreStringsWithoutSpecifiers) {
8609   // CHECK: is the format string a wide literal?
8610   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
8611     CheckFormatHandler::EmitFormatDiagnostic(
8612         S, inFunctionCall, Args[format_idx],
8613         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
8614         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8615     return;
8616   }
8617 
8618   // Str - The format string.  NOTE: this is NOT null-terminated!
8619   StringRef StrRef = FExpr->getString();
8620   const char *Str = StrRef.data();
8621   // Account for cases where the string literal is truncated in a declaration.
8622   const ConstantArrayType *T =
8623     S.Context.getAsConstantArrayType(FExpr->getType());
8624   assert(T && "String literal not of constant array type!");
8625   size_t TypeSize = T->getSize().getZExtValue();
8626   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8627   const unsigned numDataArgs = Args.size() - firstDataArg;
8628 
8629   if (IgnoreStringsWithoutSpecifiers &&
8630       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
8631           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
8632     return;
8633 
8634   // Emit a warning if the string literal is truncated and does not contain an
8635   // embedded null character.
8636   if (TypeSize <= StrRef.size() &&
8637       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
8638     CheckFormatHandler::EmitFormatDiagnostic(
8639         S, inFunctionCall, Args[format_idx],
8640         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
8641         FExpr->getBeginLoc(),
8642         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
8643     return;
8644   }
8645 
8646   // CHECK: empty format string?
8647   if (StrLen == 0 && numDataArgs > 0) {
8648     CheckFormatHandler::EmitFormatDiagnostic(
8649         S, inFunctionCall, Args[format_idx],
8650         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
8651         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8652     return;
8653   }
8654 
8655   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
8656       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
8657       Type == Sema::FST_OSTrace) {
8658     CheckPrintfHandler H(
8659         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
8660         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
8661         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
8662         CheckedVarArgs, UncoveredArg);
8663 
8664     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
8665                                                   S.getLangOpts(),
8666                                                   S.Context.getTargetInfo(),
8667                                             Type == Sema::FST_FreeBSDKPrintf))
8668       H.DoneProcessing();
8669   } else if (Type == Sema::FST_Scanf) {
8670     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
8671                         numDataArgs, Str, HasVAListArg, Args, format_idx,
8672                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
8673 
8674     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
8675                                                  S.getLangOpts(),
8676                                                  S.Context.getTargetInfo()))
8677       H.DoneProcessing();
8678   } // TODO: handle other formats
8679 }
8680 
8681 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
8682   // Str - The format string.  NOTE: this is NOT null-terminated!
8683   StringRef StrRef = FExpr->getString();
8684   const char *Str = StrRef.data();
8685   // Account for cases where the string literal is truncated in a declaration.
8686   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
8687   assert(T && "String literal not of constant array type!");
8688   size_t TypeSize = T->getSize().getZExtValue();
8689   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8690   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
8691                                                          getLangOpts(),
8692                                                          Context.getTargetInfo());
8693 }
8694 
8695 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
8696 
8697 // Returns the related absolute value function that is larger, of 0 if one
8698 // does not exist.
8699 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
8700   switch (AbsFunction) {
8701   default:
8702     return 0;
8703 
8704   case Builtin::BI__builtin_abs:
8705     return Builtin::BI__builtin_labs;
8706   case Builtin::BI__builtin_labs:
8707     return Builtin::BI__builtin_llabs;
8708   case Builtin::BI__builtin_llabs:
8709     return 0;
8710 
8711   case Builtin::BI__builtin_fabsf:
8712     return Builtin::BI__builtin_fabs;
8713   case Builtin::BI__builtin_fabs:
8714     return Builtin::BI__builtin_fabsl;
8715   case Builtin::BI__builtin_fabsl:
8716     return 0;
8717 
8718   case Builtin::BI__builtin_cabsf:
8719     return Builtin::BI__builtin_cabs;
8720   case Builtin::BI__builtin_cabs:
8721     return Builtin::BI__builtin_cabsl;
8722   case Builtin::BI__builtin_cabsl:
8723     return 0;
8724 
8725   case Builtin::BIabs:
8726     return Builtin::BIlabs;
8727   case Builtin::BIlabs:
8728     return Builtin::BIllabs;
8729   case Builtin::BIllabs:
8730     return 0;
8731 
8732   case Builtin::BIfabsf:
8733     return Builtin::BIfabs;
8734   case Builtin::BIfabs:
8735     return Builtin::BIfabsl;
8736   case Builtin::BIfabsl:
8737     return 0;
8738 
8739   case Builtin::BIcabsf:
8740    return Builtin::BIcabs;
8741   case Builtin::BIcabs:
8742     return Builtin::BIcabsl;
8743   case Builtin::BIcabsl:
8744     return 0;
8745   }
8746 }
8747 
8748 // Returns the argument type of the absolute value function.
8749 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
8750                                              unsigned AbsType) {
8751   if (AbsType == 0)
8752     return QualType();
8753 
8754   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
8755   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
8756   if (Error != ASTContext::GE_None)
8757     return QualType();
8758 
8759   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
8760   if (!FT)
8761     return QualType();
8762 
8763   if (FT->getNumParams() != 1)
8764     return QualType();
8765 
8766   return FT->getParamType(0);
8767 }
8768 
8769 // Returns the best absolute value function, or zero, based on type and
8770 // current absolute value function.
8771 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
8772                                    unsigned AbsFunctionKind) {
8773   unsigned BestKind = 0;
8774   uint64_t ArgSize = Context.getTypeSize(ArgType);
8775   for (unsigned Kind = AbsFunctionKind; Kind != 0;
8776        Kind = getLargerAbsoluteValueFunction(Kind)) {
8777     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
8778     if (Context.getTypeSize(ParamType) >= ArgSize) {
8779       if (BestKind == 0)
8780         BestKind = Kind;
8781       else if (Context.hasSameType(ParamType, ArgType)) {
8782         BestKind = Kind;
8783         break;
8784       }
8785     }
8786   }
8787   return BestKind;
8788 }
8789 
8790 enum AbsoluteValueKind {
8791   AVK_Integer,
8792   AVK_Floating,
8793   AVK_Complex
8794 };
8795 
8796 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
8797   if (T->isIntegralOrEnumerationType())
8798     return AVK_Integer;
8799   if (T->isRealFloatingType())
8800     return AVK_Floating;
8801   if (T->isAnyComplexType())
8802     return AVK_Complex;
8803 
8804   llvm_unreachable("Type not integer, floating, or complex");
8805 }
8806 
8807 // Changes the absolute value function to a different type.  Preserves whether
8808 // the function is a builtin.
8809 static unsigned changeAbsFunction(unsigned AbsKind,
8810                                   AbsoluteValueKind ValueKind) {
8811   switch (ValueKind) {
8812   case AVK_Integer:
8813     switch (AbsKind) {
8814     default:
8815       return 0;
8816     case Builtin::BI__builtin_fabsf:
8817     case Builtin::BI__builtin_fabs:
8818     case Builtin::BI__builtin_fabsl:
8819     case Builtin::BI__builtin_cabsf:
8820     case Builtin::BI__builtin_cabs:
8821     case Builtin::BI__builtin_cabsl:
8822       return Builtin::BI__builtin_abs;
8823     case Builtin::BIfabsf:
8824     case Builtin::BIfabs:
8825     case Builtin::BIfabsl:
8826     case Builtin::BIcabsf:
8827     case Builtin::BIcabs:
8828     case Builtin::BIcabsl:
8829       return Builtin::BIabs;
8830     }
8831   case AVK_Floating:
8832     switch (AbsKind) {
8833     default:
8834       return 0;
8835     case Builtin::BI__builtin_abs:
8836     case Builtin::BI__builtin_labs:
8837     case Builtin::BI__builtin_llabs:
8838     case Builtin::BI__builtin_cabsf:
8839     case Builtin::BI__builtin_cabs:
8840     case Builtin::BI__builtin_cabsl:
8841       return Builtin::BI__builtin_fabsf;
8842     case Builtin::BIabs:
8843     case Builtin::BIlabs:
8844     case Builtin::BIllabs:
8845     case Builtin::BIcabsf:
8846     case Builtin::BIcabs:
8847     case Builtin::BIcabsl:
8848       return Builtin::BIfabsf;
8849     }
8850   case AVK_Complex:
8851     switch (AbsKind) {
8852     default:
8853       return 0;
8854     case Builtin::BI__builtin_abs:
8855     case Builtin::BI__builtin_labs:
8856     case Builtin::BI__builtin_llabs:
8857     case Builtin::BI__builtin_fabsf:
8858     case Builtin::BI__builtin_fabs:
8859     case Builtin::BI__builtin_fabsl:
8860       return Builtin::BI__builtin_cabsf;
8861     case Builtin::BIabs:
8862     case Builtin::BIlabs:
8863     case Builtin::BIllabs:
8864     case Builtin::BIfabsf:
8865     case Builtin::BIfabs:
8866     case Builtin::BIfabsl:
8867       return Builtin::BIcabsf;
8868     }
8869   }
8870   llvm_unreachable("Unable to convert function");
8871 }
8872 
8873 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
8874   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
8875   if (!FnInfo)
8876     return 0;
8877 
8878   switch (FDecl->getBuiltinID()) {
8879   default:
8880     return 0;
8881   case Builtin::BI__builtin_abs:
8882   case Builtin::BI__builtin_fabs:
8883   case Builtin::BI__builtin_fabsf:
8884   case Builtin::BI__builtin_fabsl:
8885   case Builtin::BI__builtin_labs:
8886   case Builtin::BI__builtin_llabs:
8887   case Builtin::BI__builtin_cabs:
8888   case Builtin::BI__builtin_cabsf:
8889   case Builtin::BI__builtin_cabsl:
8890   case Builtin::BIabs:
8891   case Builtin::BIlabs:
8892   case Builtin::BIllabs:
8893   case Builtin::BIfabs:
8894   case Builtin::BIfabsf:
8895   case Builtin::BIfabsl:
8896   case Builtin::BIcabs:
8897   case Builtin::BIcabsf:
8898   case Builtin::BIcabsl:
8899     return FDecl->getBuiltinID();
8900   }
8901   llvm_unreachable("Unknown Builtin type");
8902 }
8903 
8904 // If the replacement is valid, emit a note with replacement function.
8905 // Additionally, suggest including the proper header if not already included.
8906 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
8907                             unsigned AbsKind, QualType ArgType) {
8908   bool EmitHeaderHint = true;
8909   const char *HeaderName = nullptr;
8910   const char *FunctionName = nullptr;
8911   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
8912     FunctionName = "std::abs";
8913     if (ArgType->isIntegralOrEnumerationType()) {
8914       HeaderName = "cstdlib";
8915     } else if (ArgType->isRealFloatingType()) {
8916       HeaderName = "cmath";
8917     } else {
8918       llvm_unreachable("Invalid Type");
8919     }
8920 
8921     // Lookup all std::abs
8922     if (NamespaceDecl *Std = S.getStdNamespace()) {
8923       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
8924       R.suppressDiagnostics();
8925       S.LookupQualifiedName(R, Std);
8926 
8927       for (const auto *I : R) {
8928         const FunctionDecl *FDecl = nullptr;
8929         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
8930           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
8931         } else {
8932           FDecl = dyn_cast<FunctionDecl>(I);
8933         }
8934         if (!FDecl)
8935           continue;
8936 
8937         // Found std::abs(), check that they are the right ones.
8938         if (FDecl->getNumParams() != 1)
8939           continue;
8940 
8941         // Check that the parameter type can handle the argument.
8942         QualType ParamType = FDecl->getParamDecl(0)->getType();
8943         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
8944             S.Context.getTypeSize(ArgType) <=
8945                 S.Context.getTypeSize(ParamType)) {
8946           // Found a function, don't need the header hint.
8947           EmitHeaderHint = false;
8948           break;
8949         }
8950       }
8951     }
8952   } else {
8953     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
8954     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
8955 
8956     if (HeaderName) {
8957       DeclarationName DN(&S.Context.Idents.get(FunctionName));
8958       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
8959       R.suppressDiagnostics();
8960       S.LookupName(R, S.getCurScope());
8961 
8962       if (R.isSingleResult()) {
8963         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
8964         if (FD && FD->getBuiltinID() == AbsKind) {
8965           EmitHeaderHint = false;
8966         } else {
8967           return;
8968         }
8969       } else if (!R.empty()) {
8970         return;
8971       }
8972     }
8973   }
8974 
8975   S.Diag(Loc, diag::note_replace_abs_function)
8976       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
8977 
8978   if (!HeaderName)
8979     return;
8980 
8981   if (!EmitHeaderHint)
8982     return;
8983 
8984   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
8985                                                     << FunctionName;
8986 }
8987 
8988 template <std::size_t StrLen>
8989 static bool IsStdFunction(const FunctionDecl *FDecl,
8990                           const char (&Str)[StrLen]) {
8991   if (!FDecl)
8992     return false;
8993   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
8994     return false;
8995   if (!FDecl->isInStdNamespace())
8996     return false;
8997 
8998   return true;
8999 }
9000 
9001 // Warn when using the wrong abs() function.
9002 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
9003                                       const FunctionDecl *FDecl) {
9004   if (Call->getNumArgs() != 1)
9005     return;
9006 
9007   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
9008   bool IsStdAbs = IsStdFunction(FDecl, "abs");
9009   if (AbsKind == 0 && !IsStdAbs)
9010     return;
9011 
9012   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9013   QualType ParamType = Call->getArg(0)->getType();
9014 
9015   // Unsigned types cannot be negative.  Suggest removing the absolute value
9016   // function call.
9017   if (ArgType->isUnsignedIntegerType()) {
9018     const char *FunctionName =
9019         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
9020     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
9021     Diag(Call->getExprLoc(), diag::note_remove_abs)
9022         << FunctionName
9023         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
9024     return;
9025   }
9026 
9027   // Taking the absolute value of a pointer is very suspicious, they probably
9028   // wanted to index into an array, dereference a pointer, call a function, etc.
9029   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
9030     unsigned DiagType = 0;
9031     if (ArgType->isFunctionType())
9032       DiagType = 1;
9033     else if (ArgType->isArrayType())
9034       DiagType = 2;
9035 
9036     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
9037     return;
9038   }
9039 
9040   // std::abs has overloads which prevent most of the absolute value problems
9041   // from occurring.
9042   if (IsStdAbs)
9043     return;
9044 
9045   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
9046   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
9047 
9048   // The argument and parameter are the same kind.  Check if they are the right
9049   // size.
9050   if (ArgValueKind == ParamValueKind) {
9051     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
9052       return;
9053 
9054     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
9055     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
9056         << FDecl << ArgType << ParamType;
9057 
9058     if (NewAbsKind == 0)
9059       return;
9060 
9061     emitReplacement(*this, Call->getExprLoc(),
9062                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9063     return;
9064   }
9065 
9066   // ArgValueKind != ParamValueKind
9067   // The wrong type of absolute value function was used.  Attempt to find the
9068   // proper one.
9069   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
9070   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
9071   if (NewAbsKind == 0)
9072     return;
9073 
9074   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
9075       << FDecl << ParamValueKind << ArgValueKind;
9076 
9077   emitReplacement(*this, Call->getExprLoc(),
9078                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9079 }
9080 
9081 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
9082 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
9083                                 const FunctionDecl *FDecl) {
9084   if (!Call || !FDecl) return;
9085 
9086   // Ignore template specializations and macros.
9087   if (inTemplateInstantiation()) return;
9088   if (Call->getExprLoc().isMacroID()) return;
9089 
9090   // Only care about the one template argument, two function parameter std::max
9091   if (Call->getNumArgs() != 2) return;
9092   if (!IsStdFunction(FDecl, "max")) return;
9093   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
9094   if (!ArgList) return;
9095   if (ArgList->size() != 1) return;
9096 
9097   // Check that template type argument is unsigned integer.
9098   const auto& TA = ArgList->get(0);
9099   if (TA.getKind() != TemplateArgument::Type) return;
9100   QualType ArgType = TA.getAsType();
9101   if (!ArgType->isUnsignedIntegerType()) return;
9102 
9103   // See if either argument is a literal zero.
9104   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
9105     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
9106     if (!MTE) return false;
9107     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
9108     if (!Num) return false;
9109     if (Num->getValue() != 0) return false;
9110     return true;
9111   };
9112 
9113   const Expr *FirstArg = Call->getArg(0);
9114   const Expr *SecondArg = Call->getArg(1);
9115   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
9116   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
9117 
9118   // Only warn when exactly one argument is zero.
9119   if (IsFirstArgZero == IsSecondArgZero) return;
9120 
9121   SourceRange FirstRange = FirstArg->getSourceRange();
9122   SourceRange SecondRange = SecondArg->getSourceRange();
9123 
9124   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
9125 
9126   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
9127       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
9128 
9129   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
9130   SourceRange RemovalRange;
9131   if (IsFirstArgZero) {
9132     RemovalRange = SourceRange(FirstRange.getBegin(),
9133                                SecondRange.getBegin().getLocWithOffset(-1));
9134   } else {
9135     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
9136                                SecondRange.getEnd());
9137   }
9138 
9139   Diag(Call->getExprLoc(), diag::note_remove_max_call)
9140         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
9141         << FixItHint::CreateRemoval(RemovalRange);
9142 }
9143 
9144 //===--- CHECK: Standard memory functions ---------------------------------===//
9145 
9146 /// Takes the expression passed to the size_t parameter of functions
9147 /// such as memcmp, strncat, etc and warns if it's a comparison.
9148 ///
9149 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
9150 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
9151                                            IdentifierInfo *FnName,
9152                                            SourceLocation FnLoc,
9153                                            SourceLocation RParenLoc) {
9154   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
9155   if (!Size)
9156     return false;
9157 
9158   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
9159   if (!Size->isComparisonOp() && !Size->isLogicalOp())
9160     return false;
9161 
9162   SourceRange SizeRange = Size->getSourceRange();
9163   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
9164       << SizeRange << FnName;
9165   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
9166       << FnName
9167       << FixItHint::CreateInsertion(
9168              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
9169       << FixItHint::CreateRemoval(RParenLoc);
9170   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
9171       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
9172       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
9173                                     ")");
9174 
9175   return true;
9176 }
9177 
9178 /// Determine whether the given type is or contains a dynamic class type
9179 /// (e.g., whether it has a vtable).
9180 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
9181                                                      bool &IsContained) {
9182   // Look through array types while ignoring qualifiers.
9183   const Type *Ty = T->getBaseElementTypeUnsafe();
9184   IsContained = false;
9185 
9186   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
9187   RD = RD ? RD->getDefinition() : nullptr;
9188   if (!RD || RD->isInvalidDecl())
9189     return nullptr;
9190 
9191   if (RD->isDynamicClass())
9192     return RD;
9193 
9194   // Check all the fields.  If any bases were dynamic, the class is dynamic.
9195   // It's impossible for a class to transitively contain itself by value, so
9196   // infinite recursion is impossible.
9197   for (auto *FD : RD->fields()) {
9198     bool SubContained;
9199     if (const CXXRecordDecl *ContainedRD =
9200             getContainedDynamicClass(FD->getType(), SubContained)) {
9201       IsContained = true;
9202       return ContainedRD;
9203     }
9204   }
9205 
9206   return nullptr;
9207 }
9208 
9209 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
9210   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
9211     if (Unary->getKind() == UETT_SizeOf)
9212       return Unary;
9213   return nullptr;
9214 }
9215 
9216 /// If E is a sizeof expression, returns its argument expression,
9217 /// otherwise returns NULL.
9218 static const Expr *getSizeOfExprArg(const Expr *E) {
9219   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9220     if (!SizeOf->isArgumentType())
9221       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
9222   return nullptr;
9223 }
9224 
9225 /// If E is a sizeof expression, returns its argument type.
9226 static QualType getSizeOfArgType(const Expr *E) {
9227   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9228     return SizeOf->getTypeOfArgument();
9229   return QualType();
9230 }
9231 
9232 namespace {
9233 
9234 struct SearchNonTrivialToInitializeField
9235     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
9236   using Super =
9237       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
9238 
9239   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
9240 
9241   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
9242                      SourceLocation SL) {
9243     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9244       asDerived().visitArray(PDIK, AT, SL);
9245       return;
9246     }
9247 
9248     Super::visitWithKind(PDIK, FT, SL);
9249   }
9250 
9251   void visitARCStrong(QualType FT, SourceLocation SL) {
9252     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9253   }
9254   void visitARCWeak(QualType FT, SourceLocation SL) {
9255     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9256   }
9257   void visitStruct(QualType FT, SourceLocation SL) {
9258     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9259       visit(FD->getType(), FD->getLocation());
9260   }
9261   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
9262                   const ArrayType *AT, SourceLocation SL) {
9263     visit(getContext().getBaseElementType(AT), SL);
9264   }
9265   void visitTrivial(QualType FT, SourceLocation SL) {}
9266 
9267   static void diag(QualType RT, const Expr *E, Sema &S) {
9268     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
9269   }
9270 
9271   ASTContext &getContext() { return S.getASTContext(); }
9272 
9273   const Expr *E;
9274   Sema &S;
9275 };
9276 
9277 struct SearchNonTrivialToCopyField
9278     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
9279   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
9280 
9281   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
9282 
9283   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
9284                      SourceLocation SL) {
9285     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9286       asDerived().visitArray(PCK, AT, SL);
9287       return;
9288     }
9289 
9290     Super::visitWithKind(PCK, FT, SL);
9291   }
9292 
9293   void visitARCStrong(QualType FT, SourceLocation SL) {
9294     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9295   }
9296   void visitARCWeak(QualType FT, SourceLocation SL) {
9297     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9298   }
9299   void visitStruct(QualType FT, SourceLocation SL) {
9300     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9301       visit(FD->getType(), FD->getLocation());
9302   }
9303   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
9304                   SourceLocation SL) {
9305     visit(getContext().getBaseElementType(AT), SL);
9306   }
9307   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
9308                 SourceLocation SL) {}
9309   void visitTrivial(QualType FT, SourceLocation SL) {}
9310   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
9311 
9312   static void diag(QualType RT, const Expr *E, Sema &S) {
9313     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
9314   }
9315 
9316   ASTContext &getContext() { return S.getASTContext(); }
9317 
9318   const Expr *E;
9319   Sema &S;
9320 };
9321 
9322 }
9323 
9324 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
9325 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
9326   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
9327 
9328   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
9329     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
9330       return false;
9331 
9332     return doesExprLikelyComputeSize(BO->getLHS()) ||
9333            doesExprLikelyComputeSize(BO->getRHS());
9334   }
9335 
9336   return getAsSizeOfExpr(SizeofExpr) != nullptr;
9337 }
9338 
9339 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
9340 ///
9341 /// \code
9342 ///   #define MACRO 0
9343 ///   foo(MACRO);
9344 ///   foo(0);
9345 /// \endcode
9346 ///
9347 /// This should return true for the first call to foo, but not for the second
9348 /// (regardless of whether foo is a macro or function).
9349 static bool isArgumentExpandedFromMacro(SourceManager &SM,
9350                                         SourceLocation CallLoc,
9351                                         SourceLocation ArgLoc) {
9352   if (!CallLoc.isMacroID())
9353     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
9354 
9355   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
9356          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
9357 }
9358 
9359 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
9360 /// last two arguments transposed.
9361 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
9362   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
9363     return;
9364 
9365   const Expr *SizeArg =
9366     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
9367 
9368   auto isLiteralZero = [](const Expr *E) {
9369     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
9370   };
9371 
9372   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
9373   SourceLocation CallLoc = Call->getRParenLoc();
9374   SourceManager &SM = S.getSourceManager();
9375   if (isLiteralZero(SizeArg) &&
9376       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
9377 
9378     SourceLocation DiagLoc = SizeArg->getExprLoc();
9379 
9380     // Some platforms #define bzero to __builtin_memset. See if this is the
9381     // case, and if so, emit a better diagnostic.
9382     if (BId == Builtin::BIbzero ||
9383         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
9384                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
9385       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
9386       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
9387     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
9388       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
9389       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
9390     }
9391     return;
9392   }
9393 
9394   // If the second argument to a memset is a sizeof expression and the third
9395   // isn't, this is also likely an error. This should catch
9396   // 'memset(buf, sizeof(buf), 0xff)'.
9397   if (BId == Builtin::BImemset &&
9398       doesExprLikelyComputeSize(Call->getArg(1)) &&
9399       !doesExprLikelyComputeSize(Call->getArg(2))) {
9400     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
9401     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
9402     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
9403     return;
9404   }
9405 }
9406 
9407 /// Check for dangerous or invalid arguments to memset().
9408 ///
9409 /// This issues warnings on known problematic, dangerous or unspecified
9410 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
9411 /// function calls.
9412 ///
9413 /// \param Call The call expression to diagnose.
9414 void Sema::CheckMemaccessArguments(const CallExpr *Call,
9415                                    unsigned BId,
9416                                    IdentifierInfo *FnName) {
9417   assert(BId != 0);
9418 
9419   // It is possible to have a non-standard definition of memset.  Validate
9420   // we have enough arguments, and if not, abort further checking.
9421   unsigned ExpectedNumArgs =
9422       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
9423   if (Call->getNumArgs() < ExpectedNumArgs)
9424     return;
9425 
9426   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
9427                       BId == Builtin::BIstrndup ? 1 : 2);
9428   unsigned LenArg =
9429       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
9430   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
9431 
9432   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
9433                                      Call->getBeginLoc(), Call->getRParenLoc()))
9434     return;
9435 
9436   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
9437   CheckMemaccessSize(*this, BId, Call);
9438 
9439   // We have special checking when the length is a sizeof expression.
9440   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
9441   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
9442   llvm::FoldingSetNodeID SizeOfArgID;
9443 
9444   // Although widely used, 'bzero' is not a standard function. Be more strict
9445   // with the argument types before allowing diagnostics and only allow the
9446   // form bzero(ptr, sizeof(...)).
9447   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9448   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
9449     return;
9450 
9451   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
9452     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
9453     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
9454 
9455     QualType DestTy = Dest->getType();
9456     QualType PointeeTy;
9457     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
9458       PointeeTy = DestPtrTy->getPointeeType();
9459 
9460       // Never warn about void type pointers. This can be used to suppress
9461       // false positives.
9462       if (PointeeTy->isVoidType())
9463         continue;
9464 
9465       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
9466       // actually comparing the expressions for equality. Because computing the
9467       // expression IDs can be expensive, we only do this if the diagnostic is
9468       // enabled.
9469       if (SizeOfArg &&
9470           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
9471                            SizeOfArg->getExprLoc())) {
9472         // We only compute IDs for expressions if the warning is enabled, and
9473         // cache the sizeof arg's ID.
9474         if (SizeOfArgID == llvm::FoldingSetNodeID())
9475           SizeOfArg->Profile(SizeOfArgID, Context, true);
9476         llvm::FoldingSetNodeID DestID;
9477         Dest->Profile(DestID, Context, true);
9478         if (DestID == SizeOfArgID) {
9479           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
9480           //       over sizeof(src) as well.
9481           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
9482           StringRef ReadableName = FnName->getName();
9483 
9484           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
9485             if (UnaryOp->getOpcode() == UO_AddrOf)
9486               ActionIdx = 1; // If its an address-of operator, just remove it.
9487           if (!PointeeTy->isIncompleteType() &&
9488               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
9489             ActionIdx = 2; // If the pointee's size is sizeof(char),
9490                            // suggest an explicit length.
9491 
9492           // If the function is defined as a builtin macro, do not show macro
9493           // expansion.
9494           SourceLocation SL = SizeOfArg->getExprLoc();
9495           SourceRange DSR = Dest->getSourceRange();
9496           SourceRange SSR = SizeOfArg->getSourceRange();
9497           SourceManager &SM = getSourceManager();
9498 
9499           if (SM.isMacroArgExpansion(SL)) {
9500             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
9501             SL = SM.getSpellingLoc(SL);
9502             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
9503                              SM.getSpellingLoc(DSR.getEnd()));
9504             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
9505                              SM.getSpellingLoc(SSR.getEnd()));
9506           }
9507 
9508           DiagRuntimeBehavior(SL, SizeOfArg,
9509                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
9510                                 << ReadableName
9511                                 << PointeeTy
9512                                 << DestTy
9513                                 << DSR
9514                                 << SSR);
9515           DiagRuntimeBehavior(SL, SizeOfArg,
9516                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
9517                                 << ActionIdx
9518                                 << SSR);
9519 
9520           break;
9521         }
9522       }
9523 
9524       // Also check for cases where the sizeof argument is the exact same
9525       // type as the memory argument, and where it points to a user-defined
9526       // record type.
9527       if (SizeOfArgTy != QualType()) {
9528         if (PointeeTy->isRecordType() &&
9529             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
9530           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
9531                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
9532                                 << FnName << SizeOfArgTy << ArgIdx
9533                                 << PointeeTy << Dest->getSourceRange()
9534                                 << LenExpr->getSourceRange());
9535           break;
9536         }
9537       }
9538     } else if (DestTy->isArrayType()) {
9539       PointeeTy = DestTy;
9540     }
9541 
9542     if (PointeeTy == QualType())
9543       continue;
9544 
9545     // Always complain about dynamic classes.
9546     bool IsContained;
9547     if (const CXXRecordDecl *ContainedRD =
9548             getContainedDynamicClass(PointeeTy, IsContained)) {
9549 
9550       unsigned OperationType = 0;
9551       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
9552       // "overwritten" if we're warning about the destination for any call
9553       // but memcmp; otherwise a verb appropriate to the call.
9554       if (ArgIdx != 0 || IsCmp) {
9555         if (BId == Builtin::BImemcpy)
9556           OperationType = 1;
9557         else if(BId == Builtin::BImemmove)
9558           OperationType = 2;
9559         else if (IsCmp)
9560           OperationType = 3;
9561       }
9562 
9563       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9564                           PDiag(diag::warn_dyn_class_memaccess)
9565                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
9566                               << IsContained << ContainedRD << OperationType
9567                               << Call->getCallee()->getSourceRange());
9568     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
9569              BId != Builtin::BImemset)
9570       DiagRuntimeBehavior(
9571         Dest->getExprLoc(), Dest,
9572         PDiag(diag::warn_arc_object_memaccess)
9573           << ArgIdx << FnName << PointeeTy
9574           << Call->getCallee()->getSourceRange());
9575     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
9576       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
9577           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
9578         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9579                             PDiag(diag::warn_cstruct_memaccess)
9580                                 << ArgIdx << FnName << PointeeTy << 0);
9581         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
9582       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
9583                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
9584         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9585                             PDiag(diag::warn_cstruct_memaccess)
9586                                 << ArgIdx << FnName << PointeeTy << 1);
9587         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
9588       } else {
9589         continue;
9590       }
9591     } else
9592       continue;
9593 
9594     DiagRuntimeBehavior(
9595       Dest->getExprLoc(), Dest,
9596       PDiag(diag::note_bad_memaccess_silence)
9597         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
9598     break;
9599   }
9600 }
9601 
9602 // A little helper routine: ignore addition and subtraction of integer literals.
9603 // This intentionally does not ignore all integer constant expressions because
9604 // we don't want to remove sizeof().
9605 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
9606   Ex = Ex->IgnoreParenCasts();
9607 
9608   while (true) {
9609     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
9610     if (!BO || !BO->isAdditiveOp())
9611       break;
9612 
9613     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
9614     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
9615 
9616     if (isa<IntegerLiteral>(RHS))
9617       Ex = LHS;
9618     else if (isa<IntegerLiteral>(LHS))
9619       Ex = RHS;
9620     else
9621       break;
9622   }
9623 
9624   return Ex;
9625 }
9626 
9627 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
9628                                                       ASTContext &Context) {
9629   // Only handle constant-sized or VLAs, but not flexible members.
9630   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
9631     // Only issue the FIXIT for arrays of size > 1.
9632     if (CAT->getSize().getSExtValue() <= 1)
9633       return false;
9634   } else if (!Ty->isVariableArrayType()) {
9635     return false;
9636   }
9637   return true;
9638 }
9639 
9640 // Warn if the user has made the 'size' argument to strlcpy or strlcat
9641 // be the size of the source, instead of the destination.
9642 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
9643                                     IdentifierInfo *FnName) {
9644 
9645   // Don't crash if the user has the wrong number of arguments
9646   unsigned NumArgs = Call->getNumArgs();
9647   if ((NumArgs != 3) && (NumArgs != 4))
9648     return;
9649 
9650   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
9651   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
9652   const Expr *CompareWithSrc = nullptr;
9653 
9654   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
9655                                      Call->getBeginLoc(), Call->getRParenLoc()))
9656     return;
9657 
9658   // Look for 'strlcpy(dst, x, sizeof(x))'
9659   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
9660     CompareWithSrc = Ex;
9661   else {
9662     // Look for 'strlcpy(dst, x, strlen(x))'
9663     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
9664       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
9665           SizeCall->getNumArgs() == 1)
9666         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
9667     }
9668   }
9669 
9670   if (!CompareWithSrc)
9671     return;
9672 
9673   // Determine if the argument to sizeof/strlen is equal to the source
9674   // argument.  In principle there's all kinds of things you could do
9675   // here, for instance creating an == expression and evaluating it with
9676   // EvaluateAsBooleanCondition, but this uses a more direct technique:
9677   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
9678   if (!SrcArgDRE)
9679     return;
9680 
9681   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
9682   if (!CompareWithSrcDRE ||
9683       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
9684     return;
9685 
9686   const Expr *OriginalSizeArg = Call->getArg(2);
9687   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
9688       << OriginalSizeArg->getSourceRange() << FnName;
9689 
9690   // Output a FIXIT hint if the destination is an array (rather than a
9691   // pointer to an array).  This could be enhanced to handle some
9692   // pointers if we know the actual size, like if DstArg is 'array+2'
9693   // we could say 'sizeof(array)-2'.
9694   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
9695   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
9696     return;
9697 
9698   SmallString<128> sizeString;
9699   llvm::raw_svector_ostream OS(sizeString);
9700   OS << "sizeof(";
9701   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9702   OS << ")";
9703 
9704   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
9705       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
9706                                       OS.str());
9707 }
9708 
9709 /// Check if two expressions refer to the same declaration.
9710 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
9711   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
9712     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
9713       return D1->getDecl() == D2->getDecl();
9714   return false;
9715 }
9716 
9717 static const Expr *getStrlenExprArg(const Expr *E) {
9718   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9719     const FunctionDecl *FD = CE->getDirectCallee();
9720     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
9721       return nullptr;
9722     return CE->getArg(0)->IgnoreParenCasts();
9723   }
9724   return nullptr;
9725 }
9726 
9727 // Warn on anti-patterns as the 'size' argument to strncat.
9728 // The correct size argument should look like following:
9729 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
9730 void Sema::CheckStrncatArguments(const CallExpr *CE,
9731                                  IdentifierInfo *FnName) {
9732   // Don't crash if the user has the wrong number of arguments.
9733   if (CE->getNumArgs() < 3)
9734     return;
9735   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
9736   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
9737   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
9738 
9739   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
9740                                      CE->getRParenLoc()))
9741     return;
9742 
9743   // Identify common expressions, which are wrongly used as the size argument
9744   // to strncat and may lead to buffer overflows.
9745   unsigned PatternType = 0;
9746   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
9747     // - sizeof(dst)
9748     if (referToTheSameDecl(SizeOfArg, DstArg))
9749       PatternType = 1;
9750     // - sizeof(src)
9751     else if (referToTheSameDecl(SizeOfArg, SrcArg))
9752       PatternType = 2;
9753   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
9754     if (BE->getOpcode() == BO_Sub) {
9755       const Expr *L = BE->getLHS()->IgnoreParenCasts();
9756       const Expr *R = BE->getRHS()->IgnoreParenCasts();
9757       // - sizeof(dst) - strlen(dst)
9758       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
9759           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
9760         PatternType = 1;
9761       // - sizeof(src) - (anything)
9762       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
9763         PatternType = 2;
9764     }
9765   }
9766 
9767   if (PatternType == 0)
9768     return;
9769 
9770   // Generate the diagnostic.
9771   SourceLocation SL = LenArg->getBeginLoc();
9772   SourceRange SR = LenArg->getSourceRange();
9773   SourceManager &SM = getSourceManager();
9774 
9775   // If the function is defined as a builtin macro, do not show macro expansion.
9776   if (SM.isMacroArgExpansion(SL)) {
9777     SL = SM.getSpellingLoc(SL);
9778     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
9779                      SM.getSpellingLoc(SR.getEnd()));
9780   }
9781 
9782   // Check if the destination is an array (rather than a pointer to an array).
9783   QualType DstTy = DstArg->getType();
9784   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
9785                                                                     Context);
9786   if (!isKnownSizeArray) {
9787     if (PatternType == 1)
9788       Diag(SL, diag::warn_strncat_wrong_size) << SR;
9789     else
9790       Diag(SL, diag::warn_strncat_src_size) << SR;
9791     return;
9792   }
9793 
9794   if (PatternType == 1)
9795     Diag(SL, diag::warn_strncat_large_size) << SR;
9796   else
9797     Diag(SL, diag::warn_strncat_src_size) << SR;
9798 
9799   SmallString<128> sizeString;
9800   llvm::raw_svector_ostream OS(sizeString);
9801   OS << "sizeof(";
9802   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9803   OS << ") - ";
9804   OS << "strlen(";
9805   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9806   OS << ") - 1";
9807 
9808   Diag(SL, diag::note_strncat_wrong_size)
9809     << FixItHint::CreateReplacement(SR, OS.str());
9810 }
9811 
9812 void
9813 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
9814                          SourceLocation ReturnLoc,
9815                          bool isObjCMethod,
9816                          const AttrVec *Attrs,
9817                          const FunctionDecl *FD) {
9818   // Check if the return value is null but should not be.
9819   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
9820        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
9821       CheckNonNullExpr(*this, RetValExp))
9822     Diag(ReturnLoc, diag::warn_null_ret)
9823       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
9824 
9825   // C++11 [basic.stc.dynamic.allocation]p4:
9826   //   If an allocation function declared with a non-throwing
9827   //   exception-specification fails to allocate storage, it shall return
9828   //   a null pointer. Any other allocation function that fails to allocate
9829   //   storage shall indicate failure only by throwing an exception [...]
9830   if (FD) {
9831     OverloadedOperatorKind Op = FD->getOverloadedOperator();
9832     if (Op == OO_New || Op == OO_Array_New) {
9833       const FunctionProtoType *Proto
9834         = FD->getType()->castAs<FunctionProtoType>();
9835       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
9836           CheckNonNullExpr(*this, RetValExp))
9837         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
9838           << FD << getLangOpts().CPlusPlus11;
9839     }
9840   }
9841 }
9842 
9843 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
9844 
9845 /// Check for comparisons of floating point operands using != and ==.
9846 /// Issue a warning if these are no self-comparisons, as they are not likely
9847 /// to do what the programmer intended.
9848 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
9849   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
9850   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
9851 
9852   // Special case: check for x == x (which is OK).
9853   // Do not emit warnings for such cases.
9854   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
9855     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
9856       if (DRL->getDecl() == DRR->getDecl())
9857         return;
9858 
9859   // Special case: check for comparisons against literals that can be exactly
9860   //  represented by APFloat.  In such cases, do not emit a warning.  This
9861   //  is a heuristic: often comparison against such literals are used to
9862   //  detect if a value in a variable has not changed.  This clearly can
9863   //  lead to false negatives.
9864   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
9865     if (FLL->isExact())
9866       return;
9867   } else
9868     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
9869       if (FLR->isExact())
9870         return;
9871 
9872   // Check for comparisons with builtin types.
9873   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
9874     if (CL->getBuiltinCallee())
9875       return;
9876 
9877   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
9878     if (CR->getBuiltinCallee())
9879       return;
9880 
9881   // Emit the diagnostic.
9882   Diag(Loc, diag::warn_floatingpoint_eq)
9883     << LHS->getSourceRange() << RHS->getSourceRange();
9884 }
9885 
9886 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
9887 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
9888 
9889 namespace {
9890 
9891 /// Structure recording the 'active' range of an integer-valued
9892 /// expression.
9893 struct IntRange {
9894   /// The number of bits active in the int.
9895   unsigned Width;
9896 
9897   /// True if the int is known not to have negative values.
9898   bool NonNegative;
9899 
9900   IntRange(unsigned Width, bool NonNegative)
9901       : Width(Width), NonNegative(NonNegative) {}
9902 
9903   /// Returns the range of the bool type.
9904   static IntRange forBoolType() {
9905     return IntRange(1, true);
9906   }
9907 
9908   /// Returns the range of an opaque value of the given integral type.
9909   static IntRange forValueOfType(ASTContext &C, QualType T) {
9910     return forValueOfCanonicalType(C,
9911                           T->getCanonicalTypeInternal().getTypePtr());
9912   }
9913 
9914   /// Returns the range of an opaque value of a canonical integral type.
9915   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
9916     assert(T->isCanonicalUnqualified());
9917 
9918     if (const VectorType *VT = dyn_cast<VectorType>(T))
9919       T = VT->getElementType().getTypePtr();
9920     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9921       T = CT->getElementType().getTypePtr();
9922     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9923       T = AT->getValueType().getTypePtr();
9924 
9925     if (!C.getLangOpts().CPlusPlus) {
9926       // For enum types in C code, use the underlying datatype.
9927       if (const EnumType *ET = dyn_cast<EnumType>(T))
9928         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
9929     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
9930       // For enum types in C++, use the known bit width of the enumerators.
9931       EnumDecl *Enum = ET->getDecl();
9932       // In C++11, enums can have a fixed underlying type. Use this type to
9933       // compute the range.
9934       if (Enum->isFixed()) {
9935         return IntRange(C.getIntWidth(QualType(T, 0)),
9936                         !ET->isSignedIntegerOrEnumerationType());
9937       }
9938 
9939       unsigned NumPositive = Enum->getNumPositiveBits();
9940       unsigned NumNegative = Enum->getNumNegativeBits();
9941 
9942       if (NumNegative == 0)
9943         return IntRange(NumPositive, true/*NonNegative*/);
9944       else
9945         return IntRange(std::max(NumPositive + 1, NumNegative),
9946                         false/*NonNegative*/);
9947     }
9948 
9949     if (const auto *EIT = dyn_cast<ExtIntType>(T))
9950       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
9951 
9952     const BuiltinType *BT = cast<BuiltinType>(T);
9953     assert(BT->isInteger());
9954 
9955     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9956   }
9957 
9958   /// Returns the "target" range of a canonical integral type, i.e.
9959   /// the range of values expressible in the type.
9960   ///
9961   /// This matches forValueOfCanonicalType except that enums have the
9962   /// full range of their type, not the range of their enumerators.
9963   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
9964     assert(T->isCanonicalUnqualified());
9965 
9966     if (const VectorType *VT = dyn_cast<VectorType>(T))
9967       T = VT->getElementType().getTypePtr();
9968     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9969       T = CT->getElementType().getTypePtr();
9970     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9971       T = AT->getValueType().getTypePtr();
9972     if (const EnumType *ET = dyn_cast<EnumType>(T))
9973       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
9974 
9975     if (const auto *EIT = dyn_cast<ExtIntType>(T))
9976       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
9977 
9978     const BuiltinType *BT = cast<BuiltinType>(T);
9979     assert(BT->isInteger());
9980 
9981     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9982   }
9983 
9984   /// Returns the supremum of two ranges: i.e. their conservative merge.
9985   static IntRange join(IntRange L, IntRange R) {
9986     return IntRange(std::max(L.Width, R.Width),
9987                     L.NonNegative && R.NonNegative);
9988   }
9989 
9990   /// Returns the infinum of two ranges: i.e. their aggressive merge.
9991   static IntRange meet(IntRange L, IntRange R) {
9992     return IntRange(std::min(L.Width, R.Width),
9993                     L.NonNegative || R.NonNegative);
9994   }
9995 };
9996 
9997 } // namespace
9998 
9999 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
10000                               unsigned MaxWidth) {
10001   if (value.isSigned() && value.isNegative())
10002     return IntRange(value.getMinSignedBits(), false);
10003 
10004   if (value.getBitWidth() > MaxWidth)
10005     value = value.trunc(MaxWidth);
10006 
10007   // isNonNegative() just checks the sign bit without considering
10008   // signedness.
10009   return IntRange(value.getActiveBits(), true);
10010 }
10011 
10012 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
10013                               unsigned MaxWidth) {
10014   if (result.isInt())
10015     return GetValueRange(C, result.getInt(), MaxWidth);
10016 
10017   if (result.isVector()) {
10018     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
10019     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
10020       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
10021       R = IntRange::join(R, El);
10022     }
10023     return R;
10024   }
10025 
10026   if (result.isComplexInt()) {
10027     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
10028     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
10029     return IntRange::join(R, I);
10030   }
10031 
10032   // This can happen with lossless casts to intptr_t of "based" lvalues.
10033   // Assume it might use arbitrary bits.
10034   // FIXME: The only reason we need to pass the type in here is to get
10035   // the sign right on this one case.  It would be nice if APValue
10036   // preserved this.
10037   assert(result.isLValue() || result.isAddrLabelDiff());
10038   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
10039 }
10040 
10041 static QualType GetExprType(const Expr *E) {
10042   QualType Ty = E->getType();
10043   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
10044     Ty = AtomicRHS->getValueType();
10045   return Ty;
10046 }
10047 
10048 /// Pseudo-evaluate the given integer expression, estimating the
10049 /// range of values it might take.
10050 ///
10051 /// \param MaxWidth - the width to which the value will be truncated
10052 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
10053                              bool InConstantContext) {
10054   E = E->IgnoreParens();
10055 
10056   // Try a full evaluation first.
10057   Expr::EvalResult result;
10058   if (E->EvaluateAsRValue(result, C, InConstantContext))
10059     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
10060 
10061   // I think we only want to look through implicit casts here; if the
10062   // user has an explicit widening cast, we should treat the value as
10063   // being of the new, wider type.
10064   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
10065     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
10066       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext);
10067 
10068     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
10069 
10070     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
10071                          CE->getCastKind() == CK_BooleanToSignedIntegral;
10072 
10073     // Assume that non-integer casts can span the full range of the type.
10074     if (!isIntegerCast)
10075       return OutputTypeRange;
10076 
10077     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
10078                                      std::min(MaxWidth, OutputTypeRange.Width),
10079                                      InConstantContext);
10080 
10081     // Bail out if the subexpr's range is as wide as the cast type.
10082     if (SubRange.Width >= OutputTypeRange.Width)
10083       return OutputTypeRange;
10084 
10085     // Otherwise, we take the smaller width, and we're non-negative if
10086     // either the output type or the subexpr is.
10087     return IntRange(SubRange.Width,
10088                     SubRange.NonNegative || OutputTypeRange.NonNegative);
10089   }
10090 
10091   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
10092     // If we can fold the condition, just take that operand.
10093     bool CondResult;
10094     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
10095       return GetExprRange(C,
10096                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
10097                           MaxWidth, InConstantContext);
10098 
10099     // Otherwise, conservatively merge.
10100     IntRange L =
10101         GetExprRange(C, CO->getTrueExpr(), MaxWidth, InConstantContext);
10102     IntRange R =
10103         GetExprRange(C, CO->getFalseExpr(), MaxWidth, InConstantContext);
10104     return IntRange::join(L, R);
10105   }
10106 
10107   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
10108     switch (BO->getOpcode()) {
10109     case BO_Cmp:
10110       llvm_unreachable("builtin <=> should have class type");
10111 
10112     // Boolean-valued operations are single-bit and positive.
10113     case BO_LAnd:
10114     case BO_LOr:
10115     case BO_LT:
10116     case BO_GT:
10117     case BO_LE:
10118     case BO_GE:
10119     case BO_EQ:
10120     case BO_NE:
10121       return IntRange::forBoolType();
10122 
10123     // The type of the assignments is the type of the LHS, so the RHS
10124     // is not necessarily the same type.
10125     case BO_MulAssign:
10126     case BO_DivAssign:
10127     case BO_RemAssign:
10128     case BO_AddAssign:
10129     case BO_SubAssign:
10130     case BO_XorAssign:
10131     case BO_OrAssign:
10132       // TODO: bitfields?
10133       return IntRange::forValueOfType(C, GetExprType(E));
10134 
10135     // Simple assignments just pass through the RHS, which will have
10136     // been coerced to the LHS type.
10137     case BO_Assign:
10138       // TODO: bitfields?
10139       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10140 
10141     // Operations with opaque sources are black-listed.
10142     case BO_PtrMemD:
10143     case BO_PtrMemI:
10144       return IntRange::forValueOfType(C, GetExprType(E));
10145 
10146     // Bitwise-and uses the *infinum* of the two source ranges.
10147     case BO_And:
10148     case BO_AndAssign:
10149       return IntRange::meet(
10150           GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext),
10151           GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext));
10152 
10153     // Left shift gets black-listed based on a judgement call.
10154     case BO_Shl:
10155       // ...except that we want to treat '1 << (blah)' as logically
10156       // positive.  It's an important idiom.
10157       if (IntegerLiteral *I
10158             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
10159         if (I->getValue() == 1) {
10160           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
10161           return IntRange(R.Width, /*NonNegative*/ true);
10162         }
10163       }
10164       LLVM_FALLTHROUGH;
10165 
10166     case BO_ShlAssign:
10167       return IntRange::forValueOfType(C, GetExprType(E));
10168 
10169     // Right shift by a constant can narrow its left argument.
10170     case BO_Shr:
10171     case BO_ShrAssign: {
10172       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
10173 
10174       // If the shift amount is a positive constant, drop the width by
10175       // that much.
10176       llvm::APSInt shift;
10177       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
10178           shift.isNonNegative()) {
10179         unsigned zext = shift.getZExtValue();
10180         if (zext >= L.Width)
10181           L.Width = (L.NonNegative ? 0 : 1);
10182         else
10183           L.Width -= zext;
10184       }
10185 
10186       return L;
10187     }
10188 
10189     // Comma acts as its right operand.
10190     case BO_Comma:
10191       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10192 
10193     // Black-list pointer subtractions.
10194     case BO_Sub:
10195       if (BO->getLHS()->getType()->isPointerType())
10196         return IntRange::forValueOfType(C, GetExprType(E));
10197       break;
10198 
10199     // The width of a division result is mostly determined by the size
10200     // of the LHS.
10201     case BO_Div: {
10202       // Don't 'pre-truncate' the operands.
10203       unsigned opWidth = C.getIntWidth(GetExprType(E));
10204       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
10205 
10206       // If the divisor is constant, use that.
10207       llvm::APSInt divisor;
10208       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
10209         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
10210         if (log2 >= L.Width)
10211           L.Width = (L.NonNegative ? 0 : 1);
10212         else
10213           L.Width = std::min(L.Width - log2, MaxWidth);
10214         return L;
10215       }
10216 
10217       // Otherwise, just use the LHS's width.
10218       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
10219       return IntRange(L.Width, L.NonNegative && R.NonNegative);
10220     }
10221 
10222     // The result of a remainder can't be larger than the result of
10223     // either side.
10224     case BO_Rem: {
10225       // Don't 'pre-truncate' the operands.
10226       unsigned opWidth = C.getIntWidth(GetExprType(E));
10227       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
10228       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
10229 
10230       IntRange meet = IntRange::meet(L, R);
10231       meet.Width = std::min(meet.Width, MaxWidth);
10232       return meet;
10233     }
10234 
10235     // The default behavior is okay for these.
10236     case BO_Mul:
10237     case BO_Add:
10238     case BO_Xor:
10239     case BO_Or:
10240       break;
10241     }
10242 
10243     // The default case is to treat the operation as if it were closed
10244     // on the narrowest type that encompasses both operands.
10245     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
10246     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10247     return IntRange::join(L, R);
10248   }
10249 
10250   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
10251     switch (UO->getOpcode()) {
10252     // Boolean-valued operations are white-listed.
10253     case UO_LNot:
10254       return IntRange::forBoolType();
10255 
10256     // Operations with opaque sources are black-listed.
10257     case UO_Deref:
10258     case UO_AddrOf: // should be impossible
10259       return IntRange::forValueOfType(C, GetExprType(E));
10260 
10261     default:
10262       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext);
10263     }
10264   }
10265 
10266   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
10267     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext);
10268 
10269   if (const auto *BitField = E->getSourceBitField())
10270     return IntRange(BitField->getBitWidthValue(C),
10271                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
10272 
10273   return IntRange::forValueOfType(C, GetExprType(E));
10274 }
10275 
10276 static IntRange GetExprRange(ASTContext &C, const Expr *E,
10277                              bool InConstantContext) {
10278   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext);
10279 }
10280 
10281 /// Checks whether the given value, which currently has the given
10282 /// source semantics, has the same value when coerced through the
10283 /// target semantics.
10284 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
10285                                  const llvm::fltSemantics &Src,
10286                                  const llvm::fltSemantics &Tgt) {
10287   llvm::APFloat truncated = value;
10288 
10289   bool ignored;
10290   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
10291   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
10292 
10293   return truncated.bitwiseIsEqual(value);
10294 }
10295 
10296 /// Checks whether the given value, which currently has the given
10297 /// source semantics, has the same value when coerced through the
10298 /// target semantics.
10299 ///
10300 /// The value might be a vector of floats (or a complex number).
10301 static bool IsSameFloatAfterCast(const APValue &value,
10302                                  const llvm::fltSemantics &Src,
10303                                  const llvm::fltSemantics &Tgt) {
10304   if (value.isFloat())
10305     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
10306 
10307   if (value.isVector()) {
10308     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
10309       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
10310         return false;
10311     return true;
10312   }
10313 
10314   assert(value.isComplexFloat());
10315   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
10316           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
10317 }
10318 
10319 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
10320                                        bool IsListInit = false);
10321 
10322 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
10323   // Suppress cases where we are comparing against an enum constant.
10324   if (const DeclRefExpr *DR =
10325       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
10326     if (isa<EnumConstantDecl>(DR->getDecl()))
10327       return true;
10328 
10329   // Suppress cases where the value is expanded from a macro, unless that macro
10330   // is how a language represents a boolean literal. This is the case in both C
10331   // and Objective-C.
10332   SourceLocation BeginLoc = E->getBeginLoc();
10333   if (BeginLoc.isMacroID()) {
10334     StringRef MacroName = Lexer::getImmediateMacroName(
10335         BeginLoc, S.getSourceManager(), S.getLangOpts());
10336     return MacroName != "YES" && MacroName != "NO" &&
10337            MacroName != "true" && MacroName != "false";
10338   }
10339 
10340   return false;
10341 }
10342 
10343 static bool isKnownToHaveUnsignedValue(Expr *E) {
10344   return E->getType()->isIntegerType() &&
10345          (!E->getType()->isSignedIntegerType() ||
10346           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
10347 }
10348 
10349 namespace {
10350 /// The promoted range of values of a type. In general this has the
10351 /// following structure:
10352 ///
10353 ///     |-----------| . . . |-----------|
10354 ///     ^           ^       ^           ^
10355 ///    Min       HoleMin  HoleMax      Max
10356 ///
10357 /// ... where there is only a hole if a signed type is promoted to unsigned
10358 /// (in which case Min and Max are the smallest and largest representable
10359 /// values).
10360 struct PromotedRange {
10361   // Min, or HoleMax if there is a hole.
10362   llvm::APSInt PromotedMin;
10363   // Max, or HoleMin if there is a hole.
10364   llvm::APSInt PromotedMax;
10365 
10366   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
10367     if (R.Width == 0)
10368       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
10369     else if (R.Width >= BitWidth && !Unsigned) {
10370       // Promotion made the type *narrower*. This happens when promoting
10371       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
10372       // Treat all values of 'signed int' as being in range for now.
10373       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
10374       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
10375     } else {
10376       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
10377                         .extOrTrunc(BitWidth);
10378       PromotedMin.setIsUnsigned(Unsigned);
10379 
10380       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
10381                         .extOrTrunc(BitWidth);
10382       PromotedMax.setIsUnsigned(Unsigned);
10383     }
10384   }
10385 
10386   // Determine whether this range is contiguous (has no hole).
10387   bool isContiguous() const { return PromotedMin <= PromotedMax; }
10388 
10389   // Where a constant value is within the range.
10390   enum ComparisonResult {
10391     LT = 0x1,
10392     LE = 0x2,
10393     GT = 0x4,
10394     GE = 0x8,
10395     EQ = 0x10,
10396     NE = 0x20,
10397     InRangeFlag = 0x40,
10398 
10399     Less = LE | LT | NE,
10400     Min = LE | InRangeFlag,
10401     InRange = InRangeFlag,
10402     Max = GE | InRangeFlag,
10403     Greater = GE | GT | NE,
10404 
10405     OnlyValue = LE | GE | EQ | InRangeFlag,
10406     InHole = NE
10407   };
10408 
10409   ComparisonResult compare(const llvm::APSInt &Value) const {
10410     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
10411            Value.isUnsigned() == PromotedMin.isUnsigned());
10412     if (!isContiguous()) {
10413       assert(Value.isUnsigned() && "discontiguous range for signed compare");
10414       if (Value.isMinValue()) return Min;
10415       if (Value.isMaxValue()) return Max;
10416       if (Value >= PromotedMin) return InRange;
10417       if (Value <= PromotedMax) return InRange;
10418       return InHole;
10419     }
10420 
10421     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
10422     case -1: return Less;
10423     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
10424     case 1:
10425       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
10426       case -1: return InRange;
10427       case 0: return Max;
10428       case 1: return Greater;
10429       }
10430     }
10431 
10432     llvm_unreachable("impossible compare result");
10433   }
10434 
10435   static llvm::Optional<StringRef>
10436   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
10437     if (Op == BO_Cmp) {
10438       ComparisonResult LTFlag = LT, GTFlag = GT;
10439       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
10440 
10441       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
10442       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
10443       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
10444       return llvm::None;
10445     }
10446 
10447     ComparisonResult TrueFlag, FalseFlag;
10448     if (Op == BO_EQ) {
10449       TrueFlag = EQ;
10450       FalseFlag = NE;
10451     } else if (Op == BO_NE) {
10452       TrueFlag = NE;
10453       FalseFlag = EQ;
10454     } else {
10455       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
10456         TrueFlag = LT;
10457         FalseFlag = GE;
10458       } else {
10459         TrueFlag = GT;
10460         FalseFlag = LE;
10461       }
10462       if (Op == BO_GE || Op == BO_LE)
10463         std::swap(TrueFlag, FalseFlag);
10464     }
10465     if (R & TrueFlag)
10466       return StringRef("true");
10467     if (R & FalseFlag)
10468       return StringRef("false");
10469     return llvm::None;
10470   }
10471 };
10472 }
10473 
10474 static bool HasEnumType(Expr *E) {
10475   // Strip off implicit integral promotions.
10476   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
10477     if (ICE->getCastKind() != CK_IntegralCast &&
10478         ICE->getCastKind() != CK_NoOp)
10479       break;
10480     E = ICE->getSubExpr();
10481   }
10482 
10483   return E->getType()->isEnumeralType();
10484 }
10485 
10486 static int classifyConstantValue(Expr *Constant) {
10487   // The values of this enumeration are used in the diagnostics
10488   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
10489   enum ConstantValueKind {
10490     Miscellaneous = 0,
10491     LiteralTrue,
10492     LiteralFalse
10493   };
10494   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
10495     return BL->getValue() ? ConstantValueKind::LiteralTrue
10496                           : ConstantValueKind::LiteralFalse;
10497   return ConstantValueKind::Miscellaneous;
10498 }
10499 
10500 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
10501                                         Expr *Constant, Expr *Other,
10502                                         const llvm::APSInt &Value,
10503                                         bool RhsConstant) {
10504   if (S.inTemplateInstantiation())
10505     return false;
10506 
10507   Expr *OriginalOther = Other;
10508 
10509   Constant = Constant->IgnoreParenImpCasts();
10510   Other = Other->IgnoreParenImpCasts();
10511 
10512   // Suppress warnings on tautological comparisons between values of the same
10513   // enumeration type. There are only two ways we could warn on this:
10514   //  - If the constant is outside the range of representable values of
10515   //    the enumeration. In such a case, we should warn about the cast
10516   //    to enumeration type, not about the comparison.
10517   //  - If the constant is the maximum / minimum in-range value. For an
10518   //    enumeratin type, such comparisons can be meaningful and useful.
10519   if (Constant->getType()->isEnumeralType() &&
10520       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
10521     return false;
10522 
10523   // TODO: Investigate using GetExprRange() to get tighter bounds
10524   // on the bit ranges.
10525   QualType OtherT = Other->getType();
10526   if (const auto *AT = OtherT->getAs<AtomicType>())
10527     OtherT = AT->getValueType();
10528   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
10529 
10530   // Special case for ObjC BOOL on targets where its a typedef for a signed char
10531   // (Namely, macOS).
10532   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
10533                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
10534                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
10535 
10536   // Whether we're treating Other as being a bool because of the form of
10537   // expression despite it having another type (typically 'int' in C).
10538   bool OtherIsBooleanDespiteType =
10539       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
10540   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
10541     OtherRange = IntRange::forBoolType();
10542 
10543   // Determine the promoted range of the other type and see if a comparison of
10544   // the constant against that range is tautological.
10545   PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
10546                                    Value.isUnsigned());
10547   auto Cmp = OtherPromotedRange.compare(Value);
10548   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
10549   if (!Result)
10550     return false;
10551 
10552   // Suppress the diagnostic for an in-range comparison if the constant comes
10553   // from a macro or enumerator. We don't want to diagnose
10554   //
10555   //   some_long_value <= INT_MAX
10556   //
10557   // when sizeof(int) == sizeof(long).
10558   bool InRange = Cmp & PromotedRange::InRangeFlag;
10559   if (InRange && IsEnumConstOrFromMacro(S, Constant))
10560     return false;
10561 
10562   // If this is a comparison to an enum constant, include that
10563   // constant in the diagnostic.
10564   const EnumConstantDecl *ED = nullptr;
10565   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
10566     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
10567 
10568   // Should be enough for uint128 (39 decimal digits)
10569   SmallString<64> PrettySourceValue;
10570   llvm::raw_svector_ostream OS(PrettySourceValue);
10571   if (ED) {
10572     OS << '\'' << *ED << "' (" << Value << ")";
10573   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
10574                Constant->IgnoreParenImpCasts())) {
10575     OS << (BL->getValue() ? "YES" : "NO");
10576   } else {
10577     OS << Value;
10578   }
10579 
10580   if (IsObjCSignedCharBool) {
10581     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10582                           S.PDiag(diag::warn_tautological_compare_objc_bool)
10583                               << OS.str() << *Result);
10584     return true;
10585   }
10586 
10587   // FIXME: We use a somewhat different formatting for the in-range cases and
10588   // cases involving boolean values for historical reasons. We should pick a
10589   // consistent way of presenting these diagnostics.
10590   if (!InRange || Other->isKnownToHaveBooleanValue()) {
10591 
10592     S.DiagRuntimeBehavior(
10593         E->getOperatorLoc(), E,
10594         S.PDiag(!InRange ? diag::warn_out_of_range_compare
10595                          : diag::warn_tautological_bool_compare)
10596             << OS.str() << classifyConstantValue(Constant) << OtherT
10597             << OtherIsBooleanDespiteType << *Result
10598             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
10599   } else {
10600     unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
10601                         ? (HasEnumType(OriginalOther)
10602                                ? diag::warn_unsigned_enum_always_true_comparison
10603                                : diag::warn_unsigned_always_true_comparison)
10604                         : diag::warn_tautological_constant_compare;
10605 
10606     S.Diag(E->getOperatorLoc(), Diag)
10607         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
10608         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
10609   }
10610 
10611   return true;
10612 }
10613 
10614 /// Analyze the operands of the given comparison.  Implements the
10615 /// fallback case from AnalyzeComparison.
10616 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
10617   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10618   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10619 }
10620 
10621 /// Implements -Wsign-compare.
10622 ///
10623 /// \param E the binary operator to check for warnings
10624 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
10625   // The type the comparison is being performed in.
10626   QualType T = E->getLHS()->getType();
10627 
10628   // Only analyze comparison operators where both sides have been converted to
10629   // the same type.
10630   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
10631     return AnalyzeImpConvsInComparison(S, E);
10632 
10633   // Don't analyze value-dependent comparisons directly.
10634   if (E->isValueDependent())
10635     return AnalyzeImpConvsInComparison(S, E);
10636 
10637   Expr *LHS = E->getLHS();
10638   Expr *RHS = E->getRHS();
10639 
10640   if (T->isIntegralType(S.Context)) {
10641     llvm::APSInt RHSValue;
10642     llvm::APSInt LHSValue;
10643 
10644     bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
10645     bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
10646 
10647     // We don't care about expressions whose result is a constant.
10648     if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
10649       return AnalyzeImpConvsInComparison(S, E);
10650 
10651     // We only care about expressions where just one side is literal
10652     if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
10653       // Is the constant on the RHS or LHS?
10654       const bool RhsConstant = IsRHSIntegralLiteral;
10655       Expr *Const = RhsConstant ? RHS : LHS;
10656       Expr *Other = RhsConstant ? LHS : RHS;
10657       const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
10658 
10659       // Check whether an integer constant comparison results in a value
10660       // of 'true' or 'false'.
10661       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
10662         return AnalyzeImpConvsInComparison(S, E);
10663     }
10664   }
10665 
10666   if (!T->hasUnsignedIntegerRepresentation()) {
10667     // We don't do anything special if this isn't an unsigned integral
10668     // comparison:  we're only interested in integral comparisons, and
10669     // signed comparisons only happen in cases we don't care to warn about.
10670     return AnalyzeImpConvsInComparison(S, E);
10671   }
10672 
10673   LHS = LHS->IgnoreParenImpCasts();
10674   RHS = RHS->IgnoreParenImpCasts();
10675 
10676   if (!S.getLangOpts().CPlusPlus) {
10677     // Avoid warning about comparison of integers with different signs when
10678     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
10679     // the type of `E`.
10680     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
10681       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10682     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
10683       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10684   }
10685 
10686   // Check to see if one of the (unmodified) operands is of different
10687   // signedness.
10688   Expr *signedOperand, *unsignedOperand;
10689   if (LHS->getType()->hasSignedIntegerRepresentation()) {
10690     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
10691            "unsigned comparison between two signed integer expressions?");
10692     signedOperand = LHS;
10693     unsignedOperand = RHS;
10694   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
10695     signedOperand = RHS;
10696     unsignedOperand = LHS;
10697   } else {
10698     return AnalyzeImpConvsInComparison(S, E);
10699   }
10700 
10701   // Otherwise, calculate the effective range of the signed operand.
10702   IntRange signedRange =
10703       GetExprRange(S.Context, signedOperand, S.isConstantEvaluated());
10704 
10705   // Go ahead and analyze implicit conversions in the operands.  Note
10706   // that we skip the implicit conversions on both sides.
10707   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
10708   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
10709 
10710   // If the signed range is non-negative, -Wsign-compare won't fire.
10711   if (signedRange.NonNegative)
10712     return;
10713 
10714   // For (in)equality comparisons, if the unsigned operand is a
10715   // constant which cannot collide with a overflowed signed operand,
10716   // then reinterpreting the signed operand as unsigned will not
10717   // change the result of the comparison.
10718   if (E->isEqualityOp()) {
10719     unsigned comparisonWidth = S.Context.getIntWidth(T);
10720     IntRange unsignedRange =
10721         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated());
10722 
10723     // We should never be unable to prove that the unsigned operand is
10724     // non-negative.
10725     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
10726 
10727     if (unsignedRange.Width < comparisonWidth)
10728       return;
10729   }
10730 
10731   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10732                         S.PDiag(diag::warn_mixed_sign_comparison)
10733                             << LHS->getType() << RHS->getType()
10734                             << LHS->getSourceRange() << RHS->getSourceRange());
10735 }
10736 
10737 /// Analyzes an attempt to assign the given value to a bitfield.
10738 ///
10739 /// Returns true if there was something fishy about the attempt.
10740 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
10741                                       SourceLocation InitLoc) {
10742   assert(Bitfield->isBitField());
10743   if (Bitfield->isInvalidDecl())
10744     return false;
10745 
10746   // White-list bool bitfields.
10747   QualType BitfieldType = Bitfield->getType();
10748   if (BitfieldType->isBooleanType())
10749      return false;
10750 
10751   if (BitfieldType->isEnumeralType()) {
10752     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
10753     // If the underlying enum type was not explicitly specified as an unsigned
10754     // type and the enum contain only positive values, MSVC++ will cause an
10755     // inconsistency by storing this as a signed type.
10756     if (S.getLangOpts().CPlusPlus11 &&
10757         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
10758         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
10759         BitfieldEnumDecl->getNumNegativeBits() == 0) {
10760       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
10761         << BitfieldEnumDecl->getNameAsString();
10762     }
10763   }
10764 
10765   if (Bitfield->getType()->isBooleanType())
10766     return false;
10767 
10768   // Ignore value- or type-dependent expressions.
10769   if (Bitfield->getBitWidth()->isValueDependent() ||
10770       Bitfield->getBitWidth()->isTypeDependent() ||
10771       Init->isValueDependent() ||
10772       Init->isTypeDependent())
10773     return false;
10774 
10775   Expr *OriginalInit = Init->IgnoreParenImpCasts();
10776   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
10777 
10778   Expr::EvalResult Result;
10779   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
10780                                    Expr::SE_AllowSideEffects)) {
10781     // The RHS is not constant.  If the RHS has an enum type, make sure the
10782     // bitfield is wide enough to hold all the values of the enum without
10783     // truncation.
10784     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
10785       EnumDecl *ED = EnumTy->getDecl();
10786       bool SignedBitfield = BitfieldType->isSignedIntegerType();
10787 
10788       // Enum types are implicitly signed on Windows, so check if there are any
10789       // negative enumerators to see if the enum was intended to be signed or
10790       // not.
10791       bool SignedEnum = ED->getNumNegativeBits() > 0;
10792 
10793       // Check for surprising sign changes when assigning enum values to a
10794       // bitfield of different signedness.  If the bitfield is signed and we
10795       // have exactly the right number of bits to store this unsigned enum,
10796       // suggest changing the enum to an unsigned type. This typically happens
10797       // on Windows where unfixed enums always use an underlying type of 'int'.
10798       unsigned DiagID = 0;
10799       if (SignedEnum && !SignedBitfield) {
10800         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
10801       } else if (SignedBitfield && !SignedEnum &&
10802                  ED->getNumPositiveBits() == FieldWidth) {
10803         DiagID = diag::warn_signed_bitfield_enum_conversion;
10804       }
10805 
10806       if (DiagID) {
10807         S.Diag(InitLoc, DiagID) << Bitfield << ED;
10808         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
10809         SourceRange TypeRange =
10810             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
10811         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
10812             << SignedEnum << TypeRange;
10813       }
10814 
10815       // Compute the required bitwidth. If the enum has negative values, we need
10816       // one more bit than the normal number of positive bits to represent the
10817       // sign bit.
10818       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
10819                                                   ED->getNumNegativeBits())
10820                                        : ED->getNumPositiveBits();
10821 
10822       // Check the bitwidth.
10823       if (BitsNeeded > FieldWidth) {
10824         Expr *WidthExpr = Bitfield->getBitWidth();
10825         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
10826             << Bitfield << ED;
10827         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
10828             << BitsNeeded << ED << WidthExpr->getSourceRange();
10829       }
10830     }
10831 
10832     return false;
10833   }
10834 
10835   llvm::APSInt Value = Result.Val.getInt();
10836 
10837   unsigned OriginalWidth = Value.getBitWidth();
10838 
10839   if (!Value.isSigned() || Value.isNegative())
10840     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
10841       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
10842         OriginalWidth = Value.getMinSignedBits();
10843 
10844   if (OriginalWidth <= FieldWidth)
10845     return false;
10846 
10847   // Compute the value which the bitfield will contain.
10848   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
10849   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
10850 
10851   // Check whether the stored value is equal to the original value.
10852   TruncatedValue = TruncatedValue.extend(OriginalWidth);
10853   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
10854     return false;
10855 
10856   // Special-case bitfields of width 1: booleans are naturally 0/1, and
10857   // therefore don't strictly fit into a signed bitfield of width 1.
10858   if (FieldWidth == 1 && Value == 1)
10859     return false;
10860 
10861   std::string PrettyValue = Value.toString(10);
10862   std::string PrettyTrunc = TruncatedValue.toString(10);
10863 
10864   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
10865     << PrettyValue << PrettyTrunc << OriginalInit->getType()
10866     << Init->getSourceRange();
10867 
10868   return true;
10869 }
10870 
10871 /// Analyze the given simple or compound assignment for warning-worthy
10872 /// operations.
10873 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
10874   // Just recurse on the LHS.
10875   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10876 
10877   // We want to recurse on the RHS as normal unless we're assigning to
10878   // a bitfield.
10879   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
10880     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
10881                                   E->getOperatorLoc())) {
10882       // Recurse, ignoring any implicit conversions on the RHS.
10883       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
10884                                         E->getOperatorLoc());
10885     }
10886   }
10887 
10888   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10889 
10890   // Diagnose implicitly sequentially-consistent atomic assignment.
10891   if (E->getLHS()->getType()->isAtomicType())
10892     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
10893 }
10894 
10895 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
10896 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
10897                             SourceLocation CContext, unsigned diag,
10898                             bool pruneControlFlow = false) {
10899   if (pruneControlFlow) {
10900     S.DiagRuntimeBehavior(E->getExprLoc(), E,
10901                           S.PDiag(diag)
10902                               << SourceType << T << E->getSourceRange()
10903                               << SourceRange(CContext));
10904     return;
10905   }
10906   S.Diag(E->getExprLoc(), diag)
10907     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
10908 }
10909 
10910 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
10911 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
10912                             SourceLocation CContext,
10913                             unsigned diag, bool pruneControlFlow = false) {
10914   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
10915 }
10916 
10917 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
10918   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
10919       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
10920 }
10921 
10922 static void adornObjCBoolConversionDiagWithTernaryFixit(
10923     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
10924   Expr *Ignored = SourceExpr->IgnoreImplicit();
10925   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
10926     Ignored = OVE->getSourceExpr();
10927   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
10928                      isa<BinaryOperator>(Ignored) ||
10929                      isa<CXXOperatorCallExpr>(Ignored);
10930   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
10931   if (NeedsParens)
10932     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
10933             << FixItHint::CreateInsertion(EndLoc, ")");
10934   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
10935 }
10936 
10937 /// Diagnose an implicit cast from a floating point value to an integer value.
10938 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
10939                                     SourceLocation CContext) {
10940   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
10941   const bool PruneWarnings = S.inTemplateInstantiation();
10942 
10943   Expr *InnerE = E->IgnoreParenImpCasts();
10944   // We also want to warn on, e.g., "int i = -1.234"
10945   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
10946     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
10947       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
10948 
10949   const bool IsLiteral =
10950       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
10951 
10952   llvm::APFloat Value(0.0);
10953   bool IsConstant =
10954     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
10955   if (!IsConstant) {
10956     if (isObjCSignedCharBool(S, T)) {
10957       return adornObjCBoolConversionDiagWithTernaryFixit(
10958           S, E,
10959           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
10960               << E->getType());
10961     }
10962 
10963     return DiagnoseImpCast(S, E, T, CContext,
10964                            diag::warn_impcast_float_integer, PruneWarnings);
10965   }
10966 
10967   bool isExact = false;
10968 
10969   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
10970                             T->hasUnsignedIntegerRepresentation());
10971   llvm::APFloat::opStatus Result = Value.convertToInteger(
10972       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
10973 
10974   // FIXME: Force the precision of the source value down so we don't print
10975   // digits which are usually useless (we don't really care here if we
10976   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
10977   // would automatically print the shortest representation, but it's a bit
10978   // tricky to implement.
10979   SmallString<16> PrettySourceValue;
10980   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
10981   precision = (precision * 59 + 195) / 196;
10982   Value.toString(PrettySourceValue, precision);
10983 
10984   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
10985     return adornObjCBoolConversionDiagWithTernaryFixit(
10986         S, E,
10987         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
10988             << PrettySourceValue);
10989   }
10990 
10991   if (Result == llvm::APFloat::opOK && isExact) {
10992     if (IsLiteral) return;
10993     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
10994                            PruneWarnings);
10995   }
10996 
10997   // Conversion of a floating-point value to a non-bool integer where the
10998   // integral part cannot be represented by the integer type is undefined.
10999   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
11000     return DiagnoseImpCast(
11001         S, E, T, CContext,
11002         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
11003                   : diag::warn_impcast_float_to_integer_out_of_range,
11004         PruneWarnings);
11005 
11006   unsigned DiagID = 0;
11007   if (IsLiteral) {
11008     // Warn on floating point literal to integer.
11009     DiagID = diag::warn_impcast_literal_float_to_integer;
11010   } else if (IntegerValue == 0) {
11011     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
11012       return DiagnoseImpCast(S, E, T, CContext,
11013                              diag::warn_impcast_float_integer, PruneWarnings);
11014     }
11015     // Warn on non-zero to zero conversion.
11016     DiagID = diag::warn_impcast_float_to_integer_zero;
11017   } else {
11018     if (IntegerValue.isUnsigned()) {
11019       if (!IntegerValue.isMaxValue()) {
11020         return DiagnoseImpCast(S, E, T, CContext,
11021                                diag::warn_impcast_float_integer, PruneWarnings);
11022       }
11023     } else {  // IntegerValue.isSigned()
11024       if (!IntegerValue.isMaxSignedValue() &&
11025           !IntegerValue.isMinSignedValue()) {
11026         return DiagnoseImpCast(S, E, T, CContext,
11027                                diag::warn_impcast_float_integer, PruneWarnings);
11028       }
11029     }
11030     // Warn on evaluatable floating point expression to integer conversion.
11031     DiagID = diag::warn_impcast_float_to_integer;
11032   }
11033 
11034   SmallString<16> PrettyTargetValue;
11035   if (IsBool)
11036     PrettyTargetValue = Value.isZero() ? "false" : "true";
11037   else
11038     IntegerValue.toString(PrettyTargetValue);
11039 
11040   if (PruneWarnings) {
11041     S.DiagRuntimeBehavior(E->getExprLoc(), E,
11042                           S.PDiag(DiagID)
11043                               << E->getType() << T.getUnqualifiedType()
11044                               << PrettySourceValue << PrettyTargetValue
11045                               << E->getSourceRange() << SourceRange(CContext));
11046   } else {
11047     S.Diag(E->getExprLoc(), DiagID)
11048         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
11049         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
11050   }
11051 }
11052 
11053 /// Analyze the given compound assignment for the possible losing of
11054 /// floating-point precision.
11055 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
11056   assert(isa<CompoundAssignOperator>(E) &&
11057          "Must be compound assignment operation");
11058   // Recurse on the LHS and RHS in here
11059   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11060   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11061 
11062   if (E->getLHS()->getType()->isAtomicType())
11063     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
11064 
11065   // Now check the outermost expression
11066   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
11067   const auto *RBT = cast<CompoundAssignOperator>(E)
11068                         ->getComputationResultType()
11069                         ->getAs<BuiltinType>();
11070 
11071   // The below checks assume source is floating point.
11072   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
11073 
11074   // If source is floating point but target is an integer.
11075   if (ResultBT->isInteger())
11076     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
11077                            E->getExprLoc(), diag::warn_impcast_float_integer);
11078 
11079   if (!ResultBT->isFloatingPoint())
11080     return;
11081 
11082   // If both source and target are floating points, warn about losing precision.
11083   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11084       QualType(ResultBT, 0), QualType(RBT, 0));
11085   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
11086     // warn about dropping FP rank.
11087     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
11088                     diag::warn_impcast_float_result_precision);
11089 }
11090 
11091 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
11092                                       IntRange Range) {
11093   if (!Range.Width) return "0";
11094 
11095   llvm::APSInt ValueInRange = Value;
11096   ValueInRange.setIsSigned(!Range.NonNegative);
11097   ValueInRange = ValueInRange.trunc(Range.Width);
11098   return ValueInRange.toString(10);
11099 }
11100 
11101 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
11102   if (!isa<ImplicitCastExpr>(Ex))
11103     return false;
11104 
11105   Expr *InnerE = Ex->IgnoreParenImpCasts();
11106   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
11107   const Type *Source =
11108     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
11109   if (Target->isDependentType())
11110     return false;
11111 
11112   const BuiltinType *FloatCandidateBT =
11113     dyn_cast<BuiltinType>(ToBool ? Source : Target);
11114   const Type *BoolCandidateType = ToBool ? Target : Source;
11115 
11116   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
11117           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
11118 }
11119 
11120 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
11121                                              SourceLocation CC) {
11122   unsigned NumArgs = TheCall->getNumArgs();
11123   for (unsigned i = 0; i < NumArgs; ++i) {
11124     Expr *CurrA = TheCall->getArg(i);
11125     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
11126       continue;
11127 
11128     bool IsSwapped = ((i > 0) &&
11129         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
11130     IsSwapped |= ((i < (NumArgs - 1)) &&
11131         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
11132     if (IsSwapped) {
11133       // Warn on this floating-point to bool conversion.
11134       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
11135                       CurrA->getType(), CC,
11136                       diag::warn_impcast_floating_point_to_bool);
11137     }
11138   }
11139 }
11140 
11141 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
11142                                    SourceLocation CC) {
11143   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
11144                         E->getExprLoc()))
11145     return;
11146 
11147   // Don't warn on functions which have return type nullptr_t.
11148   if (isa<CallExpr>(E))
11149     return;
11150 
11151   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
11152   const Expr::NullPointerConstantKind NullKind =
11153       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
11154   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
11155     return;
11156 
11157   // Return if target type is a safe conversion.
11158   if (T->isAnyPointerType() || T->isBlockPointerType() ||
11159       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
11160     return;
11161 
11162   SourceLocation Loc = E->getSourceRange().getBegin();
11163 
11164   // Venture through the macro stacks to get to the source of macro arguments.
11165   // The new location is a better location than the complete location that was
11166   // passed in.
11167   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
11168   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
11169 
11170   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
11171   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
11172     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
11173         Loc, S.SourceMgr, S.getLangOpts());
11174     if (MacroName == "NULL")
11175       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
11176   }
11177 
11178   // Only warn if the null and context location are in the same macro expansion.
11179   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
11180     return;
11181 
11182   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
11183       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
11184       << FixItHint::CreateReplacement(Loc,
11185                                       S.getFixItZeroLiteralForType(T, Loc));
11186 }
11187 
11188 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11189                                   ObjCArrayLiteral *ArrayLiteral);
11190 
11191 static void
11192 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11193                            ObjCDictionaryLiteral *DictionaryLiteral);
11194 
11195 /// Check a single element within a collection literal against the
11196 /// target element type.
11197 static void checkObjCCollectionLiteralElement(Sema &S,
11198                                               QualType TargetElementType,
11199                                               Expr *Element,
11200                                               unsigned ElementKind) {
11201   // Skip a bitcast to 'id' or qualified 'id'.
11202   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
11203     if (ICE->getCastKind() == CK_BitCast &&
11204         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
11205       Element = ICE->getSubExpr();
11206   }
11207 
11208   QualType ElementType = Element->getType();
11209   ExprResult ElementResult(Element);
11210   if (ElementType->getAs<ObjCObjectPointerType>() &&
11211       S.CheckSingleAssignmentConstraints(TargetElementType,
11212                                          ElementResult,
11213                                          false, false)
11214         != Sema::Compatible) {
11215     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
11216         << ElementType << ElementKind << TargetElementType
11217         << Element->getSourceRange();
11218   }
11219 
11220   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
11221     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
11222   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
11223     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
11224 }
11225 
11226 /// Check an Objective-C array literal being converted to the given
11227 /// target type.
11228 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11229                                   ObjCArrayLiteral *ArrayLiteral) {
11230   if (!S.NSArrayDecl)
11231     return;
11232 
11233   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11234   if (!TargetObjCPtr)
11235     return;
11236 
11237   if (TargetObjCPtr->isUnspecialized() ||
11238       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11239         != S.NSArrayDecl->getCanonicalDecl())
11240     return;
11241 
11242   auto TypeArgs = TargetObjCPtr->getTypeArgs();
11243   if (TypeArgs.size() != 1)
11244     return;
11245 
11246   QualType TargetElementType = TypeArgs[0];
11247   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
11248     checkObjCCollectionLiteralElement(S, TargetElementType,
11249                                       ArrayLiteral->getElement(I),
11250                                       0);
11251   }
11252 }
11253 
11254 /// Check an Objective-C dictionary literal being converted to the given
11255 /// target type.
11256 static void
11257 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11258                            ObjCDictionaryLiteral *DictionaryLiteral) {
11259   if (!S.NSDictionaryDecl)
11260     return;
11261 
11262   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11263   if (!TargetObjCPtr)
11264     return;
11265 
11266   if (TargetObjCPtr->isUnspecialized() ||
11267       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11268         != S.NSDictionaryDecl->getCanonicalDecl())
11269     return;
11270 
11271   auto TypeArgs = TargetObjCPtr->getTypeArgs();
11272   if (TypeArgs.size() != 2)
11273     return;
11274 
11275   QualType TargetKeyType = TypeArgs[0];
11276   QualType TargetObjectType = TypeArgs[1];
11277   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
11278     auto Element = DictionaryLiteral->getKeyValueElement(I);
11279     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
11280     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
11281   }
11282 }
11283 
11284 // Helper function to filter out cases for constant width constant conversion.
11285 // Don't warn on char array initialization or for non-decimal values.
11286 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
11287                                           SourceLocation CC) {
11288   // If initializing from a constant, and the constant starts with '0',
11289   // then it is a binary, octal, or hexadecimal.  Allow these constants
11290   // to fill all the bits, even if there is a sign change.
11291   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
11292     const char FirstLiteralCharacter =
11293         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
11294     if (FirstLiteralCharacter == '0')
11295       return false;
11296   }
11297 
11298   // If the CC location points to a '{', and the type is char, then assume
11299   // assume it is an array initialization.
11300   if (CC.isValid() && T->isCharType()) {
11301     const char FirstContextCharacter =
11302         S.getSourceManager().getCharacterData(CC)[0];
11303     if (FirstContextCharacter == '{')
11304       return false;
11305   }
11306 
11307   return true;
11308 }
11309 
11310 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
11311   const auto *IL = dyn_cast<IntegerLiteral>(E);
11312   if (!IL) {
11313     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
11314       if (UO->getOpcode() == UO_Minus)
11315         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
11316     }
11317   }
11318 
11319   return IL;
11320 }
11321 
11322 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
11323   E = E->IgnoreParenImpCasts();
11324   SourceLocation ExprLoc = E->getExprLoc();
11325 
11326   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11327     BinaryOperator::Opcode Opc = BO->getOpcode();
11328     Expr::EvalResult Result;
11329     // Do not diagnose unsigned shifts.
11330     if (Opc == BO_Shl) {
11331       const auto *LHS = getIntegerLiteral(BO->getLHS());
11332       const auto *RHS = getIntegerLiteral(BO->getRHS());
11333       if (LHS && LHS->getValue() == 0)
11334         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
11335       else if (!E->isValueDependent() && LHS && RHS &&
11336                RHS->getValue().isNonNegative() &&
11337                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
11338         S.Diag(ExprLoc, diag::warn_left_shift_always)
11339             << (Result.Val.getInt() != 0);
11340       else if (E->getType()->isSignedIntegerType())
11341         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
11342     }
11343   }
11344 
11345   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11346     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
11347     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
11348     if (!LHS || !RHS)
11349       return;
11350     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
11351         (RHS->getValue() == 0 || RHS->getValue() == 1))
11352       // Do not diagnose common idioms.
11353       return;
11354     if (LHS->getValue() != 0 && RHS->getValue() != 0)
11355       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
11356   }
11357 }
11358 
11359 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
11360                                     SourceLocation CC,
11361                                     bool *ICContext = nullptr,
11362                                     bool IsListInit = false) {
11363   if (E->isTypeDependent() || E->isValueDependent()) return;
11364 
11365   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
11366   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
11367   if (Source == Target) return;
11368   if (Target->isDependentType()) return;
11369 
11370   // If the conversion context location is invalid don't complain. We also
11371   // don't want to emit a warning if the issue occurs from the expansion of
11372   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
11373   // delay this check as long as possible. Once we detect we are in that
11374   // scenario, we just return.
11375   if (CC.isInvalid())
11376     return;
11377 
11378   if (Source->isAtomicType())
11379     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
11380 
11381   // Diagnose implicit casts to bool.
11382   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
11383     if (isa<StringLiteral>(E))
11384       // Warn on string literal to bool.  Checks for string literals in logical
11385       // and expressions, for instance, assert(0 && "error here"), are
11386       // prevented by a check in AnalyzeImplicitConversions().
11387       return DiagnoseImpCast(S, E, T, CC,
11388                              diag::warn_impcast_string_literal_to_bool);
11389     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
11390         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
11391       // This covers the literal expressions that evaluate to Objective-C
11392       // objects.
11393       return DiagnoseImpCast(S, E, T, CC,
11394                              diag::warn_impcast_objective_c_literal_to_bool);
11395     }
11396     if (Source->isPointerType() || Source->canDecayToPointerType()) {
11397       // Warn on pointer to bool conversion that is always true.
11398       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
11399                                      SourceRange(CC));
11400     }
11401   }
11402 
11403   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
11404   // is a typedef for signed char (macOS), then that constant value has to be 1
11405   // or 0.
11406   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
11407     Expr::EvalResult Result;
11408     if (E->EvaluateAsInt(Result, S.getASTContext(),
11409                          Expr::SE_AllowSideEffects)) {
11410       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
11411         adornObjCBoolConversionDiagWithTernaryFixit(
11412             S, E,
11413             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
11414                 << Result.Val.getInt().toString(10));
11415       }
11416       return;
11417     }
11418   }
11419 
11420   // Check implicit casts from Objective-C collection literals to specialized
11421   // collection types, e.g., NSArray<NSString *> *.
11422   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
11423     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
11424   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
11425     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
11426 
11427   // Strip vector types.
11428   if (isa<VectorType>(Source)) {
11429     if (!isa<VectorType>(Target)) {
11430       if (S.SourceMgr.isInSystemMacro(CC))
11431         return;
11432       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
11433     }
11434 
11435     // If the vector cast is cast between two vectors of the same size, it is
11436     // a bitcast, not a conversion.
11437     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
11438       return;
11439 
11440     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
11441     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
11442   }
11443   if (auto VecTy = dyn_cast<VectorType>(Target))
11444     Target = VecTy->getElementType().getTypePtr();
11445 
11446   // Strip complex types.
11447   if (isa<ComplexType>(Source)) {
11448     if (!isa<ComplexType>(Target)) {
11449       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
11450         return;
11451 
11452       return DiagnoseImpCast(S, E, T, CC,
11453                              S.getLangOpts().CPlusPlus
11454                                  ? diag::err_impcast_complex_scalar
11455                                  : diag::warn_impcast_complex_scalar);
11456     }
11457 
11458     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
11459     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
11460   }
11461 
11462   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
11463   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
11464 
11465   // If the source is floating point...
11466   if (SourceBT && SourceBT->isFloatingPoint()) {
11467     // ...and the target is floating point...
11468     if (TargetBT && TargetBT->isFloatingPoint()) {
11469       // ...then warn if we're dropping FP rank.
11470 
11471       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11472           QualType(SourceBT, 0), QualType(TargetBT, 0));
11473       if (Order > 0) {
11474         // Don't warn about float constants that are precisely
11475         // representable in the target type.
11476         Expr::EvalResult result;
11477         if (E->EvaluateAsRValue(result, S.Context)) {
11478           // Value might be a float, a float vector, or a float complex.
11479           if (IsSameFloatAfterCast(result.Val,
11480                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
11481                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
11482             return;
11483         }
11484 
11485         if (S.SourceMgr.isInSystemMacro(CC))
11486           return;
11487 
11488         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
11489       }
11490       // ... or possibly if we're increasing rank, too
11491       else if (Order < 0) {
11492         if (S.SourceMgr.isInSystemMacro(CC))
11493           return;
11494 
11495         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
11496       }
11497       return;
11498     }
11499 
11500     // If the target is integral, always warn.
11501     if (TargetBT && TargetBT->isInteger()) {
11502       if (S.SourceMgr.isInSystemMacro(CC))
11503         return;
11504 
11505       DiagnoseFloatingImpCast(S, E, T, CC);
11506     }
11507 
11508     // Detect the case where a call result is converted from floating-point to
11509     // to bool, and the final argument to the call is converted from bool, to
11510     // discover this typo:
11511     //
11512     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
11513     //
11514     // FIXME: This is an incredibly special case; is there some more general
11515     // way to detect this class of misplaced-parentheses bug?
11516     if (Target->isBooleanType() && isa<CallExpr>(E)) {
11517       // Check last argument of function call to see if it is an
11518       // implicit cast from a type matching the type the result
11519       // is being cast to.
11520       CallExpr *CEx = cast<CallExpr>(E);
11521       if (unsigned NumArgs = CEx->getNumArgs()) {
11522         Expr *LastA = CEx->getArg(NumArgs - 1);
11523         Expr *InnerE = LastA->IgnoreParenImpCasts();
11524         if (isa<ImplicitCastExpr>(LastA) &&
11525             InnerE->getType()->isBooleanType()) {
11526           // Warn on this floating-point to bool conversion
11527           DiagnoseImpCast(S, E, T, CC,
11528                           diag::warn_impcast_floating_point_to_bool);
11529         }
11530       }
11531     }
11532     return;
11533   }
11534 
11535   // Valid casts involving fixed point types should be accounted for here.
11536   if (Source->isFixedPointType()) {
11537     if (Target->isUnsaturatedFixedPointType()) {
11538       Expr::EvalResult Result;
11539       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
11540                                   S.isConstantEvaluated())) {
11541         APFixedPoint Value = Result.Val.getFixedPoint();
11542         APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
11543         APFixedPoint MinVal = S.Context.getFixedPointMin(T);
11544         if (Value > MaxVal || Value < MinVal) {
11545           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11546                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11547                                     << Value.toString() << T
11548                                     << E->getSourceRange()
11549                                     << clang::SourceRange(CC));
11550           return;
11551         }
11552       }
11553     } else if (Target->isIntegerType()) {
11554       Expr::EvalResult Result;
11555       if (!S.isConstantEvaluated() &&
11556           E->EvaluateAsFixedPoint(Result, S.Context,
11557                                   Expr::SE_AllowSideEffects)) {
11558         APFixedPoint FXResult = Result.Val.getFixedPoint();
11559 
11560         bool Overflowed;
11561         llvm::APSInt IntResult = FXResult.convertToInt(
11562             S.Context.getIntWidth(T),
11563             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
11564 
11565         if (Overflowed) {
11566           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11567                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11568                                     << FXResult.toString() << T
11569                                     << E->getSourceRange()
11570                                     << clang::SourceRange(CC));
11571           return;
11572         }
11573       }
11574     }
11575   } else if (Target->isUnsaturatedFixedPointType()) {
11576     if (Source->isIntegerType()) {
11577       Expr::EvalResult Result;
11578       if (!S.isConstantEvaluated() &&
11579           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
11580         llvm::APSInt Value = Result.Val.getInt();
11581 
11582         bool Overflowed;
11583         APFixedPoint IntResult = APFixedPoint::getFromIntValue(
11584             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
11585 
11586         if (Overflowed) {
11587           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11588                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11589                                     << Value.toString(/*Radix=*/10) << T
11590                                     << E->getSourceRange()
11591                                     << clang::SourceRange(CC));
11592           return;
11593         }
11594       }
11595     }
11596   }
11597 
11598   // If we are casting an integer type to a floating point type without
11599   // initialization-list syntax, we might lose accuracy if the floating
11600   // point type has a narrower significand than the integer type.
11601   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
11602       TargetBT->isFloatingType() && !IsListInit) {
11603     // Determine the number of precision bits in the source integer type.
11604     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated());
11605     unsigned int SourcePrecision = SourceRange.Width;
11606 
11607     // Determine the number of precision bits in the
11608     // target floating point type.
11609     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
11610         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
11611 
11612     if (SourcePrecision > 0 && TargetPrecision > 0 &&
11613         SourcePrecision > TargetPrecision) {
11614 
11615       llvm::APSInt SourceInt;
11616       if (E->isIntegerConstantExpr(SourceInt, S.Context)) {
11617         // If the source integer is a constant, convert it to the target
11618         // floating point type. Issue a warning if the value changes
11619         // during the whole conversion.
11620         llvm::APFloat TargetFloatValue(
11621             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
11622         llvm::APFloat::opStatus ConversionStatus =
11623             TargetFloatValue.convertFromAPInt(
11624                 SourceInt, SourceBT->isSignedInteger(),
11625                 llvm::APFloat::rmNearestTiesToEven);
11626 
11627         if (ConversionStatus != llvm::APFloat::opOK) {
11628           std::string PrettySourceValue = SourceInt.toString(10);
11629           SmallString<32> PrettyTargetValue;
11630           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
11631 
11632           S.DiagRuntimeBehavior(
11633               E->getExprLoc(), E,
11634               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
11635                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
11636                   << E->getSourceRange() << clang::SourceRange(CC));
11637         }
11638       } else {
11639         // Otherwise, the implicit conversion may lose precision.
11640         DiagnoseImpCast(S, E, T, CC,
11641                         diag::warn_impcast_integer_float_precision);
11642       }
11643     }
11644   }
11645 
11646   DiagnoseNullConversion(S, E, T, CC);
11647 
11648   S.DiscardMisalignedMemberAddress(Target, E);
11649 
11650   if (Target->isBooleanType())
11651     DiagnoseIntInBoolContext(S, E);
11652 
11653   if (!Source->isIntegerType() || !Target->isIntegerType())
11654     return;
11655 
11656   // TODO: remove this early return once the false positives for constant->bool
11657   // in templates, macros, etc, are reduced or removed.
11658   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
11659     return;
11660 
11661   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
11662       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
11663     return adornObjCBoolConversionDiagWithTernaryFixit(
11664         S, E,
11665         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
11666             << E->getType());
11667   }
11668 
11669   IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated());
11670   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
11671 
11672   if (SourceRange.Width > TargetRange.Width) {
11673     // If the source is a constant, use a default-on diagnostic.
11674     // TODO: this should happen for bitfield stores, too.
11675     Expr::EvalResult Result;
11676     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
11677                          S.isConstantEvaluated())) {
11678       llvm::APSInt Value(32);
11679       Value = Result.Val.getInt();
11680 
11681       if (S.SourceMgr.isInSystemMacro(CC))
11682         return;
11683 
11684       std::string PrettySourceValue = Value.toString(10);
11685       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11686 
11687       S.DiagRuntimeBehavior(
11688           E->getExprLoc(), E,
11689           S.PDiag(diag::warn_impcast_integer_precision_constant)
11690               << PrettySourceValue << PrettyTargetValue << E->getType() << T
11691               << E->getSourceRange() << clang::SourceRange(CC));
11692       return;
11693     }
11694 
11695     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
11696     if (S.SourceMgr.isInSystemMacro(CC))
11697       return;
11698 
11699     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
11700       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
11701                              /* pruneControlFlow */ true);
11702     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
11703   }
11704 
11705   if (TargetRange.Width > SourceRange.Width) {
11706     if (auto *UO = dyn_cast<UnaryOperator>(E))
11707       if (UO->getOpcode() == UO_Minus)
11708         if (Source->isUnsignedIntegerType()) {
11709           if (Target->isUnsignedIntegerType())
11710             return DiagnoseImpCast(S, E, T, CC,
11711                                    diag::warn_impcast_high_order_zero_bits);
11712           if (Target->isSignedIntegerType())
11713             return DiagnoseImpCast(S, E, T, CC,
11714                                    diag::warn_impcast_nonnegative_result);
11715         }
11716   }
11717 
11718   if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
11719       SourceRange.NonNegative && Source->isSignedIntegerType()) {
11720     // Warn when doing a signed to signed conversion, warn if the positive
11721     // source value is exactly the width of the target type, which will
11722     // cause a negative value to be stored.
11723 
11724     Expr::EvalResult Result;
11725     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
11726         !S.SourceMgr.isInSystemMacro(CC)) {
11727       llvm::APSInt Value = Result.Val.getInt();
11728       if (isSameWidthConstantConversion(S, E, T, CC)) {
11729         std::string PrettySourceValue = Value.toString(10);
11730         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11731 
11732         S.DiagRuntimeBehavior(
11733             E->getExprLoc(), E,
11734             S.PDiag(diag::warn_impcast_integer_precision_constant)
11735                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
11736                 << E->getSourceRange() << clang::SourceRange(CC));
11737         return;
11738       }
11739     }
11740 
11741     // Fall through for non-constants to give a sign conversion warning.
11742   }
11743 
11744   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
11745       (!TargetRange.NonNegative && SourceRange.NonNegative &&
11746        SourceRange.Width == TargetRange.Width)) {
11747     if (S.SourceMgr.isInSystemMacro(CC))
11748       return;
11749 
11750     unsigned DiagID = diag::warn_impcast_integer_sign;
11751 
11752     // Traditionally, gcc has warned about this under -Wsign-compare.
11753     // We also want to warn about it in -Wconversion.
11754     // So if -Wconversion is off, use a completely identical diagnostic
11755     // in the sign-compare group.
11756     // The conditional-checking code will
11757     if (ICContext) {
11758       DiagID = diag::warn_impcast_integer_sign_conditional;
11759       *ICContext = true;
11760     }
11761 
11762     return DiagnoseImpCast(S, E, T, CC, DiagID);
11763   }
11764 
11765   // Diagnose conversions between different enumeration types.
11766   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
11767   // type, to give us better diagnostics.
11768   QualType SourceType = E->getType();
11769   if (!S.getLangOpts().CPlusPlus) {
11770     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11771       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
11772         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
11773         SourceType = S.Context.getTypeDeclType(Enum);
11774         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
11775       }
11776   }
11777 
11778   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
11779     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
11780       if (SourceEnum->getDecl()->hasNameForLinkage() &&
11781           TargetEnum->getDecl()->hasNameForLinkage() &&
11782           SourceEnum != TargetEnum) {
11783         if (S.SourceMgr.isInSystemMacro(CC))
11784           return;
11785 
11786         return DiagnoseImpCast(S, E, SourceType, T, CC,
11787                                diag::warn_impcast_different_enum_types);
11788       }
11789 }
11790 
11791 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11792                                      SourceLocation CC, QualType T);
11793 
11794 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
11795                                     SourceLocation CC, bool &ICContext) {
11796   E = E->IgnoreParenImpCasts();
11797 
11798   if (isa<ConditionalOperator>(E))
11799     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
11800 
11801   AnalyzeImplicitConversions(S, E, CC);
11802   if (E->getType() != T)
11803     return CheckImplicitConversion(S, E, T, CC, &ICContext);
11804 }
11805 
11806 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11807                                      SourceLocation CC, QualType T) {
11808   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
11809 
11810   bool Suspicious = false;
11811   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
11812   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
11813 
11814   if (T->isBooleanType())
11815     DiagnoseIntInBoolContext(S, E);
11816 
11817   // If -Wconversion would have warned about either of the candidates
11818   // for a signedness conversion to the context type...
11819   if (!Suspicious) return;
11820 
11821   // ...but it's currently ignored...
11822   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
11823     return;
11824 
11825   // ...then check whether it would have warned about either of the
11826   // candidates for a signedness conversion to the condition type.
11827   if (E->getType() == T) return;
11828 
11829   Suspicious = false;
11830   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
11831                           E->getType(), CC, &Suspicious);
11832   if (!Suspicious)
11833     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
11834                             E->getType(), CC, &Suspicious);
11835 }
11836 
11837 /// Check conversion of given expression to boolean.
11838 /// Input argument E is a logical expression.
11839 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
11840   if (S.getLangOpts().Bool)
11841     return;
11842   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
11843     return;
11844   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
11845 }
11846 
11847 namespace {
11848 struct AnalyzeImplicitConversionsWorkItem {
11849   Expr *E;
11850   SourceLocation CC;
11851   bool IsListInit;
11852 };
11853 }
11854 
11855 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
11856 /// that should be visited are added to WorkList.
11857 static void AnalyzeImplicitConversions(
11858     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
11859     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
11860   Expr *OrigE = Item.E;
11861   SourceLocation CC = Item.CC;
11862 
11863   QualType T = OrigE->getType();
11864   Expr *E = OrigE->IgnoreParenImpCasts();
11865 
11866   // Propagate whether we are in a C++ list initialization expression.
11867   // If so, we do not issue warnings for implicit int-float conversion
11868   // precision loss, because C++11 narrowing already handles it.
11869   bool IsListInit = Item.IsListInit ||
11870                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
11871 
11872   if (E->isTypeDependent() || E->isValueDependent())
11873     return;
11874 
11875   Expr *SourceExpr = E;
11876   // Examine, but don't traverse into the source expression of an
11877   // OpaqueValueExpr, since it may have multiple parents and we don't want to
11878   // emit duplicate diagnostics. Its fine to examine the form or attempt to
11879   // evaluate it in the context of checking the specific conversion to T though.
11880   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11881     if (auto *Src = OVE->getSourceExpr())
11882       SourceExpr = Src;
11883 
11884   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
11885     if (UO->getOpcode() == UO_Not &&
11886         UO->getSubExpr()->isKnownToHaveBooleanValue())
11887       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
11888           << OrigE->getSourceRange() << T->isBooleanType()
11889           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
11890 
11891   // For conditional operators, we analyze the arguments as if they
11892   // were being fed directly into the output.
11893   if (auto *CO = dyn_cast<ConditionalOperator>(SourceExpr)) {
11894     CheckConditionalOperator(S, CO, CC, T);
11895     return;
11896   }
11897 
11898   // Check implicit argument conversions for function calls.
11899   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
11900     CheckImplicitArgumentConversions(S, Call, CC);
11901 
11902   // Go ahead and check any implicit conversions we might have skipped.
11903   // The non-canonical typecheck is just an optimization;
11904   // CheckImplicitConversion will filter out dead implicit conversions.
11905   if (SourceExpr->getType() != T)
11906     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
11907 
11908   // Now continue drilling into this expression.
11909 
11910   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
11911     // The bound subexpressions in a PseudoObjectExpr are not reachable
11912     // as transitive children.
11913     // FIXME: Use a more uniform representation for this.
11914     for (auto *SE : POE->semantics())
11915       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
11916         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
11917   }
11918 
11919   // Skip past explicit casts.
11920   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
11921     E = CE->getSubExpr()->IgnoreParenImpCasts();
11922     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
11923       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
11924     WorkList.push_back({E, CC, IsListInit});
11925     return;
11926   }
11927 
11928   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11929     // Do a somewhat different check with comparison operators.
11930     if (BO->isComparisonOp())
11931       return AnalyzeComparison(S, BO);
11932 
11933     // And with simple assignments.
11934     if (BO->getOpcode() == BO_Assign)
11935       return AnalyzeAssignment(S, BO);
11936     // And with compound assignments.
11937     if (BO->isAssignmentOp())
11938       return AnalyzeCompoundAssignment(S, BO);
11939   }
11940 
11941   // These break the otherwise-useful invariant below.  Fortunately,
11942   // we don't really need to recurse into them, because any internal
11943   // expressions should have been analyzed already when they were
11944   // built into statements.
11945   if (isa<StmtExpr>(E)) return;
11946 
11947   // Don't descend into unevaluated contexts.
11948   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
11949 
11950   // Now just recurse over the expression's children.
11951   CC = E->getExprLoc();
11952   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
11953   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
11954   for (Stmt *SubStmt : E->children()) {
11955     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
11956     if (!ChildExpr)
11957       continue;
11958 
11959     if (IsLogicalAndOperator &&
11960         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
11961       // Ignore checking string literals that are in logical and operators.
11962       // This is a common pattern for asserts.
11963       continue;
11964     WorkList.push_back({ChildExpr, CC, IsListInit});
11965   }
11966 
11967   if (BO && BO->isLogicalOp()) {
11968     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
11969     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
11970       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
11971 
11972     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
11973     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
11974       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
11975   }
11976 
11977   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
11978     if (U->getOpcode() == UO_LNot) {
11979       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
11980     } else if (U->getOpcode() != UO_AddrOf) {
11981       if (U->getSubExpr()->getType()->isAtomicType())
11982         S.Diag(U->getSubExpr()->getBeginLoc(),
11983                diag::warn_atomic_implicit_seq_cst);
11984     }
11985   }
11986 }
11987 
11988 /// AnalyzeImplicitConversions - Find and report any interesting
11989 /// implicit conversions in the given expression.  There are a couple
11990 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
11991 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
11992                                        bool IsListInit/*= false*/) {
11993   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
11994   WorkList.push_back({OrigE, CC, IsListInit});
11995   while (!WorkList.empty())
11996     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
11997 }
11998 
11999 /// Diagnose integer type and any valid implicit conversion to it.
12000 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
12001   // Taking into account implicit conversions,
12002   // allow any integer.
12003   if (!E->getType()->isIntegerType()) {
12004     S.Diag(E->getBeginLoc(),
12005            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
12006     return true;
12007   }
12008   // Potentially emit standard warnings for implicit conversions if enabled
12009   // using -Wconversion.
12010   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
12011   return false;
12012 }
12013 
12014 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
12015 // Returns true when emitting a warning about taking the address of a reference.
12016 static bool CheckForReference(Sema &SemaRef, const Expr *E,
12017                               const PartialDiagnostic &PD) {
12018   E = E->IgnoreParenImpCasts();
12019 
12020   const FunctionDecl *FD = nullptr;
12021 
12022   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12023     if (!DRE->getDecl()->getType()->isReferenceType())
12024       return false;
12025   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12026     if (!M->getMemberDecl()->getType()->isReferenceType())
12027       return false;
12028   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
12029     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
12030       return false;
12031     FD = Call->getDirectCallee();
12032   } else {
12033     return false;
12034   }
12035 
12036   SemaRef.Diag(E->getExprLoc(), PD);
12037 
12038   // If possible, point to location of function.
12039   if (FD) {
12040     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
12041   }
12042 
12043   return true;
12044 }
12045 
12046 // Returns true if the SourceLocation is expanded from any macro body.
12047 // Returns false if the SourceLocation is invalid, is from not in a macro
12048 // expansion, or is from expanded from a top-level macro argument.
12049 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
12050   if (Loc.isInvalid())
12051     return false;
12052 
12053   while (Loc.isMacroID()) {
12054     if (SM.isMacroBodyExpansion(Loc))
12055       return true;
12056     Loc = SM.getImmediateMacroCallerLoc(Loc);
12057   }
12058 
12059   return false;
12060 }
12061 
12062 /// Diagnose pointers that are always non-null.
12063 /// \param E the expression containing the pointer
12064 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
12065 /// compared to a null pointer
12066 /// \param IsEqual True when the comparison is equal to a null pointer
12067 /// \param Range Extra SourceRange to highlight in the diagnostic
12068 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
12069                                         Expr::NullPointerConstantKind NullKind,
12070                                         bool IsEqual, SourceRange Range) {
12071   if (!E)
12072     return;
12073 
12074   // Don't warn inside macros.
12075   if (E->getExprLoc().isMacroID()) {
12076     const SourceManager &SM = getSourceManager();
12077     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
12078         IsInAnyMacroBody(SM, Range.getBegin()))
12079       return;
12080   }
12081   E = E->IgnoreImpCasts();
12082 
12083   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
12084 
12085   if (isa<CXXThisExpr>(E)) {
12086     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
12087                                 : diag::warn_this_bool_conversion;
12088     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
12089     return;
12090   }
12091 
12092   bool IsAddressOf = false;
12093 
12094   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12095     if (UO->getOpcode() != UO_AddrOf)
12096       return;
12097     IsAddressOf = true;
12098     E = UO->getSubExpr();
12099   }
12100 
12101   if (IsAddressOf) {
12102     unsigned DiagID = IsCompare
12103                           ? diag::warn_address_of_reference_null_compare
12104                           : diag::warn_address_of_reference_bool_conversion;
12105     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
12106                                          << IsEqual;
12107     if (CheckForReference(*this, E, PD)) {
12108       return;
12109     }
12110   }
12111 
12112   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
12113     bool IsParam = isa<NonNullAttr>(NonnullAttr);
12114     std::string Str;
12115     llvm::raw_string_ostream S(Str);
12116     E->printPretty(S, nullptr, getPrintingPolicy());
12117     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
12118                                 : diag::warn_cast_nonnull_to_bool;
12119     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
12120       << E->getSourceRange() << Range << IsEqual;
12121     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
12122   };
12123 
12124   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
12125   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
12126     if (auto *Callee = Call->getDirectCallee()) {
12127       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
12128         ComplainAboutNonnullParamOrCall(A);
12129         return;
12130       }
12131     }
12132   }
12133 
12134   // Expect to find a single Decl.  Skip anything more complicated.
12135   ValueDecl *D = nullptr;
12136   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
12137     D = R->getDecl();
12138   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12139     D = M->getMemberDecl();
12140   }
12141 
12142   // Weak Decls can be null.
12143   if (!D || D->isWeak())
12144     return;
12145 
12146   // Check for parameter decl with nonnull attribute
12147   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
12148     if (getCurFunction() &&
12149         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
12150       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
12151         ComplainAboutNonnullParamOrCall(A);
12152         return;
12153       }
12154 
12155       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
12156         // Skip function template not specialized yet.
12157         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
12158           return;
12159         auto ParamIter = llvm::find(FD->parameters(), PV);
12160         assert(ParamIter != FD->param_end());
12161         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
12162 
12163         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
12164           if (!NonNull->args_size()) {
12165               ComplainAboutNonnullParamOrCall(NonNull);
12166               return;
12167           }
12168 
12169           for (const ParamIdx &ArgNo : NonNull->args()) {
12170             if (ArgNo.getASTIndex() == ParamNo) {
12171               ComplainAboutNonnullParamOrCall(NonNull);
12172               return;
12173             }
12174           }
12175         }
12176       }
12177     }
12178   }
12179 
12180   QualType T = D->getType();
12181   const bool IsArray = T->isArrayType();
12182   const bool IsFunction = T->isFunctionType();
12183 
12184   // Address of function is used to silence the function warning.
12185   if (IsAddressOf && IsFunction) {
12186     return;
12187   }
12188 
12189   // Found nothing.
12190   if (!IsAddressOf && !IsFunction && !IsArray)
12191     return;
12192 
12193   // Pretty print the expression for the diagnostic.
12194   std::string Str;
12195   llvm::raw_string_ostream S(Str);
12196   E->printPretty(S, nullptr, getPrintingPolicy());
12197 
12198   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
12199                               : diag::warn_impcast_pointer_to_bool;
12200   enum {
12201     AddressOf,
12202     FunctionPointer,
12203     ArrayPointer
12204   } DiagType;
12205   if (IsAddressOf)
12206     DiagType = AddressOf;
12207   else if (IsFunction)
12208     DiagType = FunctionPointer;
12209   else if (IsArray)
12210     DiagType = ArrayPointer;
12211   else
12212     llvm_unreachable("Could not determine diagnostic.");
12213   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
12214                                 << Range << IsEqual;
12215 
12216   if (!IsFunction)
12217     return;
12218 
12219   // Suggest '&' to silence the function warning.
12220   Diag(E->getExprLoc(), diag::note_function_warning_silence)
12221       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
12222 
12223   // Check to see if '()' fixit should be emitted.
12224   QualType ReturnType;
12225   UnresolvedSet<4> NonTemplateOverloads;
12226   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
12227   if (ReturnType.isNull())
12228     return;
12229 
12230   if (IsCompare) {
12231     // There are two cases here.  If there is null constant, the only suggest
12232     // for a pointer return type.  If the null is 0, then suggest if the return
12233     // type is a pointer or an integer type.
12234     if (!ReturnType->isPointerType()) {
12235       if (NullKind == Expr::NPCK_ZeroExpression ||
12236           NullKind == Expr::NPCK_ZeroLiteral) {
12237         if (!ReturnType->isIntegerType())
12238           return;
12239       } else {
12240         return;
12241       }
12242     }
12243   } else { // !IsCompare
12244     // For function to bool, only suggest if the function pointer has bool
12245     // return type.
12246     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
12247       return;
12248   }
12249   Diag(E->getExprLoc(), diag::note_function_to_function_call)
12250       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
12251 }
12252 
12253 /// Diagnoses "dangerous" implicit conversions within the given
12254 /// expression (which is a full expression).  Implements -Wconversion
12255 /// and -Wsign-compare.
12256 ///
12257 /// \param CC the "context" location of the implicit conversion, i.e.
12258 ///   the most location of the syntactic entity requiring the implicit
12259 ///   conversion
12260 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
12261   // Don't diagnose in unevaluated contexts.
12262   if (isUnevaluatedContext())
12263     return;
12264 
12265   // Don't diagnose for value- or type-dependent expressions.
12266   if (E->isTypeDependent() || E->isValueDependent())
12267     return;
12268 
12269   // Check for array bounds violations in cases where the check isn't triggered
12270   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
12271   // ArraySubscriptExpr is on the RHS of a variable initialization.
12272   CheckArrayAccess(E);
12273 
12274   // This is not the right CC for (e.g.) a variable initialization.
12275   AnalyzeImplicitConversions(*this, E, CC);
12276 }
12277 
12278 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
12279 /// Input argument E is a logical expression.
12280 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
12281   ::CheckBoolLikeConversion(*this, E, CC);
12282 }
12283 
12284 /// Diagnose when expression is an integer constant expression and its evaluation
12285 /// results in integer overflow
12286 void Sema::CheckForIntOverflow (Expr *E) {
12287   // Use a work list to deal with nested struct initializers.
12288   SmallVector<Expr *, 2> Exprs(1, E);
12289 
12290   do {
12291     Expr *OriginalE = Exprs.pop_back_val();
12292     Expr *E = OriginalE->IgnoreParenCasts();
12293 
12294     if (isa<BinaryOperator>(E)) {
12295       E->EvaluateForOverflow(Context);
12296       continue;
12297     }
12298 
12299     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
12300       Exprs.append(InitList->inits().begin(), InitList->inits().end());
12301     else if (isa<ObjCBoxedExpr>(OriginalE))
12302       E->EvaluateForOverflow(Context);
12303     else if (auto Call = dyn_cast<CallExpr>(E))
12304       Exprs.append(Call->arg_begin(), Call->arg_end());
12305     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
12306       Exprs.append(Message->arg_begin(), Message->arg_end());
12307   } while (!Exprs.empty());
12308 }
12309 
12310 namespace {
12311 
12312 /// Visitor for expressions which looks for unsequenced operations on the
12313 /// same object.
12314 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
12315   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
12316 
12317   /// A tree of sequenced regions within an expression. Two regions are
12318   /// unsequenced if one is an ancestor or a descendent of the other. When we
12319   /// finish processing an expression with sequencing, such as a comma
12320   /// expression, we fold its tree nodes into its parent, since they are
12321   /// unsequenced with respect to nodes we will visit later.
12322   class SequenceTree {
12323     struct Value {
12324       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
12325       unsigned Parent : 31;
12326       unsigned Merged : 1;
12327     };
12328     SmallVector<Value, 8> Values;
12329 
12330   public:
12331     /// A region within an expression which may be sequenced with respect
12332     /// to some other region.
12333     class Seq {
12334       friend class SequenceTree;
12335 
12336       unsigned Index;
12337 
12338       explicit Seq(unsigned N) : Index(N) {}
12339 
12340     public:
12341       Seq() : Index(0) {}
12342     };
12343 
12344     SequenceTree() { Values.push_back(Value(0)); }
12345     Seq root() const { return Seq(0); }
12346 
12347     /// Create a new sequence of operations, which is an unsequenced
12348     /// subset of \p Parent. This sequence of operations is sequenced with
12349     /// respect to other children of \p Parent.
12350     Seq allocate(Seq Parent) {
12351       Values.push_back(Value(Parent.Index));
12352       return Seq(Values.size() - 1);
12353     }
12354 
12355     /// Merge a sequence of operations into its parent.
12356     void merge(Seq S) {
12357       Values[S.Index].Merged = true;
12358     }
12359 
12360     /// Determine whether two operations are unsequenced. This operation
12361     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
12362     /// should have been merged into its parent as appropriate.
12363     bool isUnsequenced(Seq Cur, Seq Old) {
12364       unsigned C = representative(Cur.Index);
12365       unsigned Target = representative(Old.Index);
12366       while (C >= Target) {
12367         if (C == Target)
12368           return true;
12369         C = Values[C].Parent;
12370       }
12371       return false;
12372     }
12373 
12374   private:
12375     /// Pick a representative for a sequence.
12376     unsigned representative(unsigned K) {
12377       if (Values[K].Merged)
12378         // Perform path compression as we go.
12379         return Values[K].Parent = representative(Values[K].Parent);
12380       return K;
12381     }
12382   };
12383 
12384   /// An object for which we can track unsequenced uses.
12385   using Object = const NamedDecl *;
12386 
12387   /// Different flavors of object usage which we track. We only track the
12388   /// least-sequenced usage of each kind.
12389   enum UsageKind {
12390     /// A read of an object. Multiple unsequenced reads are OK.
12391     UK_Use,
12392 
12393     /// A modification of an object which is sequenced before the value
12394     /// computation of the expression, such as ++n in C++.
12395     UK_ModAsValue,
12396 
12397     /// A modification of an object which is not sequenced before the value
12398     /// computation of the expression, such as n++.
12399     UK_ModAsSideEffect,
12400 
12401     UK_Count = UK_ModAsSideEffect + 1
12402   };
12403 
12404   /// Bundle together a sequencing region and the expression corresponding
12405   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
12406   struct Usage {
12407     const Expr *UsageExpr;
12408     SequenceTree::Seq Seq;
12409 
12410     Usage() : UsageExpr(nullptr), Seq() {}
12411   };
12412 
12413   struct UsageInfo {
12414     Usage Uses[UK_Count];
12415 
12416     /// Have we issued a diagnostic for this object already?
12417     bool Diagnosed;
12418 
12419     UsageInfo() : Uses(), Diagnosed(false) {}
12420   };
12421   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
12422 
12423   Sema &SemaRef;
12424 
12425   /// Sequenced regions within the expression.
12426   SequenceTree Tree;
12427 
12428   /// Declaration modifications and references which we have seen.
12429   UsageInfoMap UsageMap;
12430 
12431   /// The region we are currently within.
12432   SequenceTree::Seq Region;
12433 
12434   /// Filled in with declarations which were modified as a side-effect
12435   /// (that is, post-increment operations).
12436   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
12437 
12438   /// Expressions to check later. We defer checking these to reduce
12439   /// stack usage.
12440   SmallVectorImpl<const Expr *> &WorkList;
12441 
12442   /// RAII object wrapping the visitation of a sequenced subexpression of an
12443   /// expression. At the end of this process, the side-effects of the evaluation
12444   /// become sequenced with respect to the value computation of the result, so
12445   /// we downgrade any UK_ModAsSideEffect within the evaluation to
12446   /// UK_ModAsValue.
12447   struct SequencedSubexpression {
12448     SequencedSubexpression(SequenceChecker &Self)
12449       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
12450       Self.ModAsSideEffect = &ModAsSideEffect;
12451     }
12452 
12453     ~SequencedSubexpression() {
12454       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
12455         // Add a new usage with usage kind UK_ModAsValue, and then restore
12456         // the previous usage with UK_ModAsSideEffect (thus clearing it if
12457         // the previous one was empty).
12458         UsageInfo &UI = Self.UsageMap[M.first];
12459         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
12460         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
12461         SideEffectUsage = M.second;
12462       }
12463       Self.ModAsSideEffect = OldModAsSideEffect;
12464     }
12465 
12466     SequenceChecker &Self;
12467     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
12468     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
12469   };
12470 
12471   /// RAII object wrapping the visitation of a subexpression which we might
12472   /// choose to evaluate as a constant. If any subexpression is evaluated and
12473   /// found to be non-constant, this allows us to suppress the evaluation of
12474   /// the outer expression.
12475   class EvaluationTracker {
12476   public:
12477     EvaluationTracker(SequenceChecker &Self)
12478         : Self(Self), Prev(Self.EvalTracker) {
12479       Self.EvalTracker = this;
12480     }
12481 
12482     ~EvaluationTracker() {
12483       Self.EvalTracker = Prev;
12484       if (Prev)
12485         Prev->EvalOK &= EvalOK;
12486     }
12487 
12488     bool evaluate(const Expr *E, bool &Result) {
12489       if (!EvalOK || E->isValueDependent())
12490         return false;
12491       EvalOK = E->EvaluateAsBooleanCondition(
12492           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
12493       return EvalOK;
12494     }
12495 
12496   private:
12497     SequenceChecker &Self;
12498     EvaluationTracker *Prev;
12499     bool EvalOK = true;
12500   } *EvalTracker = nullptr;
12501 
12502   /// Find the object which is produced by the specified expression,
12503   /// if any.
12504   Object getObject(const Expr *E, bool Mod) const {
12505     E = E->IgnoreParenCasts();
12506     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12507       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
12508         return getObject(UO->getSubExpr(), Mod);
12509     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12510       if (BO->getOpcode() == BO_Comma)
12511         return getObject(BO->getRHS(), Mod);
12512       if (Mod && BO->isAssignmentOp())
12513         return getObject(BO->getLHS(), Mod);
12514     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12515       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
12516       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
12517         return ME->getMemberDecl();
12518     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12519       // FIXME: If this is a reference, map through to its value.
12520       return DRE->getDecl();
12521     return nullptr;
12522   }
12523 
12524   /// Note that an object \p O was modified or used by an expression
12525   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
12526   /// the object \p O as obtained via the \p UsageMap.
12527   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
12528     // Get the old usage for the given object and usage kind.
12529     Usage &U = UI.Uses[UK];
12530     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
12531       // If we have a modification as side effect and are in a sequenced
12532       // subexpression, save the old Usage so that we can restore it later
12533       // in SequencedSubexpression::~SequencedSubexpression.
12534       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
12535         ModAsSideEffect->push_back(std::make_pair(O, U));
12536       // Then record the new usage with the current sequencing region.
12537       U.UsageExpr = UsageExpr;
12538       U.Seq = Region;
12539     }
12540   }
12541 
12542   /// Check whether a modification or use of an object \p O in an expression
12543   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
12544   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
12545   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
12546   /// usage and false we are checking for a mod-use unsequenced usage.
12547   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
12548                   UsageKind OtherKind, bool IsModMod) {
12549     if (UI.Diagnosed)
12550       return;
12551 
12552     const Usage &U = UI.Uses[OtherKind];
12553     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
12554       return;
12555 
12556     const Expr *Mod = U.UsageExpr;
12557     const Expr *ModOrUse = UsageExpr;
12558     if (OtherKind == UK_Use)
12559       std::swap(Mod, ModOrUse);
12560 
12561     SemaRef.DiagRuntimeBehavior(
12562         Mod->getExprLoc(), {Mod, ModOrUse},
12563         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
12564                                : diag::warn_unsequenced_mod_use)
12565             << O << SourceRange(ModOrUse->getExprLoc()));
12566     UI.Diagnosed = true;
12567   }
12568 
12569   // A note on note{Pre, Post}{Use, Mod}:
12570   //
12571   // (It helps to follow the algorithm with an expression such as
12572   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
12573   //  operations before C++17 and both are well-defined in C++17).
12574   //
12575   // When visiting a node which uses/modify an object we first call notePreUse
12576   // or notePreMod before visiting its sub-expression(s). At this point the
12577   // children of the current node have not yet been visited and so the eventual
12578   // uses/modifications resulting from the children of the current node have not
12579   // been recorded yet.
12580   //
12581   // We then visit the children of the current node. After that notePostUse or
12582   // notePostMod is called. These will 1) detect an unsequenced modification
12583   // as side effect (as in "k++ + k") and 2) add a new usage with the
12584   // appropriate usage kind.
12585   //
12586   // We also have to be careful that some operation sequences modification as
12587   // side effect as well (for example: || or ,). To account for this we wrap
12588   // the visitation of such a sub-expression (for example: the LHS of || or ,)
12589   // with SequencedSubexpression. SequencedSubexpression is an RAII object
12590   // which record usages which are modifications as side effect, and then
12591   // downgrade them (or more accurately restore the previous usage which was a
12592   // modification as side effect) when exiting the scope of the sequenced
12593   // subexpression.
12594 
12595   void notePreUse(Object O, const Expr *UseExpr) {
12596     UsageInfo &UI = UsageMap[O];
12597     // Uses conflict with other modifications.
12598     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
12599   }
12600 
12601   void notePostUse(Object O, const Expr *UseExpr) {
12602     UsageInfo &UI = UsageMap[O];
12603     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
12604                /*IsModMod=*/false);
12605     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
12606   }
12607 
12608   void notePreMod(Object O, const Expr *ModExpr) {
12609     UsageInfo &UI = UsageMap[O];
12610     // Modifications conflict with other modifications and with uses.
12611     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
12612     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
12613   }
12614 
12615   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
12616     UsageInfo &UI = UsageMap[O];
12617     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
12618                /*IsModMod=*/true);
12619     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
12620   }
12621 
12622 public:
12623   SequenceChecker(Sema &S, const Expr *E,
12624                   SmallVectorImpl<const Expr *> &WorkList)
12625       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
12626     Visit(E);
12627     // Silence a -Wunused-private-field since WorkList is now unused.
12628     // TODO: Evaluate if it can be used, and if not remove it.
12629     (void)this->WorkList;
12630   }
12631 
12632   void VisitStmt(const Stmt *S) {
12633     // Skip all statements which aren't expressions for now.
12634   }
12635 
12636   void VisitExpr(const Expr *E) {
12637     // By default, just recurse to evaluated subexpressions.
12638     Base::VisitStmt(E);
12639   }
12640 
12641   void VisitCastExpr(const CastExpr *E) {
12642     Object O = Object();
12643     if (E->getCastKind() == CK_LValueToRValue)
12644       O = getObject(E->getSubExpr(), false);
12645 
12646     if (O)
12647       notePreUse(O, E);
12648     VisitExpr(E);
12649     if (O)
12650       notePostUse(O, E);
12651   }
12652 
12653   void VisitSequencedExpressions(const Expr *SequencedBefore,
12654                                  const Expr *SequencedAfter) {
12655     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
12656     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
12657     SequenceTree::Seq OldRegion = Region;
12658 
12659     {
12660       SequencedSubexpression SeqBefore(*this);
12661       Region = BeforeRegion;
12662       Visit(SequencedBefore);
12663     }
12664 
12665     Region = AfterRegion;
12666     Visit(SequencedAfter);
12667 
12668     Region = OldRegion;
12669 
12670     Tree.merge(BeforeRegion);
12671     Tree.merge(AfterRegion);
12672   }
12673 
12674   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
12675     // C++17 [expr.sub]p1:
12676     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
12677     //   expression E1 is sequenced before the expression E2.
12678     if (SemaRef.getLangOpts().CPlusPlus17)
12679       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
12680     else {
12681       Visit(ASE->getLHS());
12682       Visit(ASE->getRHS());
12683     }
12684   }
12685 
12686   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
12687   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
12688   void VisitBinPtrMem(const BinaryOperator *BO) {
12689     // C++17 [expr.mptr.oper]p4:
12690     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
12691     //  the expression E1 is sequenced before the expression E2.
12692     if (SemaRef.getLangOpts().CPlusPlus17)
12693       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12694     else {
12695       Visit(BO->getLHS());
12696       Visit(BO->getRHS());
12697     }
12698   }
12699 
12700   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
12701   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
12702   void VisitBinShlShr(const BinaryOperator *BO) {
12703     // C++17 [expr.shift]p4:
12704     //  The expression E1 is sequenced before the expression E2.
12705     if (SemaRef.getLangOpts().CPlusPlus17)
12706       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12707     else {
12708       Visit(BO->getLHS());
12709       Visit(BO->getRHS());
12710     }
12711   }
12712 
12713   void VisitBinComma(const BinaryOperator *BO) {
12714     // C++11 [expr.comma]p1:
12715     //   Every value computation and side effect associated with the left
12716     //   expression is sequenced before every value computation and side
12717     //   effect associated with the right expression.
12718     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12719   }
12720 
12721   void VisitBinAssign(const BinaryOperator *BO) {
12722     SequenceTree::Seq RHSRegion;
12723     SequenceTree::Seq LHSRegion;
12724     if (SemaRef.getLangOpts().CPlusPlus17) {
12725       RHSRegion = Tree.allocate(Region);
12726       LHSRegion = Tree.allocate(Region);
12727     } else {
12728       RHSRegion = Region;
12729       LHSRegion = Region;
12730     }
12731     SequenceTree::Seq OldRegion = Region;
12732 
12733     // C++11 [expr.ass]p1:
12734     //  [...] the assignment is sequenced after the value computation
12735     //  of the right and left operands, [...]
12736     //
12737     // so check it before inspecting the operands and update the
12738     // map afterwards.
12739     Object O = getObject(BO->getLHS(), /*Mod=*/true);
12740     if (O)
12741       notePreMod(O, BO);
12742 
12743     if (SemaRef.getLangOpts().CPlusPlus17) {
12744       // C++17 [expr.ass]p1:
12745       //  [...] The right operand is sequenced before the left operand. [...]
12746       {
12747         SequencedSubexpression SeqBefore(*this);
12748         Region = RHSRegion;
12749         Visit(BO->getRHS());
12750       }
12751 
12752       Region = LHSRegion;
12753       Visit(BO->getLHS());
12754 
12755       if (O && isa<CompoundAssignOperator>(BO))
12756         notePostUse(O, BO);
12757 
12758     } else {
12759       // C++11 does not specify any sequencing between the LHS and RHS.
12760       Region = LHSRegion;
12761       Visit(BO->getLHS());
12762 
12763       if (O && isa<CompoundAssignOperator>(BO))
12764         notePostUse(O, BO);
12765 
12766       Region = RHSRegion;
12767       Visit(BO->getRHS());
12768     }
12769 
12770     // C++11 [expr.ass]p1:
12771     //  the assignment is sequenced [...] before the value computation of the
12772     //  assignment expression.
12773     // C11 6.5.16/3 has no such rule.
12774     Region = OldRegion;
12775     if (O)
12776       notePostMod(O, BO,
12777                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12778                                                   : UK_ModAsSideEffect);
12779     if (SemaRef.getLangOpts().CPlusPlus17) {
12780       Tree.merge(RHSRegion);
12781       Tree.merge(LHSRegion);
12782     }
12783   }
12784 
12785   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
12786     VisitBinAssign(CAO);
12787   }
12788 
12789   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12790   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12791   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
12792     Object O = getObject(UO->getSubExpr(), true);
12793     if (!O)
12794       return VisitExpr(UO);
12795 
12796     notePreMod(O, UO);
12797     Visit(UO->getSubExpr());
12798     // C++11 [expr.pre.incr]p1:
12799     //   the expression ++x is equivalent to x+=1
12800     notePostMod(O, UO,
12801                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12802                                                 : UK_ModAsSideEffect);
12803   }
12804 
12805   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12806   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12807   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
12808     Object O = getObject(UO->getSubExpr(), true);
12809     if (!O)
12810       return VisitExpr(UO);
12811 
12812     notePreMod(O, UO);
12813     Visit(UO->getSubExpr());
12814     notePostMod(O, UO, UK_ModAsSideEffect);
12815   }
12816 
12817   void VisitBinLOr(const BinaryOperator *BO) {
12818     // C++11 [expr.log.or]p2:
12819     //  If the second expression is evaluated, every value computation and
12820     //  side effect associated with the first expression is sequenced before
12821     //  every value computation and side effect associated with the
12822     //  second expression.
12823     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
12824     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
12825     SequenceTree::Seq OldRegion = Region;
12826 
12827     EvaluationTracker Eval(*this);
12828     {
12829       SequencedSubexpression Sequenced(*this);
12830       Region = LHSRegion;
12831       Visit(BO->getLHS());
12832     }
12833 
12834     // C++11 [expr.log.or]p1:
12835     //  [...] the second operand is not evaluated if the first operand
12836     //  evaluates to true.
12837     bool EvalResult = false;
12838     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
12839     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
12840     if (ShouldVisitRHS) {
12841       Region = RHSRegion;
12842       Visit(BO->getRHS());
12843     }
12844 
12845     Region = OldRegion;
12846     Tree.merge(LHSRegion);
12847     Tree.merge(RHSRegion);
12848   }
12849 
12850   void VisitBinLAnd(const BinaryOperator *BO) {
12851     // C++11 [expr.log.and]p2:
12852     //  If the second expression is evaluated, every value computation and
12853     //  side effect associated with the first expression is sequenced before
12854     //  every value computation and side effect associated with the
12855     //  second expression.
12856     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
12857     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
12858     SequenceTree::Seq OldRegion = Region;
12859 
12860     EvaluationTracker Eval(*this);
12861     {
12862       SequencedSubexpression Sequenced(*this);
12863       Region = LHSRegion;
12864       Visit(BO->getLHS());
12865     }
12866 
12867     // C++11 [expr.log.and]p1:
12868     //  [...] the second operand is not evaluated if the first operand is false.
12869     bool EvalResult = false;
12870     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
12871     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
12872     if (ShouldVisitRHS) {
12873       Region = RHSRegion;
12874       Visit(BO->getRHS());
12875     }
12876 
12877     Region = OldRegion;
12878     Tree.merge(LHSRegion);
12879     Tree.merge(RHSRegion);
12880   }
12881 
12882   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
12883     // C++11 [expr.cond]p1:
12884     //  [...] Every value computation and side effect associated with the first
12885     //  expression is sequenced before every value computation and side effect
12886     //  associated with the second or third expression.
12887     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
12888 
12889     // No sequencing is specified between the true and false expression.
12890     // However since exactly one of both is going to be evaluated we can
12891     // consider them to be sequenced. This is needed to avoid warning on
12892     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
12893     // both the true and false expressions because we can't evaluate x.
12894     // This will still allow us to detect an expression like (pre C++17)
12895     // "(x ? y += 1 : y += 2) = y".
12896     //
12897     // We don't wrap the visitation of the true and false expression with
12898     // SequencedSubexpression because we don't want to downgrade modifications
12899     // as side effect in the true and false expressions after the visition
12900     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
12901     // not warn between the two "y++", but we should warn between the "y++"
12902     // and the "y".
12903     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
12904     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
12905     SequenceTree::Seq OldRegion = Region;
12906 
12907     EvaluationTracker Eval(*this);
12908     {
12909       SequencedSubexpression Sequenced(*this);
12910       Region = ConditionRegion;
12911       Visit(CO->getCond());
12912     }
12913 
12914     // C++11 [expr.cond]p1:
12915     // [...] The first expression is contextually converted to bool (Clause 4).
12916     // It is evaluated and if it is true, the result of the conditional
12917     // expression is the value of the second expression, otherwise that of the
12918     // third expression. Only one of the second and third expressions is
12919     // evaluated. [...]
12920     bool EvalResult = false;
12921     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
12922     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
12923     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
12924     if (ShouldVisitTrueExpr) {
12925       Region = TrueRegion;
12926       Visit(CO->getTrueExpr());
12927     }
12928     if (ShouldVisitFalseExpr) {
12929       Region = FalseRegion;
12930       Visit(CO->getFalseExpr());
12931     }
12932 
12933     Region = OldRegion;
12934     Tree.merge(ConditionRegion);
12935     Tree.merge(TrueRegion);
12936     Tree.merge(FalseRegion);
12937   }
12938 
12939   void VisitCallExpr(const CallExpr *CE) {
12940     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
12941 
12942     if (CE->isUnevaluatedBuiltinCall(Context))
12943       return;
12944 
12945     // C++11 [intro.execution]p15:
12946     //   When calling a function [...], every value computation and side effect
12947     //   associated with any argument expression, or with the postfix expression
12948     //   designating the called function, is sequenced before execution of every
12949     //   expression or statement in the body of the function [and thus before
12950     //   the value computation of its result].
12951     SequencedSubexpression Sequenced(*this);
12952     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
12953       // C++17 [expr.call]p5
12954       //   The postfix-expression is sequenced before each expression in the
12955       //   expression-list and any default argument. [...]
12956       SequenceTree::Seq CalleeRegion;
12957       SequenceTree::Seq OtherRegion;
12958       if (SemaRef.getLangOpts().CPlusPlus17) {
12959         CalleeRegion = Tree.allocate(Region);
12960         OtherRegion = Tree.allocate(Region);
12961       } else {
12962         CalleeRegion = Region;
12963         OtherRegion = Region;
12964       }
12965       SequenceTree::Seq OldRegion = Region;
12966 
12967       // Visit the callee expression first.
12968       Region = CalleeRegion;
12969       if (SemaRef.getLangOpts().CPlusPlus17) {
12970         SequencedSubexpression Sequenced(*this);
12971         Visit(CE->getCallee());
12972       } else {
12973         Visit(CE->getCallee());
12974       }
12975 
12976       // Then visit the argument expressions.
12977       Region = OtherRegion;
12978       for (const Expr *Argument : CE->arguments())
12979         Visit(Argument);
12980 
12981       Region = OldRegion;
12982       if (SemaRef.getLangOpts().CPlusPlus17) {
12983         Tree.merge(CalleeRegion);
12984         Tree.merge(OtherRegion);
12985       }
12986     });
12987   }
12988 
12989   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
12990     // This is a call, so all subexpressions are sequenced before the result.
12991     SequencedSubexpression Sequenced(*this);
12992 
12993     if (!CCE->isListInitialization())
12994       return VisitExpr(CCE);
12995 
12996     // In C++11, list initializations are sequenced.
12997     SmallVector<SequenceTree::Seq, 32> Elts;
12998     SequenceTree::Seq Parent = Region;
12999     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
13000                                               E = CCE->arg_end();
13001          I != E; ++I) {
13002       Region = Tree.allocate(Parent);
13003       Elts.push_back(Region);
13004       Visit(*I);
13005     }
13006 
13007     // Forget that the initializers are sequenced.
13008     Region = Parent;
13009     for (unsigned I = 0; I < Elts.size(); ++I)
13010       Tree.merge(Elts[I]);
13011   }
13012 
13013   void VisitInitListExpr(const InitListExpr *ILE) {
13014     if (!SemaRef.getLangOpts().CPlusPlus11)
13015       return VisitExpr(ILE);
13016 
13017     // In C++11, list initializations are sequenced.
13018     SmallVector<SequenceTree::Seq, 32> Elts;
13019     SequenceTree::Seq Parent = Region;
13020     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
13021       const Expr *E = ILE->getInit(I);
13022       if (!E)
13023         continue;
13024       Region = Tree.allocate(Parent);
13025       Elts.push_back(Region);
13026       Visit(E);
13027     }
13028 
13029     // Forget that the initializers are sequenced.
13030     Region = Parent;
13031     for (unsigned I = 0; I < Elts.size(); ++I)
13032       Tree.merge(Elts[I]);
13033   }
13034 };
13035 
13036 } // namespace
13037 
13038 void Sema::CheckUnsequencedOperations(const Expr *E) {
13039   SmallVector<const Expr *, 8> WorkList;
13040   WorkList.push_back(E);
13041   while (!WorkList.empty()) {
13042     const Expr *Item = WorkList.pop_back_val();
13043     SequenceChecker(*this, Item, WorkList);
13044   }
13045 }
13046 
13047 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
13048                               bool IsConstexpr) {
13049   llvm::SaveAndRestore<bool> ConstantContext(
13050       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
13051   CheckImplicitConversions(E, CheckLoc);
13052   if (!E->isInstantiationDependent())
13053     CheckUnsequencedOperations(E);
13054   if (!IsConstexpr && !E->isValueDependent())
13055     CheckForIntOverflow(E);
13056   DiagnoseMisalignedMembers();
13057 }
13058 
13059 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
13060                                        FieldDecl *BitField,
13061                                        Expr *Init) {
13062   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
13063 }
13064 
13065 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
13066                                          SourceLocation Loc) {
13067   if (!PType->isVariablyModifiedType())
13068     return;
13069   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
13070     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
13071     return;
13072   }
13073   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
13074     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
13075     return;
13076   }
13077   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
13078     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
13079     return;
13080   }
13081 
13082   const ArrayType *AT = S.Context.getAsArrayType(PType);
13083   if (!AT)
13084     return;
13085 
13086   if (AT->getSizeModifier() != ArrayType::Star) {
13087     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
13088     return;
13089   }
13090 
13091   S.Diag(Loc, diag::err_array_star_in_function_definition);
13092 }
13093 
13094 /// CheckParmsForFunctionDef - Check that the parameters of the given
13095 /// function are appropriate for the definition of a function. This
13096 /// takes care of any checks that cannot be performed on the
13097 /// declaration itself, e.g., that the types of each of the function
13098 /// parameters are complete.
13099 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
13100                                     bool CheckParameterNames) {
13101   bool HasInvalidParm = false;
13102   for (ParmVarDecl *Param : Parameters) {
13103     // C99 6.7.5.3p4: the parameters in a parameter type list in a
13104     // function declarator that is part of a function definition of
13105     // that function shall not have incomplete type.
13106     //
13107     // This is also C++ [dcl.fct]p6.
13108     if (!Param->isInvalidDecl() &&
13109         RequireCompleteType(Param->getLocation(), Param->getType(),
13110                             diag::err_typecheck_decl_incomplete_type)) {
13111       Param->setInvalidDecl();
13112       HasInvalidParm = true;
13113     }
13114 
13115     // C99 6.9.1p5: If the declarator includes a parameter type list, the
13116     // declaration of each parameter shall include an identifier.
13117     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
13118         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
13119       // Diagnose this as an extension in C17 and earlier.
13120       if (!getLangOpts().C2x)
13121         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
13122     }
13123 
13124     // C99 6.7.5.3p12:
13125     //   If the function declarator is not part of a definition of that
13126     //   function, parameters may have incomplete type and may use the [*]
13127     //   notation in their sequences of declarator specifiers to specify
13128     //   variable length array types.
13129     QualType PType = Param->getOriginalType();
13130     // FIXME: This diagnostic should point the '[*]' if source-location
13131     // information is added for it.
13132     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
13133 
13134     // If the parameter is a c++ class type and it has to be destructed in the
13135     // callee function, declare the destructor so that it can be called by the
13136     // callee function. Do not perform any direct access check on the dtor here.
13137     if (!Param->isInvalidDecl()) {
13138       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
13139         if (!ClassDecl->isInvalidDecl() &&
13140             !ClassDecl->hasIrrelevantDestructor() &&
13141             !ClassDecl->isDependentContext() &&
13142             ClassDecl->isParamDestroyedInCallee()) {
13143           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
13144           MarkFunctionReferenced(Param->getLocation(), Destructor);
13145           DiagnoseUseOfDecl(Destructor, Param->getLocation());
13146         }
13147       }
13148     }
13149 
13150     // Parameters with the pass_object_size attribute only need to be marked
13151     // constant at function definitions. Because we lack information about
13152     // whether we're on a declaration or definition when we're instantiating the
13153     // attribute, we need to check for constness here.
13154     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
13155       if (!Param->getType().isConstQualified())
13156         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
13157             << Attr->getSpelling() << 1;
13158 
13159     // Check for parameter names shadowing fields from the class.
13160     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
13161       // The owning context for the parameter should be the function, but we
13162       // want to see if this function's declaration context is a record.
13163       DeclContext *DC = Param->getDeclContext();
13164       if (DC && DC->isFunctionOrMethod()) {
13165         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
13166           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
13167                                      RD, /*DeclIsField*/ false);
13168       }
13169     }
13170   }
13171 
13172   return HasInvalidParm;
13173 }
13174 
13175 Optional<std::pair<CharUnits, CharUnits>>
13176 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
13177 
13178 /// Compute the alignment and offset of the base class object given the
13179 /// derived-to-base cast expression and the alignment and offset of the derived
13180 /// class object.
13181 static std::pair<CharUnits, CharUnits>
13182 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
13183                                    CharUnits BaseAlignment, CharUnits Offset,
13184                                    ASTContext &Ctx) {
13185   for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
13186        ++PathI) {
13187     const CXXBaseSpecifier *Base = *PathI;
13188     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
13189     if (Base->isVirtual()) {
13190       // The complete object may have a lower alignment than the non-virtual
13191       // alignment of the base, in which case the base may be misaligned. Choose
13192       // the smaller of the non-virtual alignment and BaseAlignment, which is a
13193       // conservative lower bound of the complete object alignment.
13194       CharUnits NonVirtualAlignment =
13195           Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
13196       BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
13197       Offset = CharUnits::Zero();
13198     } else {
13199       const ASTRecordLayout &RL =
13200           Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
13201       Offset += RL.getBaseClassOffset(BaseDecl);
13202     }
13203     DerivedType = Base->getType();
13204   }
13205 
13206   return std::make_pair(BaseAlignment, Offset);
13207 }
13208 
13209 /// Compute the alignment and offset of a binary additive operator.
13210 static Optional<std::pair<CharUnits, CharUnits>>
13211 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
13212                                      bool IsSub, ASTContext &Ctx) {
13213   QualType PointeeType = PtrE->getType()->getPointeeType();
13214 
13215   if (!PointeeType->isConstantSizeType())
13216     return llvm::None;
13217 
13218   auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
13219 
13220   if (!P)
13221     return llvm::None;
13222 
13223   llvm::APSInt IdxRes;
13224   CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
13225   if (IntE->isIntegerConstantExpr(IdxRes, Ctx)) {
13226     CharUnits Offset = EltSize * IdxRes.getExtValue();
13227     if (IsSub)
13228       Offset = -Offset;
13229     return std::make_pair(P->first, P->second + Offset);
13230   }
13231 
13232   // If the integer expression isn't a constant expression, compute the lower
13233   // bound of the alignment using the alignment and offset of the pointer
13234   // expression and the element size.
13235   return std::make_pair(
13236       P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
13237       CharUnits::Zero());
13238 }
13239 
13240 /// This helper function takes an lvalue expression and returns the alignment of
13241 /// a VarDecl and a constant offset from the VarDecl.
13242 Optional<std::pair<CharUnits, CharUnits>>
13243 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
13244   E = E->IgnoreParens();
13245   switch (E->getStmtClass()) {
13246   default:
13247     break;
13248   case Stmt::CStyleCastExprClass:
13249   case Stmt::CXXStaticCastExprClass:
13250   case Stmt::ImplicitCastExprClass: {
13251     auto *CE = cast<CastExpr>(E);
13252     const Expr *From = CE->getSubExpr();
13253     switch (CE->getCastKind()) {
13254     default:
13255       break;
13256     case CK_NoOp:
13257       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
13258     case CK_UncheckedDerivedToBase:
13259     case CK_DerivedToBase: {
13260       auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
13261       if (!P)
13262         break;
13263       return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
13264                                                 P->second, Ctx);
13265     }
13266     }
13267     break;
13268   }
13269   case Stmt::ArraySubscriptExprClass: {
13270     auto *ASE = cast<ArraySubscriptExpr>(E);
13271     return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
13272                                                 false, Ctx);
13273   }
13274   case Stmt::DeclRefExprClass: {
13275     if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
13276       // FIXME: If VD is captured by copy or is an escaping __block variable,
13277       // use the alignment of VD's type.
13278       if (!VD->getType()->isReferenceType())
13279         return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
13280       if (VD->hasInit())
13281         return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
13282     }
13283     break;
13284   }
13285   case Stmt::MemberExprClass: {
13286     auto *ME = cast<MemberExpr>(E);
13287     if (ME->isArrow())
13288       break;
13289     auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
13290     if (!FD || FD->getType()->isReferenceType())
13291       break;
13292     auto P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
13293     if (!P)
13294       break;
13295     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
13296     uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
13297     return std::make_pair(P->first,
13298                           P->second + CharUnits::fromQuantity(Offset));
13299   }
13300   case Stmt::UnaryOperatorClass: {
13301     auto *UO = cast<UnaryOperator>(E);
13302     switch (UO->getOpcode()) {
13303     default:
13304       break;
13305     case UO_Deref:
13306       return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
13307     }
13308     break;
13309   }
13310   case Stmt::BinaryOperatorClass: {
13311     auto *BO = cast<BinaryOperator>(E);
13312     auto Opcode = BO->getOpcode();
13313     switch (Opcode) {
13314     default:
13315       break;
13316     case BO_Comma:
13317       return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
13318     }
13319     break;
13320   }
13321   }
13322   return llvm::None;
13323 }
13324 
13325 /// This helper function takes a pointer expression and returns the alignment of
13326 /// a VarDecl and a constant offset from the VarDecl.
13327 Optional<std::pair<CharUnits, CharUnits>>
13328 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
13329   E = E->IgnoreParens();
13330   switch (E->getStmtClass()) {
13331   default:
13332     break;
13333   case Stmt::CStyleCastExprClass:
13334   case Stmt::CXXStaticCastExprClass:
13335   case Stmt::ImplicitCastExprClass: {
13336     auto *CE = cast<CastExpr>(E);
13337     const Expr *From = CE->getSubExpr();
13338     switch (CE->getCastKind()) {
13339     default:
13340       break;
13341     case CK_NoOp:
13342       return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
13343     case CK_ArrayToPointerDecay:
13344       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
13345     case CK_UncheckedDerivedToBase:
13346     case CK_DerivedToBase: {
13347       auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
13348       if (!P)
13349         break;
13350       return getDerivedToBaseAlignmentAndOffset(
13351           CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
13352     }
13353     }
13354     break;
13355   }
13356   case Stmt::UnaryOperatorClass: {
13357     auto *UO = cast<UnaryOperator>(E);
13358     if (UO->getOpcode() == UO_AddrOf)
13359       return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
13360     break;
13361   }
13362   case Stmt::BinaryOperatorClass: {
13363     auto *BO = cast<BinaryOperator>(E);
13364     auto Opcode = BO->getOpcode();
13365     switch (Opcode) {
13366     default:
13367       break;
13368     case BO_Add:
13369     case BO_Sub: {
13370       const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
13371       if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
13372         std::swap(LHS, RHS);
13373       return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
13374                                                   Ctx);
13375     }
13376     case BO_Comma:
13377       return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
13378     }
13379     break;
13380   }
13381   }
13382   return llvm::None;
13383 }
13384 
13385 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
13386   // See if we can compute the alignment of a VarDecl and an offset from it.
13387   Optional<std::pair<CharUnits, CharUnits>> P =
13388       getBaseAlignmentAndOffsetFromPtr(E, S.Context);
13389 
13390   if (P)
13391     return P->first.alignmentAtOffset(P->second);
13392 
13393   // If that failed, return the type's alignment.
13394   return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
13395 }
13396 
13397 /// CheckCastAlign - Implements -Wcast-align, which warns when a
13398 /// pointer cast increases the alignment requirements.
13399 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
13400   // This is actually a lot of work to potentially be doing on every
13401   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
13402   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
13403     return;
13404 
13405   // Ignore dependent types.
13406   if (T->isDependentType() || Op->getType()->isDependentType())
13407     return;
13408 
13409   // Require that the destination be a pointer type.
13410   const PointerType *DestPtr = T->getAs<PointerType>();
13411   if (!DestPtr) return;
13412 
13413   // If the destination has alignment 1, we're done.
13414   QualType DestPointee = DestPtr->getPointeeType();
13415   if (DestPointee->isIncompleteType()) return;
13416   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
13417   if (DestAlign.isOne()) return;
13418 
13419   // Require that the source be a pointer type.
13420   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
13421   if (!SrcPtr) return;
13422   QualType SrcPointee = SrcPtr->getPointeeType();
13423 
13424   // Whitelist casts from cv void*.  We already implicitly
13425   // whitelisted casts to cv void*, since they have alignment 1.
13426   // Also whitelist casts involving incomplete types, which implicitly
13427   // includes 'void'.
13428   if (SrcPointee->isIncompleteType()) return;
13429 
13430   CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
13431 
13432   if (SrcAlign >= DestAlign) return;
13433 
13434   Diag(TRange.getBegin(), diag::warn_cast_align)
13435     << Op->getType() << T
13436     << static_cast<unsigned>(SrcAlign.getQuantity())
13437     << static_cast<unsigned>(DestAlign.getQuantity())
13438     << TRange << Op->getSourceRange();
13439 }
13440 
13441 /// Check whether this array fits the idiom of a size-one tail padded
13442 /// array member of a struct.
13443 ///
13444 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
13445 /// commonly used to emulate flexible arrays in C89 code.
13446 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
13447                                     const NamedDecl *ND) {
13448   if (Size != 1 || !ND) return false;
13449 
13450   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
13451   if (!FD) return false;
13452 
13453   // Don't consider sizes resulting from macro expansions or template argument
13454   // substitution to form C89 tail-padded arrays.
13455 
13456   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
13457   while (TInfo) {
13458     TypeLoc TL = TInfo->getTypeLoc();
13459     // Look through typedefs.
13460     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
13461       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
13462       TInfo = TDL->getTypeSourceInfo();
13463       continue;
13464     }
13465     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
13466       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
13467       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
13468         return false;
13469     }
13470     break;
13471   }
13472 
13473   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
13474   if (!RD) return false;
13475   if (RD->isUnion()) return false;
13476   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
13477     if (!CRD->isStandardLayout()) return false;
13478   }
13479 
13480   // See if this is the last field decl in the record.
13481   const Decl *D = FD;
13482   while ((D = D->getNextDeclInContext()))
13483     if (isa<FieldDecl>(D))
13484       return false;
13485   return true;
13486 }
13487 
13488 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
13489                             const ArraySubscriptExpr *ASE,
13490                             bool AllowOnePastEnd, bool IndexNegated) {
13491   // Already diagnosed by the constant evaluator.
13492   if (isConstantEvaluated())
13493     return;
13494 
13495   IndexExpr = IndexExpr->IgnoreParenImpCasts();
13496   if (IndexExpr->isValueDependent())
13497     return;
13498 
13499   const Type *EffectiveType =
13500       BaseExpr->getType()->getPointeeOrArrayElementType();
13501   BaseExpr = BaseExpr->IgnoreParenCasts();
13502   const ConstantArrayType *ArrayTy =
13503       Context.getAsConstantArrayType(BaseExpr->getType());
13504 
13505   if (!ArrayTy)
13506     return;
13507 
13508   const Type *BaseType = ArrayTy->getElementType().getTypePtr();
13509   if (EffectiveType->isDependentType() || BaseType->isDependentType())
13510     return;
13511 
13512   Expr::EvalResult Result;
13513   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
13514     return;
13515 
13516   llvm::APSInt index = Result.Val.getInt();
13517   if (IndexNegated)
13518     index = -index;
13519 
13520   const NamedDecl *ND = nullptr;
13521   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
13522     ND = DRE->getDecl();
13523   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
13524     ND = ME->getMemberDecl();
13525 
13526   if (index.isUnsigned() || !index.isNegative()) {
13527     // It is possible that the type of the base expression after
13528     // IgnoreParenCasts is incomplete, even though the type of the base
13529     // expression before IgnoreParenCasts is complete (see PR39746 for an
13530     // example). In this case we have no information about whether the array
13531     // access exceeds the array bounds. However we can still diagnose an array
13532     // access which precedes the array bounds.
13533     if (BaseType->isIncompleteType())
13534       return;
13535 
13536     llvm::APInt size = ArrayTy->getSize();
13537     if (!size.isStrictlyPositive())
13538       return;
13539 
13540     if (BaseType != EffectiveType) {
13541       // Make sure we're comparing apples to apples when comparing index to size
13542       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
13543       uint64_t array_typesize = Context.getTypeSize(BaseType);
13544       // Handle ptrarith_typesize being zero, such as when casting to void*
13545       if (!ptrarith_typesize) ptrarith_typesize = 1;
13546       if (ptrarith_typesize != array_typesize) {
13547         // There's a cast to a different size type involved
13548         uint64_t ratio = array_typesize / ptrarith_typesize;
13549         // TODO: Be smarter about handling cases where array_typesize is not a
13550         // multiple of ptrarith_typesize
13551         if (ptrarith_typesize * ratio == array_typesize)
13552           size *= llvm::APInt(size.getBitWidth(), ratio);
13553       }
13554     }
13555 
13556     if (size.getBitWidth() > index.getBitWidth())
13557       index = index.zext(size.getBitWidth());
13558     else if (size.getBitWidth() < index.getBitWidth())
13559       size = size.zext(index.getBitWidth());
13560 
13561     // For array subscripting the index must be less than size, but for pointer
13562     // arithmetic also allow the index (offset) to be equal to size since
13563     // computing the next address after the end of the array is legal and
13564     // commonly done e.g. in C++ iterators and range-based for loops.
13565     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
13566       return;
13567 
13568     // Also don't warn for arrays of size 1 which are members of some
13569     // structure. These are often used to approximate flexible arrays in C89
13570     // code.
13571     if (IsTailPaddedMemberArray(*this, size, ND))
13572       return;
13573 
13574     // Suppress the warning if the subscript expression (as identified by the
13575     // ']' location) and the index expression are both from macro expansions
13576     // within a system header.
13577     if (ASE) {
13578       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
13579           ASE->getRBracketLoc());
13580       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
13581         SourceLocation IndexLoc =
13582             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
13583         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
13584           return;
13585       }
13586     }
13587 
13588     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
13589     if (ASE)
13590       DiagID = diag::warn_array_index_exceeds_bounds;
13591 
13592     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
13593                         PDiag(DiagID) << index.toString(10, true)
13594                                       << size.toString(10, true)
13595                                       << (unsigned)size.getLimitedValue(~0U)
13596                                       << IndexExpr->getSourceRange());
13597   } else {
13598     unsigned DiagID = diag::warn_array_index_precedes_bounds;
13599     if (!ASE) {
13600       DiagID = diag::warn_ptr_arith_precedes_bounds;
13601       if (index.isNegative()) index = -index;
13602     }
13603 
13604     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
13605                         PDiag(DiagID) << index.toString(10, true)
13606                                       << IndexExpr->getSourceRange());
13607   }
13608 
13609   if (!ND) {
13610     // Try harder to find a NamedDecl to point at in the note.
13611     while (const ArraySubscriptExpr *ASE =
13612            dyn_cast<ArraySubscriptExpr>(BaseExpr))
13613       BaseExpr = ASE->getBase()->IgnoreParenCasts();
13614     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
13615       ND = DRE->getDecl();
13616     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
13617       ND = ME->getMemberDecl();
13618   }
13619 
13620   if (ND)
13621     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
13622                         PDiag(diag::note_array_declared_here)
13623                             << ND->getDeclName());
13624 }
13625 
13626 void Sema::CheckArrayAccess(const Expr *expr) {
13627   int AllowOnePastEnd = 0;
13628   while (expr) {
13629     expr = expr->IgnoreParenImpCasts();
13630     switch (expr->getStmtClass()) {
13631       case Stmt::ArraySubscriptExprClass: {
13632         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
13633         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
13634                          AllowOnePastEnd > 0);
13635         expr = ASE->getBase();
13636         break;
13637       }
13638       case Stmt::MemberExprClass: {
13639         expr = cast<MemberExpr>(expr)->getBase();
13640         break;
13641       }
13642       case Stmt::OMPArraySectionExprClass: {
13643         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
13644         if (ASE->getLowerBound())
13645           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
13646                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
13647         return;
13648       }
13649       case Stmt::UnaryOperatorClass: {
13650         // Only unwrap the * and & unary operators
13651         const UnaryOperator *UO = cast<UnaryOperator>(expr);
13652         expr = UO->getSubExpr();
13653         switch (UO->getOpcode()) {
13654           case UO_AddrOf:
13655             AllowOnePastEnd++;
13656             break;
13657           case UO_Deref:
13658             AllowOnePastEnd--;
13659             break;
13660           default:
13661             return;
13662         }
13663         break;
13664       }
13665       case Stmt::ConditionalOperatorClass: {
13666         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
13667         if (const Expr *lhs = cond->getLHS())
13668           CheckArrayAccess(lhs);
13669         if (const Expr *rhs = cond->getRHS())
13670           CheckArrayAccess(rhs);
13671         return;
13672       }
13673       case Stmt::CXXOperatorCallExprClass: {
13674         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
13675         for (const auto *Arg : OCE->arguments())
13676           CheckArrayAccess(Arg);
13677         return;
13678       }
13679       default:
13680         return;
13681     }
13682   }
13683 }
13684 
13685 //===--- CHECK: Objective-C retain cycles ----------------------------------//
13686 
13687 namespace {
13688 
13689 struct RetainCycleOwner {
13690   VarDecl *Variable = nullptr;
13691   SourceRange Range;
13692   SourceLocation Loc;
13693   bool Indirect = false;
13694 
13695   RetainCycleOwner() = default;
13696 
13697   void setLocsFrom(Expr *e) {
13698     Loc = e->getExprLoc();
13699     Range = e->getSourceRange();
13700   }
13701 };
13702 
13703 } // namespace
13704 
13705 /// Consider whether capturing the given variable can possibly lead to
13706 /// a retain cycle.
13707 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
13708   // In ARC, it's captured strongly iff the variable has __strong
13709   // lifetime.  In MRR, it's captured strongly if the variable is
13710   // __block and has an appropriate type.
13711   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
13712     return false;
13713 
13714   owner.Variable = var;
13715   if (ref)
13716     owner.setLocsFrom(ref);
13717   return true;
13718 }
13719 
13720 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
13721   while (true) {
13722     e = e->IgnoreParens();
13723     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
13724       switch (cast->getCastKind()) {
13725       case CK_BitCast:
13726       case CK_LValueBitCast:
13727       case CK_LValueToRValue:
13728       case CK_ARCReclaimReturnedObject:
13729         e = cast->getSubExpr();
13730         continue;
13731 
13732       default:
13733         return false;
13734       }
13735     }
13736 
13737     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
13738       ObjCIvarDecl *ivar = ref->getDecl();
13739       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
13740         return false;
13741 
13742       // Try to find a retain cycle in the base.
13743       if (!findRetainCycleOwner(S, ref->getBase(), owner))
13744         return false;
13745 
13746       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
13747       owner.Indirect = true;
13748       return true;
13749     }
13750 
13751     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
13752       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
13753       if (!var) return false;
13754       return considerVariable(var, ref, owner);
13755     }
13756 
13757     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
13758       if (member->isArrow()) return false;
13759 
13760       // Don't count this as an indirect ownership.
13761       e = member->getBase();
13762       continue;
13763     }
13764 
13765     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
13766       // Only pay attention to pseudo-objects on property references.
13767       ObjCPropertyRefExpr *pre
13768         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
13769                                               ->IgnoreParens());
13770       if (!pre) return false;
13771       if (pre->isImplicitProperty()) return false;
13772       ObjCPropertyDecl *property = pre->getExplicitProperty();
13773       if (!property->isRetaining() &&
13774           !(property->getPropertyIvarDecl() &&
13775             property->getPropertyIvarDecl()->getType()
13776               .getObjCLifetime() == Qualifiers::OCL_Strong))
13777           return false;
13778 
13779       owner.Indirect = true;
13780       if (pre->isSuperReceiver()) {
13781         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
13782         if (!owner.Variable)
13783           return false;
13784         owner.Loc = pre->getLocation();
13785         owner.Range = pre->getSourceRange();
13786         return true;
13787       }
13788       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
13789                               ->getSourceExpr());
13790       continue;
13791     }
13792 
13793     // Array ivars?
13794 
13795     return false;
13796   }
13797 }
13798 
13799 namespace {
13800 
13801   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
13802     ASTContext &Context;
13803     VarDecl *Variable;
13804     Expr *Capturer = nullptr;
13805     bool VarWillBeReased = false;
13806 
13807     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
13808         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
13809           Context(Context), Variable(variable) {}
13810 
13811     void VisitDeclRefExpr(DeclRefExpr *ref) {
13812       if (ref->getDecl() == Variable && !Capturer)
13813         Capturer = ref;
13814     }
13815 
13816     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
13817       if (Capturer) return;
13818       Visit(ref->getBase());
13819       if (Capturer && ref->isFreeIvar())
13820         Capturer = ref;
13821     }
13822 
13823     void VisitBlockExpr(BlockExpr *block) {
13824       // Look inside nested blocks
13825       if (block->getBlockDecl()->capturesVariable(Variable))
13826         Visit(block->getBlockDecl()->getBody());
13827     }
13828 
13829     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
13830       if (Capturer) return;
13831       if (OVE->getSourceExpr())
13832         Visit(OVE->getSourceExpr());
13833     }
13834 
13835     void VisitBinaryOperator(BinaryOperator *BinOp) {
13836       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
13837         return;
13838       Expr *LHS = BinOp->getLHS();
13839       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
13840         if (DRE->getDecl() != Variable)
13841           return;
13842         if (Expr *RHS = BinOp->getRHS()) {
13843           RHS = RHS->IgnoreParenCasts();
13844           llvm::APSInt Value;
13845           VarWillBeReased =
13846             (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
13847         }
13848       }
13849     }
13850   };
13851 
13852 } // namespace
13853 
13854 /// Check whether the given argument is a block which captures a
13855 /// variable.
13856 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
13857   assert(owner.Variable && owner.Loc.isValid());
13858 
13859   e = e->IgnoreParenCasts();
13860 
13861   // Look through [^{...} copy] and Block_copy(^{...}).
13862   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
13863     Selector Cmd = ME->getSelector();
13864     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
13865       e = ME->getInstanceReceiver();
13866       if (!e)
13867         return nullptr;
13868       e = e->IgnoreParenCasts();
13869     }
13870   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
13871     if (CE->getNumArgs() == 1) {
13872       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
13873       if (Fn) {
13874         const IdentifierInfo *FnI = Fn->getIdentifier();
13875         if (FnI && FnI->isStr("_Block_copy")) {
13876           e = CE->getArg(0)->IgnoreParenCasts();
13877         }
13878       }
13879     }
13880   }
13881 
13882   BlockExpr *block = dyn_cast<BlockExpr>(e);
13883   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
13884     return nullptr;
13885 
13886   FindCaptureVisitor visitor(S.Context, owner.Variable);
13887   visitor.Visit(block->getBlockDecl()->getBody());
13888   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
13889 }
13890 
13891 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
13892                                 RetainCycleOwner &owner) {
13893   assert(capturer);
13894   assert(owner.Variable && owner.Loc.isValid());
13895 
13896   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
13897     << owner.Variable << capturer->getSourceRange();
13898   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
13899     << owner.Indirect << owner.Range;
13900 }
13901 
13902 /// Check for a keyword selector that starts with the word 'add' or
13903 /// 'set'.
13904 static bool isSetterLikeSelector(Selector sel) {
13905   if (sel.isUnarySelector()) return false;
13906 
13907   StringRef str = sel.getNameForSlot(0);
13908   while (!str.empty() && str.front() == '_') str = str.substr(1);
13909   if (str.startswith("set"))
13910     str = str.substr(3);
13911   else if (str.startswith("add")) {
13912     // Specially whitelist 'addOperationWithBlock:'.
13913     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
13914       return false;
13915     str = str.substr(3);
13916   }
13917   else
13918     return false;
13919 
13920   if (str.empty()) return true;
13921   return !isLowercase(str.front());
13922 }
13923 
13924 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
13925                                                     ObjCMessageExpr *Message) {
13926   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
13927                                                 Message->getReceiverInterface(),
13928                                                 NSAPI::ClassId_NSMutableArray);
13929   if (!IsMutableArray) {
13930     return None;
13931   }
13932 
13933   Selector Sel = Message->getSelector();
13934 
13935   Optional<NSAPI::NSArrayMethodKind> MKOpt =
13936     S.NSAPIObj->getNSArrayMethodKind(Sel);
13937   if (!MKOpt) {
13938     return None;
13939   }
13940 
13941   NSAPI::NSArrayMethodKind MK = *MKOpt;
13942 
13943   switch (MK) {
13944     case NSAPI::NSMutableArr_addObject:
13945     case NSAPI::NSMutableArr_insertObjectAtIndex:
13946     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
13947       return 0;
13948     case NSAPI::NSMutableArr_replaceObjectAtIndex:
13949       return 1;
13950 
13951     default:
13952       return None;
13953   }
13954 
13955   return None;
13956 }
13957 
13958 static
13959 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
13960                                                   ObjCMessageExpr *Message) {
13961   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
13962                                             Message->getReceiverInterface(),
13963                                             NSAPI::ClassId_NSMutableDictionary);
13964   if (!IsMutableDictionary) {
13965     return None;
13966   }
13967 
13968   Selector Sel = Message->getSelector();
13969 
13970   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
13971     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
13972   if (!MKOpt) {
13973     return None;
13974   }
13975 
13976   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
13977 
13978   switch (MK) {
13979     case NSAPI::NSMutableDict_setObjectForKey:
13980     case NSAPI::NSMutableDict_setValueForKey:
13981     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
13982       return 0;
13983 
13984     default:
13985       return None;
13986   }
13987 
13988   return None;
13989 }
13990 
13991 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
13992   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
13993                                                 Message->getReceiverInterface(),
13994                                                 NSAPI::ClassId_NSMutableSet);
13995 
13996   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
13997                                             Message->getReceiverInterface(),
13998                                             NSAPI::ClassId_NSMutableOrderedSet);
13999   if (!IsMutableSet && !IsMutableOrderedSet) {
14000     return None;
14001   }
14002 
14003   Selector Sel = Message->getSelector();
14004 
14005   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
14006   if (!MKOpt) {
14007     return None;
14008   }
14009 
14010   NSAPI::NSSetMethodKind MK = *MKOpt;
14011 
14012   switch (MK) {
14013     case NSAPI::NSMutableSet_addObject:
14014     case NSAPI::NSOrderedSet_setObjectAtIndex:
14015     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
14016     case NSAPI::NSOrderedSet_insertObjectAtIndex:
14017       return 0;
14018     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
14019       return 1;
14020   }
14021 
14022   return None;
14023 }
14024 
14025 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
14026   if (!Message->isInstanceMessage()) {
14027     return;
14028   }
14029 
14030   Optional<int> ArgOpt;
14031 
14032   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
14033       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
14034       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
14035     return;
14036   }
14037 
14038   int ArgIndex = *ArgOpt;
14039 
14040   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
14041   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
14042     Arg = OE->getSourceExpr()->IgnoreImpCasts();
14043   }
14044 
14045   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
14046     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
14047       if (ArgRE->isObjCSelfExpr()) {
14048         Diag(Message->getSourceRange().getBegin(),
14049              diag::warn_objc_circular_container)
14050           << ArgRE->getDecl() << StringRef("'super'");
14051       }
14052     }
14053   } else {
14054     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
14055 
14056     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
14057       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
14058     }
14059 
14060     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
14061       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
14062         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
14063           ValueDecl *Decl = ReceiverRE->getDecl();
14064           Diag(Message->getSourceRange().getBegin(),
14065                diag::warn_objc_circular_container)
14066             << Decl << Decl;
14067           if (!ArgRE->isObjCSelfExpr()) {
14068             Diag(Decl->getLocation(),
14069                  diag::note_objc_circular_container_declared_here)
14070               << Decl;
14071           }
14072         }
14073       }
14074     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
14075       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
14076         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
14077           ObjCIvarDecl *Decl = IvarRE->getDecl();
14078           Diag(Message->getSourceRange().getBegin(),
14079                diag::warn_objc_circular_container)
14080             << Decl << Decl;
14081           Diag(Decl->getLocation(),
14082                diag::note_objc_circular_container_declared_here)
14083             << Decl;
14084         }
14085       }
14086     }
14087   }
14088 }
14089 
14090 /// Check a message send to see if it's likely to cause a retain cycle.
14091 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
14092   // Only check instance methods whose selector looks like a setter.
14093   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
14094     return;
14095 
14096   // Try to find a variable that the receiver is strongly owned by.
14097   RetainCycleOwner owner;
14098   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
14099     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
14100       return;
14101   } else {
14102     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
14103     owner.Variable = getCurMethodDecl()->getSelfDecl();
14104     owner.Loc = msg->getSuperLoc();
14105     owner.Range = msg->getSuperLoc();
14106   }
14107 
14108   // Check whether the receiver is captured by any of the arguments.
14109   const ObjCMethodDecl *MD = msg->getMethodDecl();
14110   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
14111     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
14112       // noescape blocks should not be retained by the method.
14113       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
14114         continue;
14115       return diagnoseRetainCycle(*this, capturer, owner);
14116     }
14117   }
14118 }
14119 
14120 /// Check a property assign to see if it's likely to cause a retain cycle.
14121 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
14122   RetainCycleOwner owner;
14123   if (!findRetainCycleOwner(*this, receiver, owner))
14124     return;
14125 
14126   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
14127     diagnoseRetainCycle(*this, capturer, owner);
14128 }
14129 
14130 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
14131   RetainCycleOwner Owner;
14132   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
14133     return;
14134 
14135   // Because we don't have an expression for the variable, we have to set the
14136   // location explicitly here.
14137   Owner.Loc = Var->getLocation();
14138   Owner.Range = Var->getSourceRange();
14139 
14140   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
14141     diagnoseRetainCycle(*this, Capturer, Owner);
14142 }
14143 
14144 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
14145                                      Expr *RHS, bool isProperty) {
14146   // Check if RHS is an Objective-C object literal, which also can get
14147   // immediately zapped in a weak reference.  Note that we explicitly
14148   // allow ObjCStringLiterals, since those are designed to never really die.
14149   RHS = RHS->IgnoreParenImpCasts();
14150 
14151   // This enum needs to match with the 'select' in
14152   // warn_objc_arc_literal_assign (off-by-1).
14153   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
14154   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
14155     return false;
14156 
14157   S.Diag(Loc, diag::warn_arc_literal_assign)
14158     << (unsigned) Kind
14159     << (isProperty ? 0 : 1)
14160     << RHS->getSourceRange();
14161 
14162   return true;
14163 }
14164 
14165 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
14166                                     Qualifiers::ObjCLifetime LT,
14167                                     Expr *RHS, bool isProperty) {
14168   // Strip off any implicit cast added to get to the one ARC-specific.
14169   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
14170     if (cast->getCastKind() == CK_ARCConsumeObject) {
14171       S.Diag(Loc, diag::warn_arc_retained_assign)
14172         << (LT == Qualifiers::OCL_ExplicitNone)
14173         << (isProperty ? 0 : 1)
14174         << RHS->getSourceRange();
14175       return true;
14176     }
14177     RHS = cast->getSubExpr();
14178   }
14179 
14180   if (LT == Qualifiers::OCL_Weak &&
14181       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
14182     return true;
14183 
14184   return false;
14185 }
14186 
14187 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
14188                               QualType LHS, Expr *RHS) {
14189   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
14190 
14191   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
14192     return false;
14193 
14194   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
14195     return true;
14196 
14197   return false;
14198 }
14199 
14200 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
14201                               Expr *LHS, Expr *RHS) {
14202   QualType LHSType;
14203   // PropertyRef on LHS type need be directly obtained from
14204   // its declaration as it has a PseudoType.
14205   ObjCPropertyRefExpr *PRE
14206     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
14207   if (PRE && !PRE->isImplicitProperty()) {
14208     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
14209     if (PD)
14210       LHSType = PD->getType();
14211   }
14212 
14213   if (LHSType.isNull())
14214     LHSType = LHS->getType();
14215 
14216   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
14217 
14218   if (LT == Qualifiers::OCL_Weak) {
14219     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
14220       getCurFunction()->markSafeWeakUse(LHS);
14221   }
14222 
14223   if (checkUnsafeAssigns(Loc, LHSType, RHS))
14224     return;
14225 
14226   // FIXME. Check for other life times.
14227   if (LT != Qualifiers::OCL_None)
14228     return;
14229 
14230   if (PRE) {
14231     if (PRE->isImplicitProperty())
14232       return;
14233     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
14234     if (!PD)
14235       return;
14236 
14237     unsigned Attributes = PD->getPropertyAttributes();
14238     if (Attributes & ObjCPropertyAttribute::kind_assign) {
14239       // when 'assign' attribute was not explicitly specified
14240       // by user, ignore it and rely on property type itself
14241       // for lifetime info.
14242       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
14243       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
14244           LHSType->isObjCRetainableType())
14245         return;
14246 
14247       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
14248         if (cast->getCastKind() == CK_ARCConsumeObject) {
14249           Diag(Loc, diag::warn_arc_retained_property_assign)
14250           << RHS->getSourceRange();
14251           return;
14252         }
14253         RHS = cast->getSubExpr();
14254       }
14255     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
14256       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
14257         return;
14258     }
14259   }
14260 }
14261 
14262 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
14263 
14264 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
14265                                         SourceLocation StmtLoc,
14266                                         const NullStmt *Body) {
14267   // Do not warn if the body is a macro that expands to nothing, e.g:
14268   //
14269   // #define CALL(x)
14270   // if (condition)
14271   //   CALL(0);
14272   if (Body->hasLeadingEmptyMacro())
14273     return false;
14274 
14275   // Get line numbers of statement and body.
14276   bool StmtLineInvalid;
14277   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
14278                                                       &StmtLineInvalid);
14279   if (StmtLineInvalid)
14280     return false;
14281 
14282   bool BodyLineInvalid;
14283   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
14284                                                       &BodyLineInvalid);
14285   if (BodyLineInvalid)
14286     return false;
14287 
14288   // Warn if null statement and body are on the same line.
14289   if (StmtLine != BodyLine)
14290     return false;
14291 
14292   return true;
14293 }
14294 
14295 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
14296                                  const Stmt *Body,
14297                                  unsigned DiagID) {
14298   // Since this is a syntactic check, don't emit diagnostic for template
14299   // instantiations, this just adds noise.
14300   if (CurrentInstantiationScope)
14301     return;
14302 
14303   // The body should be a null statement.
14304   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
14305   if (!NBody)
14306     return;
14307 
14308   // Do the usual checks.
14309   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
14310     return;
14311 
14312   Diag(NBody->getSemiLoc(), DiagID);
14313   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
14314 }
14315 
14316 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
14317                                  const Stmt *PossibleBody) {
14318   assert(!CurrentInstantiationScope); // Ensured by caller
14319 
14320   SourceLocation StmtLoc;
14321   const Stmt *Body;
14322   unsigned DiagID;
14323   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
14324     StmtLoc = FS->getRParenLoc();
14325     Body = FS->getBody();
14326     DiagID = diag::warn_empty_for_body;
14327   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
14328     StmtLoc = WS->getCond()->getSourceRange().getEnd();
14329     Body = WS->getBody();
14330     DiagID = diag::warn_empty_while_body;
14331   } else
14332     return; // Neither `for' nor `while'.
14333 
14334   // The body should be a null statement.
14335   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
14336   if (!NBody)
14337     return;
14338 
14339   // Skip expensive checks if diagnostic is disabled.
14340   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
14341     return;
14342 
14343   // Do the usual checks.
14344   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
14345     return;
14346 
14347   // `for(...);' and `while(...);' are popular idioms, so in order to keep
14348   // noise level low, emit diagnostics only if for/while is followed by a
14349   // CompoundStmt, e.g.:
14350   //    for (int i = 0; i < n; i++);
14351   //    {
14352   //      a(i);
14353   //    }
14354   // or if for/while is followed by a statement with more indentation
14355   // than for/while itself:
14356   //    for (int i = 0; i < n; i++);
14357   //      a(i);
14358   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
14359   if (!ProbableTypo) {
14360     bool BodyColInvalid;
14361     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
14362         PossibleBody->getBeginLoc(), &BodyColInvalid);
14363     if (BodyColInvalid)
14364       return;
14365 
14366     bool StmtColInvalid;
14367     unsigned StmtCol =
14368         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
14369     if (StmtColInvalid)
14370       return;
14371 
14372     if (BodyCol > StmtCol)
14373       ProbableTypo = true;
14374   }
14375 
14376   if (ProbableTypo) {
14377     Diag(NBody->getSemiLoc(), DiagID);
14378     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
14379   }
14380 }
14381 
14382 //===--- CHECK: Warn on self move with std::move. -------------------------===//
14383 
14384 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
14385 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
14386                              SourceLocation OpLoc) {
14387   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
14388     return;
14389 
14390   if (inTemplateInstantiation())
14391     return;
14392 
14393   // Strip parens and casts away.
14394   LHSExpr = LHSExpr->IgnoreParenImpCasts();
14395   RHSExpr = RHSExpr->IgnoreParenImpCasts();
14396 
14397   // Check for a call expression
14398   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
14399   if (!CE || CE->getNumArgs() != 1)
14400     return;
14401 
14402   // Check for a call to std::move
14403   if (!CE->isCallToStdMove())
14404     return;
14405 
14406   // Get argument from std::move
14407   RHSExpr = CE->getArg(0);
14408 
14409   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
14410   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
14411 
14412   // Two DeclRefExpr's, check that the decls are the same.
14413   if (LHSDeclRef && RHSDeclRef) {
14414     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
14415       return;
14416     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
14417         RHSDeclRef->getDecl()->getCanonicalDecl())
14418       return;
14419 
14420     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14421                                         << LHSExpr->getSourceRange()
14422                                         << RHSExpr->getSourceRange();
14423     return;
14424   }
14425 
14426   // Member variables require a different approach to check for self moves.
14427   // MemberExpr's are the same if every nested MemberExpr refers to the same
14428   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
14429   // the base Expr's are CXXThisExpr's.
14430   const Expr *LHSBase = LHSExpr;
14431   const Expr *RHSBase = RHSExpr;
14432   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
14433   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
14434   if (!LHSME || !RHSME)
14435     return;
14436 
14437   while (LHSME && RHSME) {
14438     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
14439         RHSME->getMemberDecl()->getCanonicalDecl())
14440       return;
14441 
14442     LHSBase = LHSME->getBase();
14443     RHSBase = RHSME->getBase();
14444     LHSME = dyn_cast<MemberExpr>(LHSBase);
14445     RHSME = dyn_cast<MemberExpr>(RHSBase);
14446   }
14447 
14448   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
14449   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
14450   if (LHSDeclRef && RHSDeclRef) {
14451     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
14452       return;
14453     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
14454         RHSDeclRef->getDecl()->getCanonicalDecl())
14455       return;
14456 
14457     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14458                                         << LHSExpr->getSourceRange()
14459                                         << RHSExpr->getSourceRange();
14460     return;
14461   }
14462 
14463   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
14464     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14465                                         << LHSExpr->getSourceRange()
14466                                         << RHSExpr->getSourceRange();
14467 }
14468 
14469 //===--- Layout compatibility ----------------------------------------------//
14470 
14471 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
14472 
14473 /// Check if two enumeration types are layout-compatible.
14474 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
14475   // C++11 [dcl.enum] p8:
14476   // Two enumeration types are layout-compatible if they have the same
14477   // underlying type.
14478   return ED1->isComplete() && ED2->isComplete() &&
14479          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
14480 }
14481 
14482 /// Check if two fields are layout-compatible.
14483 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
14484                                FieldDecl *Field2) {
14485   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
14486     return false;
14487 
14488   if (Field1->isBitField() != Field2->isBitField())
14489     return false;
14490 
14491   if (Field1->isBitField()) {
14492     // Make sure that the bit-fields are the same length.
14493     unsigned Bits1 = Field1->getBitWidthValue(C);
14494     unsigned Bits2 = Field2->getBitWidthValue(C);
14495 
14496     if (Bits1 != Bits2)
14497       return false;
14498   }
14499 
14500   return true;
14501 }
14502 
14503 /// Check if two standard-layout structs are layout-compatible.
14504 /// (C++11 [class.mem] p17)
14505 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
14506                                      RecordDecl *RD2) {
14507   // If both records are C++ classes, check that base classes match.
14508   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
14509     // If one of records is a CXXRecordDecl we are in C++ mode,
14510     // thus the other one is a CXXRecordDecl, too.
14511     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
14512     // Check number of base classes.
14513     if (D1CXX->getNumBases() != D2CXX->getNumBases())
14514       return false;
14515 
14516     // Check the base classes.
14517     for (CXXRecordDecl::base_class_const_iterator
14518                Base1 = D1CXX->bases_begin(),
14519            BaseEnd1 = D1CXX->bases_end(),
14520               Base2 = D2CXX->bases_begin();
14521          Base1 != BaseEnd1;
14522          ++Base1, ++Base2) {
14523       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
14524         return false;
14525     }
14526   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
14527     // If only RD2 is a C++ class, it should have zero base classes.
14528     if (D2CXX->getNumBases() > 0)
14529       return false;
14530   }
14531 
14532   // Check the fields.
14533   RecordDecl::field_iterator Field2 = RD2->field_begin(),
14534                              Field2End = RD2->field_end(),
14535                              Field1 = RD1->field_begin(),
14536                              Field1End = RD1->field_end();
14537   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
14538     if (!isLayoutCompatible(C, *Field1, *Field2))
14539       return false;
14540   }
14541   if (Field1 != Field1End || Field2 != Field2End)
14542     return false;
14543 
14544   return true;
14545 }
14546 
14547 /// Check if two standard-layout unions are layout-compatible.
14548 /// (C++11 [class.mem] p18)
14549 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
14550                                     RecordDecl *RD2) {
14551   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
14552   for (auto *Field2 : RD2->fields())
14553     UnmatchedFields.insert(Field2);
14554 
14555   for (auto *Field1 : RD1->fields()) {
14556     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
14557         I = UnmatchedFields.begin(),
14558         E = UnmatchedFields.end();
14559 
14560     for ( ; I != E; ++I) {
14561       if (isLayoutCompatible(C, Field1, *I)) {
14562         bool Result = UnmatchedFields.erase(*I);
14563         (void) Result;
14564         assert(Result);
14565         break;
14566       }
14567     }
14568     if (I == E)
14569       return false;
14570   }
14571 
14572   return UnmatchedFields.empty();
14573 }
14574 
14575 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
14576                                RecordDecl *RD2) {
14577   if (RD1->isUnion() != RD2->isUnion())
14578     return false;
14579 
14580   if (RD1->isUnion())
14581     return isLayoutCompatibleUnion(C, RD1, RD2);
14582   else
14583     return isLayoutCompatibleStruct(C, RD1, RD2);
14584 }
14585 
14586 /// Check if two types are layout-compatible in C++11 sense.
14587 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
14588   if (T1.isNull() || T2.isNull())
14589     return false;
14590 
14591   // C++11 [basic.types] p11:
14592   // If two types T1 and T2 are the same type, then T1 and T2 are
14593   // layout-compatible types.
14594   if (C.hasSameType(T1, T2))
14595     return true;
14596 
14597   T1 = T1.getCanonicalType().getUnqualifiedType();
14598   T2 = T2.getCanonicalType().getUnqualifiedType();
14599 
14600   const Type::TypeClass TC1 = T1->getTypeClass();
14601   const Type::TypeClass TC2 = T2->getTypeClass();
14602 
14603   if (TC1 != TC2)
14604     return false;
14605 
14606   if (TC1 == Type::Enum) {
14607     return isLayoutCompatible(C,
14608                               cast<EnumType>(T1)->getDecl(),
14609                               cast<EnumType>(T2)->getDecl());
14610   } else if (TC1 == Type::Record) {
14611     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
14612       return false;
14613 
14614     return isLayoutCompatible(C,
14615                               cast<RecordType>(T1)->getDecl(),
14616                               cast<RecordType>(T2)->getDecl());
14617   }
14618 
14619   return false;
14620 }
14621 
14622 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
14623 
14624 /// Given a type tag expression find the type tag itself.
14625 ///
14626 /// \param TypeExpr Type tag expression, as it appears in user's code.
14627 ///
14628 /// \param VD Declaration of an identifier that appears in a type tag.
14629 ///
14630 /// \param MagicValue Type tag magic value.
14631 ///
14632 /// \param isConstantEvaluated wether the evalaution should be performed in
14633 
14634 /// constant context.
14635 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
14636                             const ValueDecl **VD, uint64_t *MagicValue,
14637                             bool isConstantEvaluated) {
14638   while(true) {
14639     if (!TypeExpr)
14640       return false;
14641 
14642     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
14643 
14644     switch (TypeExpr->getStmtClass()) {
14645     case Stmt::UnaryOperatorClass: {
14646       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
14647       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
14648         TypeExpr = UO->getSubExpr();
14649         continue;
14650       }
14651       return false;
14652     }
14653 
14654     case Stmt::DeclRefExprClass: {
14655       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
14656       *VD = DRE->getDecl();
14657       return true;
14658     }
14659 
14660     case Stmt::IntegerLiteralClass: {
14661       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
14662       llvm::APInt MagicValueAPInt = IL->getValue();
14663       if (MagicValueAPInt.getActiveBits() <= 64) {
14664         *MagicValue = MagicValueAPInt.getZExtValue();
14665         return true;
14666       } else
14667         return false;
14668     }
14669 
14670     case Stmt::BinaryConditionalOperatorClass:
14671     case Stmt::ConditionalOperatorClass: {
14672       const AbstractConditionalOperator *ACO =
14673           cast<AbstractConditionalOperator>(TypeExpr);
14674       bool Result;
14675       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
14676                                                      isConstantEvaluated)) {
14677         if (Result)
14678           TypeExpr = ACO->getTrueExpr();
14679         else
14680           TypeExpr = ACO->getFalseExpr();
14681         continue;
14682       }
14683       return false;
14684     }
14685 
14686     case Stmt::BinaryOperatorClass: {
14687       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
14688       if (BO->getOpcode() == BO_Comma) {
14689         TypeExpr = BO->getRHS();
14690         continue;
14691       }
14692       return false;
14693     }
14694 
14695     default:
14696       return false;
14697     }
14698   }
14699 }
14700 
14701 /// Retrieve the C type corresponding to type tag TypeExpr.
14702 ///
14703 /// \param TypeExpr Expression that specifies a type tag.
14704 ///
14705 /// \param MagicValues Registered magic values.
14706 ///
14707 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
14708 ///        kind.
14709 ///
14710 /// \param TypeInfo Information about the corresponding C type.
14711 ///
14712 /// \param isConstantEvaluated wether the evalaution should be performed in
14713 /// constant context.
14714 ///
14715 /// \returns true if the corresponding C type was found.
14716 static bool GetMatchingCType(
14717     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
14718     const ASTContext &Ctx,
14719     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
14720         *MagicValues,
14721     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
14722     bool isConstantEvaluated) {
14723   FoundWrongKind = false;
14724 
14725   // Variable declaration that has type_tag_for_datatype attribute.
14726   const ValueDecl *VD = nullptr;
14727 
14728   uint64_t MagicValue;
14729 
14730   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
14731     return false;
14732 
14733   if (VD) {
14734     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
14735       if (I->getArgumentKind() != ArgumentKind) {
14736         FoundWrongKind = true;
14737         return false;
14738       }
14739       TypeInfo.Type = I->getMatchingCType();
14740       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
14741       TypeInfo.MustBeNull = I->getMustBeNull();
14742       return true;
14743     }
14744     return false;
14745   }
14746 
14747   if (!MagicValues)
14748     return false;
14749 
14750   llvm::DenseMap<Sema::TypeTagMagicValue,
14751                  Sema::TypeTagData>::const_iterator I =
14752       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
14753   if (I == MagicValues->end())
14754     return false;
14755 
14756   TypeInfo = I->second;
14757   return true;
14758 }
14759 
14760 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
14761                                       uint64_t MagicValue, QualType Type,
14762                                       bool LayoutCompatible,
14763                                       bool MustBeNull) {
14764   if (!TypeTagForDatatypeMagicValues)
14765     TypeTagForDatatypeMagicValues.reset(
14766         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
14767 
14768   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
14769   (*TypeTagForDatatypeMagicValues)[Magic] =
14770       TypeTagData(Type, LayoutCompatible, MustBeNull);
14771 }
14772 
14773 static bool IsSameCharType(QualType T1, QualType T2) {
14774   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
14775   if (!BT1)
14776     return false;
14777 
14778   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
14779   if (!BT2)
14780     return false;
14781 
14782   BuiltinType::Kind T1Kind = BT1->getKind();
14783   BuiltinType::Kind T2Kind = BT2->getKind();
14784 
14785   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
14786          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
14787          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
14788          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
14789 }
14790 
14791 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
14792                                     const ArrayRef<const Expr *> ExprArgs,
14793                                     SourceLocation CallSiteLoc) {
14794   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
14795   bool IsPointerAttr = Attr->getIsPointer();
14796 
14797   // Retrieve the argument representing the 'type_tag'.
14798   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
14799   if (TypeTagIdxAST >= ExprArgs.size()) {
14800     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
14801         << 0 << Attr->getTypeTagIdx().getSourceIndex();
14802     return;
14803   }
14804   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
14805   bool FoundWrongKind;
14806   TypeTagData TypeInfo;
14807   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
14808                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
14809                         TypeInfo, isConstantEvaluated())) {
14810     if (FoundWrongKind)
14811       Diag(TypeTagExpr->getExprLoc(),
14812            diag::warn_type_tag_for_datatype_wrong_kind)
14813         << TypeTagExpr->getSourceRange();
14814     return;
14815   }
14816 
14817   // Retrieve the argument representing the 'arg_idx'.
14818   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
14819   if (ArgumentIdxAST >= ExprArgs.size()) {
14820     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
14821         << 1 << Attr->getArgumentIdx().getSourceIndex();
14822     return;
14823   }
14824   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
14825   if (IsPointerAttr) {
14826     // Skip implicit cast of pointer to `void *' (as a function argument).
14827     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
14828       if (ICE->getType()->isVoidPointerType() &&
14829           ICE->getCastKind() == CK_BitCast)
14830         ArgumentExpr = ICE->getSubExpr();
14831   }
14832   QualType ArgumentType = ArgumentExpr->getType();
14833 
14834   // Passing a `void*' pointer shouldn't trigger a warning.
14835   if (IsPointerAttr && ArgumentType->isVoidPointerType())
14836     return;
14837 
14838   if (TypeInfo.MustBeNull) {
14839     // Type tag with matching void type requires a null pointer.
14840     if (!ArgumentExpr->isNullPointerConstant(Context,
14841                                              Expr::NPC_ValueDependentIsNotNull)) {
14842       Diag(ArgumentExpr->getExprLoc(),
14843            diag::warn_type_safety_null_pointer_required)
14844           << ArgumentKind->getName()
14845           << ArgumentExpr->getSourceRange()
14846           << TypeTagExpr->getSourceRange();
14847     }
14848     return;
14849   }
14850 
14851   QualType RequiredType = TypeInfo.Type;
14852   if (IsPointerAttr)
14853     RequiredType = Context.getPointerType(RequiredType);
14854 
14855   bool mismatch = false;
14856   if (!TypeInfo.LayoutCompatible) {
14857     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
14858 
14859     // C++11 [basic.fundamental] p1:
14860     // Plain char, signed char, and unsigned char are three distinct types.
14861     //
14862     // But we treat plain `char' as equivalent to `signed char' or `unsigned
14863     // char' depending on the current char signedness mode.
14864     if (mismatch)
14865       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
14866                                            RequiredType->getPointeeType())) ||
14867           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
14868         mismatch = false;
14869   } else
14870     if (IsPointerAttr)
14871       mismatch = !isLayoutCompatible(Context,
14872                                      ArgumentType->getPointeeType(),
14873                                      RequiredType->getPointeeType());
14874     else
14875       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
14876 
14877   if (mismatch)
14878     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
14879         << ArgumentType << ArgumentKind
14880         << TypeInfo.LayoutCompatible << RequiredType
14881         << ArgumentExpr->getSourceRange()
14882         << TypeTagExpr->getSourceRange();
14883 }
14884 
14885 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
14886                                          CharUnits Alignment) {
14887   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
14888 }
14889 
14890 void Sema::DiagnoseMisalignedMembers() {
14891   for (MisalignedMember &m : MisalignedMembers) {
14892     const NamedDecl *ND = m.RD;
14893     if (ND->getName().empty()) {
14894       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
14895         ND = TD;
14896     }
14897     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
14898         << m.MD << ND << m.E->getSourceRange();
14899   }
14900   MisalignedMembers.clear();
14901 }
14902 
14903 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
14904   E = E->IgnoreParens();
14905   if (!T->isPointerType() && !T->isIntegerType())
14906     return;
14907   if (isa<UnaryOperator>(E) &&
14908       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
14909     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
14910     if (isa<MemberExpr>(Op)) {
14911       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
14912       if (MA != MisalignedMembers.end() &&
14913           (T->isIntegerType() ||
14914            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
14915                                    Context.getTypeAlignInChars(
14916                                        T->getPointeeType()) <= MA->Alignment))))
14917         MisalignedMembers.erase(MA);
14918     }
14919   }
14920 }
14921 
14922 void Sema::RefersToMemberWithReducedAlignment(
14923     Expr *E,
14924     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
14925         Action) {
14926   const auto *ME = dyn_cast<MemberExpr>(E);
14927   if (!ME)
14928     return;
14929 
14930   // No need to check expressions with an __unaligned-qualified type.
14931   if (E->getType().getQualifiers().hasUnaligned())
14932     return;
14933 
14934   // For a chain of MemberExpr like "a.b.c.d" this list
14935   // will keep FieldDecl's like [d, c, b].
14936   SmallVector<FieldDecl *, 4> ReverseMemberChain;
14937   const MemberExpr *TopME = nullptr;
14938   bool AnyIsPacked = false;
14939   do {
14940     QualType BaseType = ME->getBase()->getType();
14941     if (BaseType->isDependentType())
14942       return;
14943     if (ME->isArrow())
14944       BaseType = BaseType->getPointeeType();
14945     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
14946     if (RD->isInvalidDecl())
14947       return;
14948 
14949     ValueDecl *MD = ME->getMemberDecl();
14950     auto *FD = dyn_cast<FieldDecl>(MD);
14951     // We do not care about non-data members.
14952     if (!FD || FD->isInvalidDecl())
14953       return;
14954 
14955     AnyIsPacked =
14956         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
14957     ReverseMemberChain.push_back(FD);
14958 
14959     TopME = ME;
14960     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
14961   } while (ME);
14962   assert(TopME && "We did not compute a topmost MemberExpr!");
14963 
14964   // Not the scope of this diagnostic.
14965   if (!AnyIsPacked)
14966     return;
14967 
14968   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
14969   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
14970   // TODO: The innermost base of the member expression may be too complicated.
14971   // For now, just disregard these cases. This is left for future
14972   // improvement.
14973   if (!DRE && !isa<CXXThisExpr>(TopBase))
14974       return;
14975 
14976   // Alignment expected by the whole expression.
14977   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
14978 
14979   // No need to do anything else with this case.
14980   if (ExpectedAlignment.isOne())
14981     return;
14982 
14983   // Synthesize offset of the whole access.
14984   CharUnits Offset;
14985   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
14986        I++) {
14987     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
14988   }
14989 
14990   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
14991   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
14992       ReverseMemberChain.back()->getParent()->getTypeForDecl());
14993 
14994   // The base expression of the innermost MemberExpr may give
14995   // stronger guarantees than the class containing the member.
14996   if (DRE && !TopME->isArrow()) {
14997     const ValueDecl *VD = DRE->getDecl();
14998     if (!VD->getType()->isReferenceType())
14999       CompleteObjectAlignment =
15000           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
15001   }
15002 
15003   // Check if the synthesized offset fulfills the alignment.
15004   if (Offset % ExpectedAlignment != 0 ||
15005       // It may fulfill the offset it but the effective alignment may still be
15006       // lower than the expected expression alignment.
15007       CompleteObjectAlignment < ExpectedAlignment) {
15008     // If this happens, we want to determine a sensible culprit of this.
15009     // Intuitively, watching the chain of member expressions from right to
15010     // left, we start with the required alignment (as required by the field
15011     // type) but some packed attribute in that chain has reduced the alignment.
15012     // It may happen that another packed structure increases it again. But if
15013     // we are here such increase has not been enough. So pointing the first
15014     // FieldDecl that either is packed or else its RecordDecl is,
15015     // seems reasonable.
15016     FieldDecl *FD = nullptr;
15017     CharUnits Alignment;
15018     for (FieldDecl *FDI : ReverseMemberChain) {
15019       if (FDI->hasAttr<PackedAttr>() ||
15020           FDI->getParent()->hasAttr<PackedAttr>()) {
15021         FD = FDI;
15022         Alignment = std::min(
15023             Context.getTypeAlignInChars(FD->getType()),
15024             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
15025         break;
15026       }
15027     }
15028     assert(FD && "We did not find a packed FieldDecl!");
15029     Action(E, FD->getParent(), FD, Alignment);
15030   }
15031 }
15032 
15033 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
15034   using namespace std::placeholders;
15035 
15036   RefersToMemberWithReducedAlignment(
15037       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
15038                      _2, _3, _4));
15039 }
15040 
15041 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
15042                                             ExprResult CallResult) {
15043   if (checkArgCount(*this, TheCall, 1))
15044     return ExprError();
15045 
15046   ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
15047   if (MatrixArg.isInvalid())
15048     return MatrixArg;
15049   Expr *Matrix = MatrixArg.get();
15050 
15051   auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
15052   if (!MType) {
15053     Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg) << 0;
15054     return ExprError();
15055   }
15056 
15057   // Create returned matrix type by swapping rows and columns of the argument
15058   // matrix type.
15059   QualType ResultType = Context.getConstantMatrixType(
15060       MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
15061 
15062   // Change the return type to the type of the returned matrix.
15063   TheCall->setType(ResultType);
15064 
15065   // Update call argument to use the possibly converted matrix argument.
15066   TheCall->setArg(0, Matrix);
15067   return CallResult;
15068 }
15069