xref: /freebsd/contrib/llvm-project/clang/lib/Sema/SemaChecking.cpp (revision 7ec2f6bce5d28e6662c29e63f6ab6b7ef57d98b2)
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 <bitset>
92 #include <cassert>
93 #include <cstddef>
94 #include <cstdint>
95 #include <functional>
96 #include <limits>
97 #include <string>
98 #include <tuple>
99 #include <utility>
100 
101 using namespace clang;
102 using namespace sema;
103 
104 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
105                                                     unsigned ByteNo) const {
106   return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
107                                Context.getTargetInfo());
108 }
109 
110 /// Checks that a call expression's argument count is the desired number.
111 /// This is useful when doing custom type-checking.  Returns true on error.
112 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
113   unsigned argCount = call->getNumArgs();
114   if (argCount == desiredArgCount) return false;
115 
116   if (argCount < desiredArgCount)
117     return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args)
118            << 0 /*function call*/ << desiredArgCount << argCount
119            << call->getSourceRange();
120 
121   // Highlight all the excess arguments.
122   SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(),
123                     call->getArg(argCount - 1)->getEndLoc());
124 
125   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
126     << 0 /*function call*/ << desiredArgCount << argCount
127     << call->getArg(1)->getSourceRange();
128 }
129 
130 /// Check that the first argument to __builtin_annotation is an integer
131 /// and the second argument is a non-wide string literal.
132 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
133   if (checkArgCount(S, TheCall, 2))
134     return true;
135 
136   // First argument should be an integer.
137   Expr *ValArg = TheCall->getArg(0);
138   QualType Ty = ValArg->getType();
139   if (!Ty->isIntegerType()) {
140     S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
141         << ValArg->getSourceRange();
142     return true;
143   }
144 
145   // Second argument should be a constant string.
146   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
147   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
148   if (!Literal || !Literal->isAscii()) {
149     S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
150         << StrArg->getSourceRange();
151     return true;
152   }
153 
154   TheCall->setType(Ty);
155   return false;
156 }
157 
158 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
159   // We need at least one argument.
160   if (TheCall->getNumArgs() < 1) {
161     S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
162         << 0 << 1 << TheCall->getNumArgs()
163         << TheCall->getCallee()->getSourceRange();
164     return true;
165   }
166 
167   // All arguments should be wide string literals.
168   for (Expr *Arg : TheCall->arguments()) {
169     auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
170     if (!Literal || !Literal->isWide()) {
171       S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
172           << Arg->getSourceRange();
173       return true;
174     }
175   }
176 
177   return false;
178 }
179 
180 /// Check that the argument to __builtin_addressof is a glvalue, and set the
181 /// result type to the corresponding pointer type.
182 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
183   if (checkArgCount(S, TheCall, 1))
184     return true;
185 
186   ExprResult Arg(TheCall->getArg(0));
187   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
188   if (ResultType.isNull())
189     return true;
190 
191   TheCall->setArg(0, Arg.get());
192   TheCall->setType(ResultType);
193   return false;
194 }
195 
196 /// Check the number of arguments and set the result type to
197 /// the argument type.
198 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
199   if (checkArgCount(S, TheCall, 1))
200     return true;
201 
202   TheCall->setType(TheCall->getArg(0)->getType());
203   return false;
204 }
205 
206 /// Check that the value argument for __builtin_is_aligned(value, alignment) and
207 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
208 /// type (but not a function pointer) and that the alignment is a power-of-two.
209 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
210   if (checkArgCount(S, TheCall, 2))
211     return true;
212 
213   clang::Expr *Source = TheCall->getArg(0);
214   bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
215 
216   auto IsValidIntegerType = [](QualType Ty) {
217     return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
218   };
219   QualType SrcTy = Source->getType();
220   // We should also be able to use it with arrays (but not functions!).
221   if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
222     SrcTy = S.Context.getDecayedType(SrcTy);
223   }
224   if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
225       SrcTy->isFunctionPointerType()) {
226     // FIXME: this is not quite the right error message since we don't allow
227     // floating point types, or member pointers.
228     S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
229         << SrcTy;
230     return true;
231   }
232 
233   clang::Expr *AlignOp = TheCall->getArg(1);
234   if (!IsValidIntegerType(AlignOp->getType())) {
235     S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
236         << AlignOp->getType();
237     return true;
238   }
239   Expr::EvalResult AlignResult;
240   unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
241   // We can't check validity of alignment if it is value dependent.
242   if (!AlignOp->isValueDependent() &&
243       AlignOp->EvaluateAsInt(AlignResult, S.Context,
244                              Expr::SE_AllowSideEffects)) {
245     llvm::APSInt AlignValue = AlignResult.Val.getInt();
246     llvm::APSInt MaxValue(
247         llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
248     if (AlignValue < 1) {
249       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
250       return true;
251     }
252     if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
253       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
254           << MaxValue.toString(10);
255       return true;
256     }
257     if (!AlignValue.isPowerOf2()) {
258       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
259       return true;
260     }
261     if (AlignValue == 1) {
262       S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
263           << IsBooleanAlignBuiltin;
264     }
265   }
266 
267   ExprResult SrcArg = S.PerformCopyInitialization(
268       InitializedEntity::InitializeParameter(S.Context, SrcTy, false),
269       SourceLocation(), Source);
270   if (SrcArg.isInvalid())
271     return true;
272   TheCall->setArg(0, SrcArg.get());
273   ExprResult AlignArg =
274       S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
275                                       S.Context, AlignOp->getType(), false),
276                                   SourceLocation(), AlignOp);
277   if (AlignArg.isInvalid())
278     return true;
279   TheCall->setArg(1, AlignArg.get());
280   // For align_up/align_down, the return type is the same as the (potentially
281   // decayed) argument type including qualifiers. For is_aligned(), the result
282   // is always bool.
283   TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
284   return false;
285 }
286 
287 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall,
288                                 unsigned BuiltinID) {
289   if (checkArgCount(S, TheCall, 3))
290     return true;
291 
292   // First two arguments should be integers.
293   for (unsigned I = 0; I < 2; ++I) {
294     ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I));
295     if (Arg.isInvalid()) return true;
296     TheCall->setArg(I, Arg.get());
297 
298     QualType Ty = Arg.get()->getType();
299     if (!Ty->isIntegerType()) {
300       S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
301           << Ty << Arg.get()->getSourceRange();
302       return true;
303     }
304   }
305 
306   // Third argument should be a pointer to a non-const integer.
307   // IRGen correctly handles volatile, restrict, and address spaces, and
308   // the other qualifiers aren't possible.
309   {
310     ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2));
311     if (Arg.isInvalid()) return true;
312     TheCall->setArg(2, Arg.get());
313 
314     QualType Ty = Arg.get()->getType();
315     const auto *PtrTy = Ty->getAs<PointerType>();
316     if (!PtrTy ||
317         !PtrTy->getPointeeType()->isIntegerType() ||
318         PtrTy->getPointeeType().isConstQualified()) {
319       S.Diag(Arg.get()->getBeginLoc(),
320              diag::err_overflow_builtin_must_be_ptr_int)
321         << Ty << Arg.get()->getSourceRange();
322       return true;
323     }
324   }
325 
326   // Disallow signed ExtIntType args larger than 128 bits to mul function until
327   // we improve backend support.
328   if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
329     for (unsigned I = 0; I < 3; ++I) {
330       const auto Arg = TheCall->getArg(I);
331       // Third argument will be a pointer.
332       auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
333       if (Ty->isExtIntType() && Ty->isSignedIntegerType() &&
334           S.getASTContext().getIntWidth(Ty) > 128)
335         return S.Diag(Arg->getBeginLoc(),
336                       diag::err_overflow_builtin_ext_int_max_size)
337                << 128;
338     }
339   }
340 
341   return false;
342 }
343 
344 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
345   if (checkArgCount(S, BuiltinCall, 2))
346     return true;
347 
348   SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
349   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
350   Expr *Call = BuiltinCall->getArg(0);
351   Expr *Chain = BuiltinCall->getArg(1);
352 
353   if (Call->getStmtClass() != Stmt::CallExprClass) {
354     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
355         << Call->getSourceRange();
356     return true;
357   }
358 
359   auto CE = cast<CallExpr>(Call);
360   if (CE->getCallee()->getType()->isBlockPointerType()) {
361     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
362         << Call->getSourceRange();
363     return true;
364   }
365 
366   const Decl *TargetDecl = CE->getCalleeDecl();
367   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
368     if (FD->getBuiltinID()) {
369       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
370           << Call->getSourceRange();
371       return true;
372     }
373 
374   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
375     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
376         << Call->getSourceRange();
377     return true;
378   }
379 
380   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
381   if (ChainResult.isInvalid())
382     return true;
383   if (!ChainResult.get()->getType()->isPointerType()) {
384     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
385         << Chain->getSourceRange();
386     return true;
387   }
388 
389   QualType ReturnTy = CE->getCallReturnType(S.Context);
390   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
391   QualType BuiltinTy = S.Context.getFunctionType(
392       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
393   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
394 
395   Builtin =
396       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
397 
398   BuiltinCall->setType(CE->getType());
399   BuiltinCall->setValueKind(CE->getValueKind());
400   BuiltinCall->setObjectKind(CE->getObjectKind());
401   BuiltinCall->setCallee(Builtin);
402   BuiltinCall->setArg(1, ChainResult.get());
403 
404   return false;
405 }
406 
407 namespace {
408 
409 class EstimateSizeFormatHandler
410     : public analyze_format_string::FormatStringHandler {
411   size_t Size;
412 
413 public:
414   EstimateSizeFormatHandler(StringRef Format)
415       : Size(std::min(Format.find(0), Format.size()) +
416              1 /* null byte always written by sprintf */) {}
417 
418   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
419                              const char *, unsigned SpecifierLen) override {
420 
421     const size_t FieldWidth = computeFieldWidth(FS);
422     const size_t Precision = computePrecision(FS);
423 
424     // The actual format.
425     switch (FS.getConversionSpecifier().getKind()) {
426     // Just a char.
427     case analyze_format_string::ConversionSpecifier::cArg:
428     case analyze_format_string::ConversionSpecifier::CArg:
429       Size += std::max(FieldWidth, (size_t)1);
430       break;
431     // Just an integer.
432     case analyze_format_string::ConversionSpecifier::dArg:
433     case analyze_format_string::ConversionSpecifier::DArg:
434     case analyze_format_string::ConversionSpecifier::iArg:
435     case analyze_format_string::ConversionSpecifier::oArg:
436     case analyze_format_string::ConversionSpecifier::OArg:
437     case analyze_format_string::ConversionSpecifier::uArg:
438     case analyze_format_string::ConversionSpecifier::UArg:
439     case analyze_format_string::ConversionSpecifier::xArg:
440     case analyze_format_string::ConversionSpecifier::XArg:
441       Size += std::max(FieldWidth, Precision);
442       break;
443 
444     // %g style conversion switches between %f or %e style dynamically.
445     // %f always takes less space, so default to it.
446     case analyze_format_string::ConversionSpecifier::gArg:
447     case analyze_format_string::ConversionSpecifier::GArg:
448 
449     // Floating point number in the form '[+]ddd.ddd'.
450     case analyze_format_string::ConversionSpecifier::fArg:
451     case analyze_format_string::ConversionSpecifier::FArg:
452       Size += std::max(FieldWidth, 1 /* integer part */ +
453                                        (Precision ? 1 + Precision
454                                                   : 0) /* period + decimal */);
455       break;
456 
457     // Floating point number in the form '[-]d.ddde[+-]dd'.
458     case analyze_format_string::ConversionSpecifier::eArg:
459     case analyze_format_string::ConversionSpecifier::EArg:
460       Size +=
461           std::max(FieldWidth,
462                    1 /* integer part */ +
463                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
464                        1 /* e or E letter */ + 2 /* exponent */);
465       break;
466 
467     // Floating point number in the form '[-]0xh.hhhhp±dd'.
468     case analyze_format_string::ConversionSpecifier::aArg:
469     case analyze_format_string::ConversionSpecifier::AArg:
470       Size +=
471           std::max(FieldWidth,
472                    2 /* 0x */ + 1 /* integer part */ +
473                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
474                        1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
475       break;
476 
477     // Just a string.
478     case analyze_format_string::ConversionSpecifier::sArg:
479     case analyze_format_string::ConversionSpecifier::SArg:
480       Size += FieldWidth;
481       break;
482 
483     // Just a pointer in the form '0xddd'.
484     case analyze_format_string::ConversionSpecifier::pArg:
485       Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
486       break;
487 
488     // A plain percent.
489     case analyze_format_string::ConversionSpecifier::PercentArg:
490       Size += 1;
491       break;
492 
493     default:
494       break;
495     }
496 
497     Size += FS.hasPlusPrefix() || FS.hasSpacePrefix();
498 
499     if (FS.hasAlternativeForm()) {
500       switch (FS.getConversionSpecifier().getKind()) {
501       default:
502         break;
503       // Force a leading '0'.
504       case analyze_format_string::ConversionSpecifier::oArg:
505         Size += 1;
506         break;
507       // Force a leading '0x'.
508       case analyze_format_string::ConversionSpecifier::xArg:
509       case analyze_format_string::ConversionSpecifier::XArg:
510         Size += 2;
511         break;
512       // Force a period '.' before decimal, even if precision is 0.
513       case analyze_format_string::ConversionSpecifier::aArg:
514       case analyze_format_string::ConversionSpecifier::AArg:
515       case analyze_format_string::ConversionSpecifier::eArg:
516       case analyze_format_string::ConversionSpecifier::EArg:
517       case analyze_format_string::ConversionSpecifier::fArg:
518       case analyze_format_string::ConversionSpecifier::FArg:
519       case analyze_format_string::ConversionSpecifier::gArg:
520       case analyze_format_string::ConversionSpecifier::GArg:
521         Size += (Precision ? 0 : 1);
522         break;
523       }
524     }
525     assert(SpecifierLen <= Size && "no underflow");
526     Size -= SpecifierLen;
527     return true;
528   }
529 
530   size_t getSizeLowerBound() const { return Size; }
531 
532 private:
533   static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
534     const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
535     size_t FieldWidth = 0;
536     if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant)
537       FieldWidth = FW.getConstantAmount();
538     return FieldWidth;
539   }
540 
541   static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
542     const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
543     size_t Precision = 0;
544 
545     // See man 3 printf for default precision value based on the specifier.
546     switch (FW.getHowSpecified()) {
547     case analyze_format_string::OptionalAmount::NotSpecified:
548       switch (FS.getConversionSpecifier().getKind()) {
549       default:
550         break;
551       case analyze_format_string::ConversionSpecifier::dArg: // %d
552       case analyze_format_string::ConversionSpecifier::DArg: // %D
553       case analyze_format_string::ConversionSpecifier::iArg: // %i
554         Precision = 1;
555         break;
556       case analyze_format_string::ConversionSpecifier::oArg: // %d
557       case analyze_format_string::ConversionSpecifier::OArg: // %D
558       case analyze_format_string::ConversionSpecifier::uArg: // %d
559       case analyze_format_string::ConversionSpecifier::UArg: // %D
560       case analyze_format_string::ConversionSpecifier::xArg: // %d
561       case analyze_format_string::ConversionSpecifier::XArg: // %D
562         Precision = 1;
563         break;
564       case analyze_format_string::ConversionSpecifier::fArg: // %f
565       case analyze_format_string::ConversionSpecifier::FArg: // %F
566       case analyze_format_string::ConversionSpecifier::eArg: // %e
567       case analyze_format_string::ConversionSpecifier::EArg: // %E
568       case analyze_format_string::ConversionSpecifier::gArg: // %g
569       case analyze_format_string::ConversionSpecifier::GArg: // %G
570         Precision = 6;
571         break;
572       case analyze_format_string::ConversionSpecifier::pArg: // %d
573         Precision = 1;
574         break;
575       }
576       break;
577     case analyze_format_string::OptionalAmount::Constant:
578       Precision = FW.getConstantAmount();
579       break;
580     default:
581       break;
582     }
583     return Precision;
584   }
585 };
586 
587 } // namespace
588 
589 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a
590 /// __builtin_*_chk function, then use the object size argument specified in the
591 /// source. Otherwise, infer the object size using __builtin_object_size.
592 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
593                                                CallExpr *TheCall) {
594   // FIXME: There are some more useful checks we could be doing here:
595   //  - Evaluate strlen of strcpy arguments, use as object size.
596 
597   if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
598       isConstantEvaluated())
599     return;
600 
601   unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
602   if (!BuiltinID)
603     return;
604 
605   const TargetInfo &TI = getASTContext().getTargetInfo();
606   unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
607 
608   unsigned DiagID = 0;
609   bool IsChkVariant = false;
610   Optional<llvm::APSInt> UsedSize;
611   unsigned SizeIndex, ObjectIndex;
612   switch (BuiltinID) {
613   default:
614     return;
615   case Builtin::BIsprintf:
616   case Builtin::BI__builtin___sprintf_chk: {
617     size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
618     auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
619 
620     if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) {
621 
622       if (!Format->isAscii() && !Format->isUTF8())
623         return;
624 
625       StringRef FormatStrRef = Format->getString();
626       EstimateSizeFormatHandler H(FormatStrRef);
627       const char *FormatBytes = FormatStrRef.data();
628       const ConstantArrayType *T =
629           Context.getAsConstantArrayType(Format->getType());
630       assert(T && "String literal not of constant array type!");
631       size_t TypeSize = T->getSize().getZExtValue();
632 
633       // In case there's a null byte somewhere.
634       size_t StrLen =
635           std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
636       if (!analyze_format_string::ParsePrintfString(
637               H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
638               Context.getTargetInfo(), false)) {
639         DiagID = diag::warn_fortify_source_format_overflow;
640         UsedSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
641                        .extOrTrunc(SizeTypeWidth);
642         if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
643           IsChkVariant = true;
644           ObjectIndex = 2;
645         } else {
646           IsChkVariant = false;
647           ObjectIndex = 0;
648         }
649         break;
650       }
651     }
652     return;
653   }
654   case Builtin::BI__builtin___memcpy_chk:
655   case Builtin::BI__builtin___memmove_chk:
656   case Builtin::BI__builtin___memset_chk:
657   case Builtin::BI__builtin___strlcat_chk:
658   case Builtin::BI__builtin___strlcpy_chk:
659   case Builtin::BI__builtin___strncat_chk:
660   case Builtin::BI__builtin___strncpy_chk:
661   case Builtin::BI__builtin___stpncpy_chk:
662   case Builtin::BI__builtin___memccpy_chk:
663   case Builtin::BI__builtin___mempcpy_chk: {
664     DiagID = diag::warn_builtin_chk_overflow;
665     IsChkVariant = true;
666     SizeIndex = TheCall->getNumArgs() - 2;
667     ObjectIndex = TheCall->getNumArgs() - 1;
668     break;
669   }
670 
671   case Builtin::BI__builtin___snprintf_chk:
672   case Builtin::BI__builtin___vsnprintf_chk: {
673     DiagID = diag::warn_builtin_chk_overflow;
674     IsChkVariant = true;
675     SizeIndex = 1;
676     ObjectIndex = 3;
677     break;
678   }
679 
680   case Builtin::BIstrncat:
681   case Builtin::BI__builtin_strncat:
682   case Builtin::BIstrncpy:
683   case Builtin::BI__builtin_strncpy:
684   case Builtin::BIstpncpy:
685   case Builtin::BI__builtin_stpncpy: {
686     // Whether these functions overflow depends on the runtime strlen of the
687     // string, not just the buffer size, so emitting the "always overflow"
688     // diagnostic isn't quite right. We should still diagnose passing a buffer
689     // size larger than the destination buffer though; this is a runtime abort
690     // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
691     DiagID = diag::warn_fortify_source_size_mismatch;
692     SizeIndex = TheCall->getNumArgs() - 1;
693     ObjectIndex = 0;
694     break;
695   }
696 
697   case Builtin::BImemcpy:
698   case Builtin::BI__builtin_memcpy:
699   case Builtin::BImemmove:
700   case Builtin::BI__builtin_memmove:
701   case Builtin::BImemset:
702   case Builtin::BI__builtin_memset:
703   case Builtin::BImempcpy:
704   case Builtin::BI__builtin_mempcpy: {
705     DiagID = diag::warn_fortify_source_overflow;
706     SizeIndex = TheCall->getNumArgs() - 1;
707     ObjectIndex = 0;
708     break;
709   }
710   case Builtin::BIsnprintf:
711   case Builtin::BI__builtin_snprintf:
712   case Builtin::BIvsnprintf:
713   case Builtin::BI__builtin_vsnprintf: {
714     DiagID = diag::warn_fortify_source_size_mismatch;
715     SizeIndex = 1;
716     ObjectIndex = 0;
717     break;
718   }
719   }
720 
721   llvm::APSInt ObjectSize;
722   // For __builtin___*_chk, the object size is explicitly provided by the caller
723   // (usually using __builtin_object_size). Use that value to check this call.
724   if (IsChkVariant) {
725     Expr::EvalResult Result;
726     Expr *SizeArg = TheCall->getArg(ObjectIndex);
727     if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
728       return;
729     ObjectSize = Result.Val.getInt();
730 
731   // Otherwise, try to evaluate an imaginary call to __builtin_object_size.
732   } else {
733     // If the parameter has a pass_object_size attribute, then we should use its
734     // (potentially) more strict checking mode. Otherwise, conservatively assume
735     // type 0.
736     int BOSType = 0;
737     if (const auto *POS =
738             FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>())
739       BOSType = POS->getType();
740 
741     Expr *ObjArg = TheCall->getArg(ObjectIndex);
742     uint64_t Result;
743     if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
744       return;
745     // Get the object size in the target's size_t width.
746     ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
747   }
748 
749   // Evaluate the number of bytes of the object that this call will use.
750   if (!UsedSize) {
751     Expr::EvalResult Result;
752     Expr *UsedSizeArg = TheCall->getArg(SizeIndex);
753     if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext()))
754       return;
755     UsedSize = Result.Val.getInt().extOrTrunc(SizeTypeWidth);
756   }
757 
758   if (UsedSize.getValue().ule(ObjectSize))
759     return;
760 
761   StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
762   // Skim off the details of whichever builtin was called to produce a better
763   // diagnostic, as it's unlikley that the user wrote the __builtin explicitly.
764   if (IsChkVariant) {
765     FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
766     FunctionName = FunctionName.drop_back(std::strlen("_chk"));
767   } else if (FunctionName.startswith("__builtin_")) {
768     FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
769   }
770 
771   DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
772                       PDiag(DiagID)
773                           << FunctionName << ObjectSize.toString(/*Radix=*/10)
774                           << UsedSize.getValue().toString(/*Radix=*/10));
775 }
776 
777 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
778                                      Scope::ScopeFlags NeededScopeFlags,
779                                      unsigned DiagID) {
780   // Scopes aren't available during instantiation. Fortunately, builtin
781   // functions cannot be template args so they cannot be formed through template
782   // instantiation. Therefore checking once during the parse is sufficient.
783   if (SemaRef.inTemplateInstantiation())
784     return false;
785 
786   Scope *S = SemaRef.getCurScope();
787   while (S && !S->isSEHExceptScope())
788     S = S->getParent();
789   if (!S || !(S->getFlags() & NeededScopeFlags)) {
790     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
791     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
792         << DRE->getDecl()->getIdentifier();
793     return true;
794   }
795 
796   return false;
797 }
798 
799 static inline bool isBlockPointer(Expr *Arg) {
800   return Arg->getType()->isBlockPointerType();
801 }
802 
803 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
804 /// void*, which is a requirement of device side enqueue.
805 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
806   const BlockPointerType *BPT =
807       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
808   ArrayRef<QualType> Params =
809       BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
810   unsigned ArgCounter = 0;
811   bool IllegalParams = false;
812   // Iterate through the block parameters until either one is found that is not
813   // a local void*, or the block is valid.
814   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
815        I != E; ++I, ++ArgCounter) {
816     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
817         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
818             LangAS::opencl_local) {
819       // Get the location of the error. If a block literal has been passed
820       // (BlockExpr) then we can point straight to the offending argument,
821       // else we just point to the variable reference.
822       SourceLocation ErrorLoc;
823       if (isa<BlockExpr>(BlockArg)) {
824         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
825         ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
826       } else if (isa<DeclRefExpr>(BlockArg)) {
827         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
828       }
829       S.Diag(ErrorLoc,
830              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
831       IllegalParams = true;
832     }
833   }
834 
835   return IllegalParams;
836 }
837 
838 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
839   if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
840     S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
841         << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
842     return true;
843   }
844   return false;
845 }
846 
847 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
848   if (checkArgCount(S, TheCall, 2))
849     return true;
850 
851   if (checkOpenCLSubgroupExt(S, TheCall))
852     return true;
853 
854   // First argument is an ndrange_t type.
855   Expr *NDRangeArg = TheCall->getArg(0);
856   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
857     S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
858         << TheCall->getDirectCallee() << "'ndrange_t'";
859     return true;
860   }
861 
862   Expr *BlockArg = TheCall->getArg(1);
863   if (!isBlockPointer(BlockArg)) {
864     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
865         << TheCall->getDirectCallee() << "block";
866     return true;
867   }
868   return checkOpenCLBlockArgs(S, BlockArg);
869 }
870 
871 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
872 /// get_kernel_work_group_size
873 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
874 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
875   if (checkArgCount(S, TheCall, 1))
876     return true;
877 
878   Expr *BlockArg = TheCall->getArg(0);
879   if (!isBlockPointer(BlockArg)) {
880     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
881         << TheCall->getDirectCallee() << "block";
882     return true;
883   }
884   return checkOpenCLBlockArgs(S, BlockArg);
885 }
886 
887 /// Diagnose integer type and any valid implicit conversion to it.
888 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
889                                       const QualType &IntType);
890 
891 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
892                                             unsigned Start, unsigned End) {
893   bool IllegalParams = false;
894   for (unsigned I = Start; I <= End; ++I)
895     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
896                                               S.Context.getSizeType());
897   return IllegalParams;
898 }
899 
900 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
901 /// 'local void*' parameter of passed block.
902 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
903                                            Expr *BlockArg,
904                                            unsigned NumNonVarArgs) {
905   const BlockPointerType *BPT =
906       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
907   unsigned NumBlockParams =
908       BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
909   unsigned TotalNumArgs = TheCall->getNumArgs();
910 
911   // For each argument passed to the block, a corresponding uint needs to
912   // be passed to describe the size of the local memory.
913   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
914     S.Diag(TheCall->getBeginLoc(),
915            diag::err_opencl_enqueue_kernel_local_size_args);
916     return true;
917   }
918 
919   // Check that the sizes of the local memory are specified by integers.
920   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
921                                          TotalNumArgs - 1);
922 }
923 
924 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
925 /// overload formats specified in Table 6.13.17.1.
926 /// int enqueue_kernel(queue_t queue,
927 ///                    kernel_enqueue_flags_t flags,
928 ///                    const ndrange_t ndrange,
929 ///                    void (^block)(void))
930 /// int enqueue_kernel(queue_t queue,
931 ///                    kernel_enqueue_flags_t flags,
932 ///                    const ndrange_t ndrange,
933 ///                    uint num_events_in_wait_list,
934 ///                    clk_event_t *event_wait_list,
935 ///                    clk_event_t *event_ret,
936 ///                    void (^block)(void))
937 /// int enqueue_kernel(queue_t queue,
938 ///                    kernel_enqueue_flags_t flags,
939 ///                    const ndrange_t ndrange,
940 ///                    void (^block)(local void*, ...),
941 ///                    uint size0, ...)
942 /// int enqueue_kernel(queue_t queue,
943 ///                    kernel_enqueue_flags_t flags,
944 ///                    const ndrange_t ndrange,
945 ///                    uint num_events_in_wait_list,
946 ///                    clk_event_t *event_wait_list,
947 ///                    clk_event_t *event_ret,
948 ///                    void (^block)(local void*, ...),
949 ///                    uint size0, ...)
950 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
951   unsigned NumArgs = TheCall->getNumArgs();
952 
953   if (NumArgs < 4) {
954     S.Diag(TheCall->getBeginLoc(),
955            diag::err_typecheck_call_too_few_args_at_least)
956         << 0 << 4 << NumArgs;
957     return true;
958   }
959 
960   Expr *Arg0 = TheCall->getArg(0);
961   Expr *Arg1 = TheCall->getArg(1);
962   Expr *Arg2 = TheCall->getArg(2);
963   Expr *Arg3 = TheCall->getArg(3);
964 
965   // First argument always needs to be a queue_t type.
966   if (!Arg0->getType()->isQueueT()) {
967     S.Diag(TheCall->getArg(0)->getBeginLoc(),
968            diag::err_opencl_builtin_expected_type)
969         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
970     return true;
971   }
972 
973   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
974   if (!Arg1->getType()->isIntegerType()) {
975     S.Diag(TheCall->getArg(1)->getBeginLoc(),
976            diag::err_opencl_builtin_expected_type)
977         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
978     return true;
979   }
980 
981   // Third argument is always an ndrange_t type.
982   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
983     S.Diag(TheCall->getArg(2)->getBeginLoc(),
984            diag::err_opencl_builtin_expected_type)
985         << TheCall->getDirectCallee() << "'ndrange_t'";
986     return true;
987   }
988 
989   // With four arguments, there is only one form that the function could be
990   // called in: no events and no variable arguments.
991   if (NumArgs == 4) {
992     // check that the last argument is the right block type.
993     if (!isBlockPointer(Arg3)) {
994       S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
995           << TheCall->getDirectCallee() << "block";
996       return true;
997     }
998     // we have a block type, check the prototype
999     const BlockPointerType *BPT =
1000         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
1001     if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
1002       S.Diag(Arg3->getBeginLoc(),
1003              diag::err_opencl_enqueue_kernel_blocks_no_args);
1004       return true;
1005     }
1006     return false;
1007   }
1008   // we can have block + varargs.
1009   if (isBlockPointer(Arg3))
1010     return (checkOpenCLBlockArgs(S, Arg3) ||
1011             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
1012   // last two cases with either exactly 7 args or 7 args and varargs.
1013   if (NumArgs >= 7) {
1014     // check common block argument.
1015     Expr *Arg6 = TheCall->getArg(6);
1016     if (!isBlockPointer(Arg6)) {
1017       S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1018           << TheCall->getDirectCallee() << "block";
1019       return true;
1020     }
1021     if (checkOpenCLBlockArgs(S, Arg6))
1022       return true;
1023 
1024     // Forth argument has to be any integer type.
1025     if (!Arg3->getType()->isIntegerType()) {
1026       S.Diag(TheCall->getArg(3)->getBeginLoc(),
1027              diag::err_opencl_builtin_expected_type)
1028           << TheCall->getDirectCallee() << "integer";
1029       return true;
1030     }
1031     // check remaining common arguments.
1032     Expr *Arg4 = TheCall->getArg(4);
1033     Expr *Arg5 = TheCall->getArg(5);
1034 
1035     // Fifth argument is always passed as a pointer to clk_event_t.
1036     if (!Arg4->isNullPointerConstant(S.Context,
1037                                      Expr::NPC_ValueDependentIsNotNull) &&
1038         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
1039       S.Diag(TheCall->getArg(4)->getBeginLoc(),
1040              diag::err_opencl_builtin_expected_type)
1041           << TheCall->getDirectCallee()
1042           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1043       return true;
1044     }
1045 
1046     // Sixth argument is always passed as a pointer to clk_event_t.
1047     if (!Arg5->isNullPointerConstant(S.Context,
1048                                      Expr::NPC_ValueDependentIsNotNull) &&
1049         !(Arg5->getType()->isPointerType() &&
1050           Arg5->getType()->getPointeeType()->isClkEventT())) {
1051       S.Diag(TheCall->getArg(5)->getBeginLoc(),
1052              diag::err_opencl_builtin_expected_type)
1053           << TheCall->getDirectCallee()
1054           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1055       return true;
1056     }
1057 
1058     if (NumArgs == 7)
1059       return false;
1060 
1061     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
1062   }
1063 
1064   // None of the specific case has been detected, give generic error
1065   S.Diag(TheCall->getBeginLoc(),
1066          diag::err_opencl_enqueue_kernel_incorrect_args);
1067   return true;
1068 }
1069 
1070 /// Returns OpenCL access qual.
1071 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
1072     return D->getAttr<OpenCLAccessAttr>();
1073 }
1074 
1075 /// Returns true if pipe element type is different from the pointer.
1076 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
1077   const Expr *Arg0 = Call->getArg(0);
1078   // First argument type should always be pipe.
1079   if (!Arg0->getType()->isPipeType()) {
1080     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1081         << Call->getDirectCallee() << Arg0->getSourceRange();
1082     return true;
1083   }
1084   OpenCLAccessAttr *AccessQual =
1085       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
1086   // Validates the access qualifier is compatible with the call.
1087   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
1088   // read_only and write_only, and assumed to be read_only if no qualifier is
1089   // specified.
1090   switch (Call->getDirectCallee()->getBuiltinID()) {
1091   case Builtin::BIread_pipe:
1092   case Builtin::BIreserve_read_pipe:
1093   case Builtin::BIcommit_read_pipe:
1094   case Builtin::BIwork_group_reserve_read_pipe:
1095   case Builtin::BIsub_group_reserve_read_pipe:
1096   case Builtin::BIwork_group_commit_read_pipe:
1097   case Builtin::BIsub_group_commit_read_pipe:
1098     if (!(!AccessQual || AccessQual->isReadOnly())) {
1099       S.Diag(Arg0->getBeginLoc(),
1100              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1101           << "read_only" << Arg0->getSourceRange();
1102       return true;
1103     }
1104     break;
1105   case Builtin::BIwrite_pipe:
1106   case Builtin::BIreserve_write_pipe:
1107   case Builtin::BIcommit_write_pipe:
1108   case Builtin::BIwork_group_reserve_write_pipe:
1109   case Builtin::BIsub_group_reserve_write_pipe:
1110   case Builtin::BIwork_group_commit_write_pipe:
1111   case Builtin::BIsub_group_commit_write_pipe:
1112     if (!(AccessQual && AccessQual->isWriteOnly())) {
1113       S.Diag(Arg0->getBeginLoc(),
1114              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1115           << "write_only" << Arg0->getSourceRange();
1116       return true;
1117     }
1118     break;
1119   default:
1120     break;
1121   }
1122   return false;
1123 }
1124 
1125 /// Returns true if pipe element type is different from the pointer.
1126 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
1127   const Expr *Arg0 = Call->getArg(0);
1128   const Expr *ArgIdx = Call->getArg(Idx);
1129   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
1130   const QualType EltTy = PipeTy->getElementType();
1131   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
1132   // The Idx argument should be a pointer and the type of the pointer and
1133   // the type of pipe element should also be the same.
1134   if (!ArgTy ||
1135       !S.Context.hasSameType(
1136           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
1137     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1138         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
1139         << ArgIdx->getType() << ArgIdx->getSourceRange();
1140     return true;
1141   }
1142   return false;
1143 }
1144 
1145 // Performs semantic analysis for the read/write_pipe call.
1146 // \param S Reference to the semantic analyzer.
1147 // \param Call A pointer to the builtin call.
1148 // \return True if a semantic error has been found, false otherwise.
1149 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
1150   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
1151   // functions have two forms.
1152   switch (Call->getNumArgs()) {
1153   case 2:
1154     if (checkOpenCLPipeArg(S, Call))
1155       return true;
1156     // The call with 2 arguments should be
1157     // read/write_pipe(pipe T, T*).
1158     // Check packet type T.
1159     if (checkOpenCLPipePacketType(S, Call, 1))
1160       return true;
1161     break;
1162 
1163   case 4: {
1164     if (checkOpenCLPipeArg(S, Call))
1165       return true;
1166     // The call with 4 arguments should be
1167     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
1168     // Check reserve_id_t.
1169     if (!Call->getArg(1)->getType()->isReserveIDT()) {
1170       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1171           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1172           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1173       return true;
1174     }
1175 
1176     // Check the index.
1177     const Expr *Arg2 = Call->getArg(2);
1178     if (!Arg2->getType()->isIntegerType() &&
1179         !Arg2->getType()->isUnsignedIntegerType()) {
1180       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1181           << Call->getDirectCallee() << S.Context.UnsignedIntTy
1182           << Arg2->getType() << Arg2->getSourceRange();
1183       return true;
1184     }
1185 
1186     // Check packet type T.
1187     if (checkOpenCLPipePacketType(S, Call, 3))
1188       return true;
1189   } break;
1190   default:
1191     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
1192         << Call->getDirectCallee() << Call->getSourceRange();
1193     return true;
1194   }
1195 
1196   return false;
1197 }
1198 
1199 // Performs a semantic analysis on the {work_group_/sub_group_
1200 //        /_}reserve_{read/write}_pipe
1201 // \param S Reference to the semantic analyzer.
1202 // \param Call The call to the builtin function to be analyzed.
1203 // \return True if a semantic error was found, false otherwise.
1204 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
1205   if (checkArgCount(S, Call, 2))
1206     return true;
1207 
1208   if (checkOpenCLPipeArg(S, Call))
1209     return true;
1210 
1211   // Check the reserve size.
1212   if (!Call->getArg(1)->getType()->isIntegerType() &&
1213       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
1214     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1215         << Call->getDirectCallee() << S.Context.UnsignedIntTy
1216         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1217     return true;
1218   }
1219 
1220   // Since return type of reserve_read/write_pipe built-in function is
1221   // reserve_id_t, which is not defined in the builtin def file , we used int
1222   // as return type and need to override the return type of these functions.
1223   Call->setType(S.Context.OCLReserveIDTy);
1224 
1225   return false;
1226 }
1227 
1228 // Performs a semantic analysis on {work_group_/sub_group_
1229 //        /_}commit_{read/write}_pipe
1230 // \param S Reference to the semantic analyzer.
1231 // \param Call The call to the builtin function to be analyzed.
1232 // \return True if a semantic error was found, false otherwise.
1233 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
1234   if (checkArgCount(S, Call, 2))
1235     return true;
1236 
1237   if (checkOpenCLPipeArg(S, Call))
1238     return true;
1239 
1240   // Check reserve_id_t.
1241   if (!Call->getArg(1)->getType()->isReserveIDT()) {
1242     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1243         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1244         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1245     return true;
1246   }
1247 
1248   return false;
1249 }
1250 
1251 // Performs a semantic analysis on the call to built-in Pipe
1252 //        Query Functions.
1253 // \param S Reference to the semantic analyzer.
1254 // \param Call The call to the builtin function to be analyzed.
1255 // \return True if a semantic error was found, false otherwise.
1256 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
1257   if (checkArgCount(S, Call, 1))
1258     return true;
1259 
1260   if (!Call->getArg(0)->getType()->isPipeType()) {
1261     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1262         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
1263     return true;
1264   }
1265 
1266   return false;
1267 }
1268 
1269 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
1270 // Performs semantic analysis for the to_global/local/private call.
1271 // \param S Reference to the semantic analyzer.
1272 // \param BuiltinID ID of the builtin function.
1273 // \param Call A pointer to the builtin call.
1274 // \return True if a semantic error has been found, false otherwise.
1275 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
1276                                     CallExpr *Call) {
1277   if (Call->getNumArgs() != 1) {
1278     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num)
1279         << Call->getDirectCallee() << Call->getSourceRange();
1280     return true;
1281   }
1282 
1283   auto RT = Call->getArg(0)->getType();
1284   if (!RT->isPointerType() || RT->getPointeeType()
1285       .getAddressSpace() == LangAS::opencl_constant) {
1286     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
1287         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
1288     return true;
1289   }
1290 
1291   if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
1292     S.Diag(Call->getArg(0)->getBeginLoc(),
1293            diag::warn_opencl_generic_address_space_arg)
1294         << Call->getDirectCallee()->getNameInfo().getAsString()
1295         << Call->getArg(0)->getSourceRange();
1296   }
1297 
1298   RT = RT->getPointeeType();
1299   auto Qual = RT.getQualifiers();
1300   switch (BuiltinID) {
1301   case Builtin::BIto_global:
1302     Qual.setAddressSpace(LangAS::opencl_global);
1303     break;
1304   case Builtin::BIto_local:
1305     Qual.setAddressSpace(LangAS::opencl_local);
1306     break;
1307   case Builtin::BIto_private:
1308     Qual.setAddressSpace(LangAS::opencl_private);
1309     break;
1310   default:
1311     llvm_unreachable("Invalid builtin function");
1312   }
1313   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
1314       RT.getUnqualifiedType(), Qual)));
1315 
1316   return false;
1317 }
1318 
1319 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
1320   if (checkArgCount(S, TheCall, 1))
1321     return ExprError();
1322 
1323   // Compute __builtin_launder's parameter type from the argument.
1324   // The parameter type is:
1325   //  * The type of the argument if it's not an array or function type,
1326   //  Otherwise,
1327   //  * The decayed argument type.
1328   QualType ParamTy = [&]() {
1329     QualType ArgTy = TheCall->getArg(0)->getType();
1330     if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1331       return S.Context.getPointerType(Ty->getElementType());
1332     if (ArgTy->isFunctionType()) {
1333       return S.Context.getPointerType(ArgTy);
1334     }
1335     return ArgTy;
1336   }();
1337 
1338   TheCall->setType(ParamTy);
1339 
1340   auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1341     if (!ParamTy->isPointerType())
1342       return 0;
1343     if (ParamTy->isFunctionPointerType())
1344       return 1;
1345     if (ParamTy->isVoidPointerType())
1346       return 2;
1347     return llvm::Optional<unsigned>{};
1348   }();
1349   if (DiagSelect.hasValue()) {
1350     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1351         << DiagSelect.getValue() << TheCall->getSourceRange();
1352     return ExprError();
1353   }
1354 
1355   // We either have an incomplete class type, or we have a class template
1356   // whose instantiation has not been forced. Example:
1357   //
1358   //   template <class T> struct Foo { T value; };
1359   //   Foo<int> *p = nullptr;
1360   //   auto *d = __builtin_launder(p);
1361   if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1362                             diag::err_incomplete_type))
1363     return ExprError();
1364 
1365   assert(ParamTy->getPointeeType()->isObjectType() &&
1366          "Unhandled non-object pointer case");
1367 
1368   InitializedEntity Entity =
1369       InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1370   ExprResult Arg =
1371       S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1372   if (Arg.isInvalid())
1373     return ExprError();
1374   TheCall->setArg(0, Arg.get());
1375 
1376   return TheCall;
1377 }
1378 
1379 // Emit an error and return true if the current architecture is not in the list
1380 // of supported architectures.
1381 static bool
1382 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1383                           ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1384   llvm::Triple::ArchType CurArch =
1385       S.getASTContext().getTargetInfo().getTriple().getArch();
1386   if (llvm::is_contained(SupportedArchs, CurArch))
1387     return false;
1388   S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1389       << TheCall->getSourceRange();
1390   return true;
1391 }
1392 
1393 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
1394                                  SourceLocation CallSiteLoc);
1395 
1396 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
1397                                       CallExpr *TheCall) {
1398   switch (TI.getTriple().getArch()) {
1399   default:
1400     // Some builtins don't require additional checking, so just consider these
1401     // acceptable.
1402     return false;
1403   case llvm::Triple::arm:
1404   case llvm::Triple::armeb:
1405   case llvm::Triple::thumb:
1406   case llvm::Triple::thumbeb:
1407     return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
1408   case llvm::Triple::aarch64:
1409   case llvm::Triple::aarch64_32:
1410   case llvm::Triple::aarch64_be:
1411     return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
1412   case llvm::Triple::bpfeb:
1413   case llvm::Triple::bpfel:
1414     return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
1415   case llvm::Triple::hexagon:
1416     return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
1417   case llvm::Triple::mips:
1418   case llvm::Triple::mipsel:
1419   case llvm::Triple::mips64:
1420   case llvm::Triple::mips64el:
1421     return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
1422   case llvm::Triple::systemz:
1423     return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
1424   case llvm::Triple::x86:
1425   case llvm::Triple::x86_64:
1426     return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall);
1427   case llvm::Triple::ppc:
1428   case llvm::Triple::ppc64:
1429   case llvm::Triple::ppc64le:
1430     return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
1431   case llvm::Triple::amdgcn:
1432     return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
1433   }
1434 }
1435 
1436 ExprResult
1437 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1438                                CallExpr *TheCall) {
1439   ExprResult TheCallResult(TheCall);
1440 
1441   // Find out if any arguments are required to be integer constant expressions.
1442   unsigned ICEArguments = 0;
1443   ASTContext::GetBuiltinTypeError Error;
1444   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1445   if (Error != ASTContext::GE_None)
1446     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
1447 
1448   // If any arguments are required to be ICE's, check and diagnose.
1449   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1450     // Skip arguments not required to be ICE's.
1451     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1452 
1453     llvm::APSInt Result;
1454     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1455       return true;
1456     ICEArguments &= ~(1 << ArgNo);
1457   }
1458 
1459   switch (BuiltinID) {
1460   case Builtin::BI__builtin___CFStringMakeConstantString:
1461     assert(TheCall->getNumArgs() == 1 &&
1462            "Wrong # arguments to builtin CFStringMakeConstantString");
1463     if (CheckObjCString(TheCall->getArg(0)))
1464       return ExprError();
1465     break;
1466   case Builtin::BI__builtin_ms_va_start:
1467   case Builtin::BI__builtin_stdarg_start:
1468   case Builtin::BI__builtin_va_start:
1469     if (SemaBuiltinVAStart(BuiltinID, TheCall))
1470       return ExprError();
1471     break;
1472   case Builtin::BI__va_start: {
1473     switch (Context.getTargetInfo().getTriple().getArch()) {
1474     case llvm::Triple::aarch64:
1475     case llvm::Triple::arm:
1476     case llvm::Triple::thumb:
1477       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1478         return ExprError();
1479       break;
1480     default:
1481       if (SemaBuiltinVAStart(BuiltinID, TheCall))
1482         return ExprError();
1483       break;
1484     }
1485     break;
1486   }
1487 
1488   // The acquire, release, and no fence variants are ARM and AArch64 only.
1489   case Builtin::BI_interlockedbittestandset_acq:
1490   case Builtin::BI_interlockedbittestandset_rel:
1491   case Builtin::BI_interlockedbittestandset_nf:
1492   case Builtin::BI_interlockedbittestandreset_acq:
1493   case Builtin::BI_interlockedbittestandreset_rel:
1494   case Builtin::BI_interlockedbittestandreset_nf:
1495     if (CheckBuiltinTargetSupport(
1496             *this, BuiltinID, TheCall,
1497             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1498       return ExprError();
1499     break;
1500 
1501   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1502   case Builtin::BI_bittest64:
1503   case Builtin::BI_bittestandcomplement64:
1504   case Builtin::BI_bittestandreset64:
1505   case Builtin::BI_bittestandset64:
1506   case Builtin::BI_interlockedbittestandreset64:
1507   case Builtin::BI_interlockedbittestandset64:
1508     if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1509                                   {llvm::Triple::x86_64, llvm::Triple::arm,
1510                                    llvm::Triple::thumb, llvm::Triple::aarch64}))
1511       return ExprError();
1512     break;
1513 
1514   case Builtin::BI__builtin_isgreater:
1515   case Builtin::BI__builtin_isgreaterequal:
1516   case Builtin::BI__builtin_isless:
1517   case Builtin::BI__builtin_islessequal:
1518   case Builtin::BI__builtin_islessgreater:
1519   case Builtin::BI__builtin_isunordered:
1520     if (SemaBuiltinUnorderedCompare(TheCall))
1521       return ExprError();
1522     break;
1523   case Builtin::BI__builtin_fpclassify:
1524     if (SemaBuiltinFPClassification(TheCall, 6))
1525       return ExprError();
1526     break;
1527   case Builtin::BI__builtin_isfinite:
1528   case Builtin::BI__builtin_isinf:
1529   case Builtin::BI__builtin_isinf_sign:
1530   case Builtin::BI__builtin_isnan:
1531   case Builtin::BI__builtin_isnormal:
1532   case Builtin::BI__builtin_signbit:
1533   case Builtin::BI__builtin_signbitf:
1534   case Builtin::BI__builtin_signbitl:
1535     if (SemaBuiltinFPClassification(TheCall, 1))
1536       return ExprError();
1537     break;
1538   case Builtin::BI__builtin_shufflevector:
1539     return SemaBuiltinShuffleVector(TheCall);
1540     // TheCall will be freed by the smart pointer here, but that's fine, since
1541     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1542   case Builtin::BI__builtin_prefetch:
1543     if (SemaBuiltinPrefetch(TheCall))
1544       return ExprError();
1545     break;
1546   case Builtin::BI__builtin_alloca_with_align:
1547     if (SemaBuiltinAllocaWithAlign(TheCall))
1548       return ExprError();
1549     LLVM_FALLTHROUGH;
1550   case Builtin::BI__builtin_alloca:
1551     Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1552         << TheCall->getDirectCallee();
1553     break;
1554   case Builtin::BI__assume:
1555   case Builtin::BI__builtin_assume:
1556     if (SemaBuiltinAssume(TheCall))
1557       return ExprError();
1558     break;
1559   case Builtin::BI__builtin_assume_aligned:
1560     if (SemaBuiltinAssumeAligned(TheCall))
1561       return ExprError();
1562     break;
1563   case Builtin::BI__builtin_dynamic_object_size:
1564   case Builtin::BI__builtin_object_size:
1565     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1566       return ExprError();
1567     break;
1568   case Builtin::BI__builtin_longjmp:
1569     if (SemaBuiltinLongjmp(TheCall))
1570       return ExprError();
1571     break;
1572   case Builtin::BI__builtin_setjmp:
1573     if (SemaBuiltinSetjmp(TheCall))
1574       return ExprError();
1575     break;
1576   case Builtin::BI_setjmp:
1577   case Builtin::BI_setjmpex:
1578     if (checkArgCount(*this, TheCall, 1))
1579       return true;
1580     break;
1581   case Builtin::BI__builtin_classify_type:
1582     if (checkArgCount(*this, TheCall, 1)) return true;
1583     TheCall->setType(Context.IntTy);
1584     break;
1585   case Builtin::BI__builtin_constant_p: {
1586     if (checkArgCount(*this, TheCall, 1)) return true;
1587     ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1588     if (Arg.isInvalid()) return true;
1589     TheCall->setArg(0, Arg.get());
1590     TheCall->setType(Context.IntTy);
1591     break;
1592   }
1593   case Builtin::BI__builtin_launder:
1594     return SemaBuiltinLaunder(*this, TheCall);
1595   case Builtin::BI__sync_fetch_and_add:
1596   case Builtin::BI__sync_fetch_and_add_1:
1597   case Builtin::BI__sync_fetch_and_add_2:
1598   case Builtin::BI__sync_fetch_and_add_4:
1599   case Builtin::BI__sync_fetch_and_add_8:
1600   case Builtin::BI__sync_fetch_and_add_16:
1601   case Builtin::BI__sync_fetch_and_sub:
1602   case Builtin::BI__sync_fetch_and_sub_1:
1603   case Builtin::BI__sync_fetch_and_sub_2:
1604   case Builtin::BI__sync_fetch_and_sub_4:
1605   case Builtin::BI__sync_fetch_and_sub_8:
1606   case Builtin::BI__sync_fetch_and_sub_16:
1607   case Builtin::BI__sync_fetch_and_or:
1608   case Builtin::BI__sync_fetch_and_or_1:
1609   case Builtin::BI__sync_fetch_and_or_2:
1610   case Builtin::BI__sync_fetch_and_or_4:
1611   case Builtin::BI__sync_fetch_and_or_8:
1612   case Builtin::BI__sync_fetch_and_or_16:
1613   case Builtin::BI__sync_fetch_and_and:
1614   case Builtin::BI__sync_fetch_and_and_1:
1615   case Builtin::BI__sync_fetch_and_and_2:
1616   case Builtin::BI__sync_fetch_and_and_4:
1617   case Builtin::BI__sync_fetch_and_and_8:
1618   case Builtin::BI__sync_fetch_and_and_16:
1619   case Builtin::BI__sync_fetch_and_xor:
1620   case Builtin::BI__sync_fetch_and_xor_1:
1621   case Builtin::BI__sync_fetch_and_xor_2:
1622   case Builtin::BI__sync_fetch_and_xor_4:
1623   case Builtin::BI__sync_fetch_and_xor_8:
1624   case Builtin::BI__sync_fetch_and_xor_16:
1625   case Builtin::BI__sync_fetch_and_nand:
1626   case Builtin::BI__sync_fetch_and_nand_1:
1627   case Builtin::BI__sync_fetch_and_nand_2:
1628   case Builtin::BI__sync_fetch_and_nand_4:
1629   case Builtin::BI__sync_fetch_and_nand_8:
1630   case Builtin::BI__sync_fetch_and_nand_16:
1631   case Builtin::BI__sync_add_and_fetch:
1632   case Builtin::BI__sync_add_and_fetch_1:
1633   case Builtin::BI__sync_add_and_fetch_2:
1634   case Builtin::BI__sync_add_and_fetch_4:
1635   case Builtin::BI__sync_add_and_fetch_8:
1636   case Builtin::BI__sync_add_and_fetch_16:
1637   case Builtin::BI__sync_sub_and_fetch:
1638   case Builtin::BI__sync_sub_and_fetch_1:
1639   case Builtin::BI__sync_sub_and_fetch_2:
1640   case Builtin::BI__sync_sub_and_fetch_4:
1641   case Builtin::BI__sync_sub_and_fetch_8:
1642   case Builtin::BI__sync_sub_and_fetch_16:
1643   case Builtin::BI__sync_and_and_fetch:
1644   case Builtin::BI__sync_and_and_fetch_1:
1645   case Builtin::BI__sync_and_and_fetch_2:
1646   case Builtin::BI__sync_and_and_fetch_4:
1647   case Builtin::BI__sync_and_and_fetch_8:
1648   case Builtin::BI__sync_and_and_fetch_16:
1649   case Builtin::BI__sync_or_and_fetch:
1650   case Builtin::BI__sync_or_and_fetch_1:
1651   case Builtin::BI__sync_or_and_fetch_2:
1652   case Builtin::BI__sync_or_and_fetch_4:
1653   case Builtin::BI__sync_or_and_fetch_8:
1654   case Builtin::BI__sync_or_and_fetch_16:
1655   case Builtin::BI__sync_xor_and_fetch:
1656   case Builtin::BI__sync_xor_and_fetch_1:
1657   case Builtin::BI__sync_xor_and_fetch_2:
1658   case Builtin::BI__sync_xor_and_fetch_4:
1659   case Builtin::BI__sync_xor_and_fetch_8:
1660   case Builtin::BI__sync_xor_and_fetch_16:
1661   case Builtin::BI__sync_nand_and_fetch:
1662   case Builtin::BI__sync_nand_and_fetch_1:
1663   case Builtin::BI__sync_nand_and_fetch_2:
1664   case Builtin::BI__sync_nand_and_fetch_4:
1665   case Builtin::BI__sync_nand_and_fetch_8:
1666   case Builtin::BI__sync_nand_and_fetch_16:
1667   case Builtin::BI__sync_val_compare_and_swap:
1668   case Builtin::BI__sync_val_compare_and_swap_1:
1669   case Builtin::BI__sync_val_compare_and_swap_2:
1670   case Builtin::BI__sync_val_compare_and_swap_4:
1671   case Builtin::BI__sync_val_compare_and_swap_8:
1672   case Builtin::BI__sync_val_compare_and_swap_16:
1673   case Builtin::BI__sync_bool_compare_and_swap:
1674   case Builtin::BI__sync_bool_compare_and_swap_1:
1675   case Builtin::BI__sync_bool_compare_and_swap_2:
1676   case Builtin::BI__sync_bool_compare_and_swap_4:
1677   case Builtin::BI__sync_bool_compare_and_swap_8:
1678   case Builtin::BI__sync_bool_compare_and_swap_16:
1679   case Builtin::BI__sync_lock_test_and_set:
1680   case Builtin::BI__sync_lock_test_and_set_1:
1681   case Builtin::BI__sync_lock_test_and_set_2:
1682   case Builtin::BI__sync_lock_test_and_set_4:
1683   case Builtin::BI__sync_lock_test_and_set_8:
1684   case Builtin::BI__sync_lock_test_and_set_16:
1685   case Builtin::BI__sync_lock_release:
1686   case Builtin::BI__sync_lock_release_1:
1687   case Builtin::BI__sync_lock_release_2:
1688   case Builtin::BI__sync_lock_release_4:
1689   case Builtin::BI__sync_lock_release_8:
1690   case Builtin::BI__sync_lock_release_16:
1691   case Builtin::BI__sync_swap:
1692   case Builtin::BI__sync_swap_1:
1693   case Builtin::BI__sync_swap_2:
1694   case Builtin::BI__sync_swap_4:
1695   case Builtin::BI__sync_swap_8:
1696   case Builtin::BI__sync_swap_16:
1697     return SemaBuiltinAtomicOverloaded(TheCallResult);
1698   case Builtin::BI__sync_synchronize:
1699     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1700         << TheCall->getCallee()->getSourceRange();
1701     break;
1702   case Builtin::BI__builtin_nontemporal_load:
1703   case Builtin::BI__builtin_nontemporal_store:
1704     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1705   case Builtin::BI__builtin_memcpy_inline: {
1706     clang::Expr *SizeOp = TheCall->getArg(2);
1707     // We warn about copying to or from `nullptr` pointers when `size` is
1708     // greater than 0. When `size` is value dependent we cannot evaluate its
1709     // value so we bail out.
1710     if (SizeOp->isValueDependent())
1711       break;
1712     if (!SizeOp->EvaluateKnownConstInt(Context).isNullValue()) {
1713       CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
1714       CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
1715     }
1716     break;
1717   }
1718 #define BUILTIN(ID, TYPE, ATTRS)
1719 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1720   case Builtin::BI##ID: \
1721     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1722 #include "clang/Basic/Builtins.def"
1723   case Builtin::BI__annotation:
1724     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1725       return ExprError();
1726     break;
1727   case Builtin::BI__builtin_annotation:
1728     if (SemaBuiltinAnnotation(*this, TheCall))
1729       return ExprError();
1730     break;
1731   case Builtin::BI__builtin_addressof:
1732     if (SemaBuiltinAddressof(*this, TheCall))
1733       return ExprError();
1734     break;
1735   case Builtin::BI__builtin_is_aligned:
1736   case Builtin::BI__builtin_align_up:
1737   case Builtin::BI__builtin_align_down:
1738     if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
1739       return ExprError();
1740     break;
1741   case Builtin::BI__builtin_add_overflow:
1742   case Builtin::BI__builtin_sub_overflow:
1743   case Builtin::BI__builtin_mul_overflow:
1744     if (SemaBuiltinOverflow(*this, TheCall, BuiltinID))
1745       return ExprError();
1746     break;
1747   case Builtin::BI__builtin_operator_new:
1748   case Builtin::BI__builtin_operator_delete: {
1749     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1750     ExprResult Res =
1751         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1752     if (Res.isInvalid())
1753       CorrectDelayedTyposInExpr(TheCallResult.get());
1754     return Res;
1755   }
1756   case Builtin::BI__builtin_dump_struct: {
1757     // We first want to ensure we are called with 2 arguments
1758     if (checkArgCount(*this, TheCall, 2))
1759       return ExprError();
1760     // Ensure that the first argument is of type 'struct XX *'
1761     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1762     const QualType PtrArgType = PtrArg->getType();
1763     if (!PtrArgType->isPointerType() ||
1764         !PtrArgType->getPointeeType()->isRecordType()) {
1765       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1766           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1767           << "structure pointer";
1768       return ExprError();
1769     }
1770 
1771     // Ensure that the second argument is of type 'FunctionType'
1772     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1773     const QualType FnPtrArgType = FnPtrArg->getType();
1774     if (!FnPtrArgType->isPointerType()) {
1775       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1776           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1777           << FnPtrArgType << "'int (*)(const char *, ...)'";
1778       return ExprError();
1779     }
1780 
1781     const auto *FuncType =
1782         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1783 
1784     if (!FuncType) {
1785       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1786           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1787           << FnPtrArgType << "'int (*)(const char *, ...)'";
1788       return ExprError();
1789     }
1790 
1791     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1792       if (!FT->getNumParams()) {
1793         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1794             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1795             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1796         return ExprError();
1797       }
1798       QualType PT = FT->getParamType(0);
1799       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1800           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1801           !PT->getPointeeType().isConstQualified()) {
1802         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1803             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1804             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1805         return ExprError();
1806       }
1807     }
1808 
1809     TheCall->setType(Context.IntTy);
1810     break;
1811   }
1812   case Builtin::BI__builtin_expect_with_probability: {
1813     // We first want to ensure we are called with 3 arguments
1814     if (checkArgCount(*this, TheCall, 3))
1815       return ExprError();
1816     // then check probability is constant float in range [0.0, 1.0]
1817     const Expr *ProbArg = TheCall->getArg(2);
1818     SmallVector<PartialDiagnosticAt, 8> Notes;
1819     Expr::EvalResult Eval;
1820     Eval.Diag = &Notes;
1821     if ((!ProbArg->EvaluateAsConstantExpr(Eval, Expr::EvaluateForCodeGen,
1822                                           Context)) ||
1823         !Eval.Val.isFloat()) {
1824       Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
1825           << ProbArg->getSourceRange();
1826       for (const PartialDiagnosticAt &PDiag : Notes)
1827         Diag(PDiag.first, PDiag.second);
1828       return ExprError();
1829     }
1830     llvm::APFloat Probability = Eval.Val.getFloat();
1831     bool LoseInfo = false;
1832     Probability.convert(llvm::APFloat::IEEEdouble(),
1833                         llvm::RoundingMode::Dynamic, &LoseInfo);
1834     if (!(Probability >= llvm::APFloat(0.0) &&
1835           Probability <= llvm::APFloat(1.0))) {
1836       Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
1837           << ProbArg->getSourceRange();
1838       return ExprError();
1839     }
1840     break;
1841   }
1842   case Builtin::BI__builtin_preserve_access_index:
1843     if (SemaBuiltinPreserveAI(*this, TheCall))
1844       return ExprError();
1845     break;
1846   case Builtin::BI__builtin_call_with_static_chain:
1847     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1848       return ExprError();
1849     break;
1850   case Builtin::BI__exception_code:
1851   case Builtin::BI_exception_code:
1852     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1853                                  diag::err_seh___except_block))
1854       return ExprError();
1855     break;
1856   case Builtin::BI__exception_info:
1857   case Builtin::BI_exception_info:
1858     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1859                                  diag::err_seh___except_filter))
1860       return ExprError();
1861     break;
1862   case Builtin::BI__GetExceptionInfo:
1863     if (checkArgCount(*this, TheCall, 1))
1864       return ExprError();
1865 
1866     if (CheckCXXThrowOperand(
1867             TheCall->getBeginLoc(),
1868             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1869             TheCall))
1870       return ExprError();
1871 
1872     TheCall->setType(Context.VoidPtrTy);
1873     break;
1874   // OpenCL v2.0, s6.13.16 - Pipe functions
1875   case Builtin::BIread_pipe:
1876   case Builtin::BIwrite_pipe:
1877     // Since those two functions are declared with var args, we need a semantic
1878     // check for the argument.
1879     if (SemaBuiltinRWPipe(*this, TheCall))
1880       return ExprError();
1881     break;
1882   case Builtin::BIreserve_read_pipe:
1883   case Builtin::BIreserve_write_pipe:
1884   case Builtin::BIwork_group_reserve_read_pipe:
1885   case Builtin::BIwork_group_reserve_write_pipe:
1886     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1887       return ExprError();
1888     break;
1889   case Builtin::BIsub_group_reserve_read_pipe:
1890   case Builtin::BIsub_group_reserve_write_pipe:
1891     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1892         SemaBuiltinReserveRWPipe(*this, TheCall))
1893       return ExprError();
1894     break;
1895   case Builtin::BIcommit_read_pipe:
1896   case Builtin::BIcommit_write_pipe:
1897   case Builtin::BIwork_group_commit_read_pipe:
1898   case Builtin::BIwork_group_commit_write_pipe:
1899     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1900       return ExprError();
1901     break;
1902   case Builtin::BIsub_group_commit_read_pipe:
1903   case Builtin::BIsub_group_commit_write_pipe:
1904     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1905         SemaBuiltinCommitRWPipe(*this, TheCall))
1906       return ExprError();
1907     break;
1908   case Builtin::BIget_pipe_num_packets:
1909   case Builtin::BIget_pipe_max_packets:
1910     if (SemaBuiltinPipePackets(*this, TheCall))
1911       return ExprError();
1912     break;
1913   case Builtin::BIto_global:
1914   case Builtin::BIto_local:
1915   case Builtin::BIto_private:
1916     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1917       return ExprError();
1918     break;
1919   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1920   case Builtin::BIenqueue_kernel:
1921     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1922       return ExprError();
1923     break;
1924   case Builtin::BIget_kernel_work_group_size:
1925   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1926     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1927       return ExprError();
1928     break;
1929   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1930   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1931     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1932       return ExprError();
1933     break;
1934   case Builtin::BI__builtin_os_log_format:
1935     Cleanup.setExprNeedsCleanups(true);
1936     LLVM_FALLTHROUGH;
1937   case Builtin::BI__builtin_os_log_format_buffer_size:
1938     if (SemaBuiltinOSLogFormat(TheCall))
1939       return ExprError();
1940     break;
1941   case Builtin::BI__builtin_frame_address:
1942   case Builtin::BI__builtin_return_address: {
1943     if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
1944       return ExprError();
1945 
1946     // -Wframe-address warning if non-zero passed to builtin
1947     // return/frame address.
1948     Expr::EvalResult Result;
1949     if (TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
1950         Result.Val.getInt() != 0)
1951       Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
1952           << ((BuiltinID == Builtin::BI__builtin_return_address)
1953                   ? "__builtin_return_address"
1954                   : "__builtin_frame_address")
1955           << TheCall->getSourceRange();
1956     break;
1957   }
1958 
1959   case Builtin::BI__builtin_matrix_transpose:
1960     return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
1961 
1962   case Builtin::BI__builtin_matrix_column_major_load:
1963     return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
1964 
1965   case Builtin::BI__builtin_matrix_column_major_store:
1966     return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
1967   }
1968 
1969   // Since the target specific builtins for each arch overlap, only check those
1970   // of the arch we are compiling for.
1971   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1972     if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
1973       assert(Context.getAuxTargetInfo() &&
1974              "Aux Target Builtin, but not an aux target?");
1975 
1976       if (CheckTSBuiltinFunctionCall(
1977               *Context.getAuxTargetInfo(),
1978               Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
1979         return ExprError();
1980     } else {
1981       if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
1982                                      TheCall))
1983         return ExprError();
1984     }
1985   }
1986 
1987   return TheCallResult;
1988 }
1989 
1990 // Get the valid immediate range for the specified NEON type code.
1991 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1992   NeonTypeFlags Type(t);
1993   int IsQuad = ForceQuad ? true : Type.isQuad();
1994   switch (Type.getEltType()) {
1995   case NeonTypeFlags::Int8:
1996   case NeonTypeFlags::Poly8:
1997     return shift ? 7 : (8 << IsQuad) - 1;
1998   case NeonTypeFlags::Int16:
1999   case NeonTypeFlags::Poly16:
2000     return shift ? 15 : (4 << IsQuad) - 1;
2001   case NeonTypeFlags::Int32:
2002     return shift ? 31 : (2 << IsQuad) - 1;
2003   case NeonTypeFlags::Int64:
2004   case NeonTypeFlags::Poly64:
2005     return shift ? 63 : (1 << IsQuad) - 1;
2006   case NeonTypeFlags::Poly128:
2007     return shift ? 127 : (1 << IsQuad) - 1;
2008   case NeonTypeFlags::Float16:
2009     assert(!shift && "cannot shift float types!");
2010     return (4 << IsQuad) - 1;
2011   case NeonTypeFlags::Float32:
2012     assert(!shift && "cannot shift float types!");
2013     return (2 << IsQuad) - 1;
2014   case NeonTypeFlags::Float64:
2015     assert(!shift && "cannot shift float types!");
2016     return (1 << IsQuad) - 1;
2017   case NeonTypeFlags::BFloat16:
2018     assert(!shift && "cannot shift float types!");
2019     return (4 << IsQuad) - 1;
2020   }
2021   llvm_unreachable("Invalid NeonTypeFlag!");
2022 }
2023 
2024 /// getNeonEltType - Return the QualType corresponding to the elements of
2025 /// the vector type specified by the NeonTypeFlags.  This is used to check
2026 /// the pointer arguments for Neon load/store intrinsics.
2027 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
2028                                bool IsPolyUnsigned, bool IsInt64Long) {
2029   switch (Flags.getEltType()) {
2030   case NeonTypeFlags::Int8:
2031     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
2032   case NeonTypeFlags::Int16:
2033     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
2034   case NeonTypeFlags::Int32:
2035     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
2036   case NeonTypeFlags::Int64:
2037     if (IsInt64Long)
2038       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
2039     else
2040       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
2041                                 : Context.LongLongTy;
2042   case NeonTypeFlags::Poly8:
2043     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
2044   case NeonTypeFlags::Poly16:
2045     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
2046   case NeonTypeFlags::Poly64:
2047     if (IsInt64Long)
2048       return Context.UnsignedLongTy;
2049     else
2050       return Context.UnsignedLongLongTy;
2051   case NeonTypeFlags::Poly128:
2052     break;
2053   case NeonTypeFlags::Float16:
2054     return Context.HalfTy;
2055   case NeonTypeFlags::Float32:
2056     return Context.FloatTy;
2057   case NeonTypeFlags::Float64:
2058     return Context.DoubleTy;
2059   case NeonTypeFlags::BFloat16:
2060     return Context.BFloat16Ty;
2061   }
2062   llvm_unreachable("Invalid NeonTypeFlag!");
2063 }
2064 
2065 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2066   // Range check SVE intrinsics that take immediate values.
2067   SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
2068 
2069   switch (BuiltinID) {
2070   default:
2071     return false;
2072 #define GET_SVE_IMMEDIATE_CHECK
2073 #include "clang/Basic/arm_sve_sema_rangechecks.inc"
2074 #undef GET_SVE_IMMEDIATE_CHECK
2075   }
2076 
2077   // Perform all the immediate checks for this builtin call.
2078   bool HasError = false;
2079   for (auto &I : ImmChecks) {
2080     int ArgNum, CheckTy, ElementSizeInBits;
2081     std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
2082 
2083     typedef bool(*OptionSetCheckFnTy)(int64_t Value);
2084 
2085     // Function that checks whether the operand (ArgNum) is an immediate
2086     // that is one of the predefined values.
2087     auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
2088                                    int ErrDiag) -> bool {
2089       // We can't check the value of a dependent argument.
2090       Expr *Arg = TheCall->getArg(ArgNum);
2091       if (Arg->isTypeDependent() || Arg->isValueDependent())
2092         return false;
2093 
2094       // Check constant-ness first.
2095       llvm::APSInt Imm;
2096       if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
2097         return true;
2098 
2099       if (!CheckImm(Imm.getSExtValue()))
2100         return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
2101       return false;
2102     };
2103 
2104     switch ((SVETypeFlags::ImmCheckType)CheckTy) {
2105     case SVETypeFlags::ImmCheck0_31:
2106       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
2107         HasError = true;
2108       break;
2109     case SVETypeFlags::ImmCheck0_13:
2110       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
2111         HasError = true;
2112       break;
2113     case SVETypeFlags::ImmCheck1_16:
2114       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
2115         HasError = true;
2116       break;
2117     case SVETypeFlags::ImmCheck0_7:
2118       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
2119         HasError = true;
2120       break;
2121     case SVETypeFlags::ImmCheckExtract:
2122       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2123                                       (2048 / ElementSizeInBits) - 1))
2124         HasError = true;
2125       break;
2126     case SVETypeFlags::ImmCheckShiftRight:
2127       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
2128         HasError = true;
2129       break;
2130     case SVETypeFlags::ImmCheckShiftRightNarrow:
2131       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
2132                                       ElementSizeInBits / 2))
2133         HasError = true;
2134       break;
2135     case SVETypeFlags::ImmCheckShiftLeft:
2136       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2137                                       ElementSizeInBits - 1))
2138         HasError = true;
2139       break;
2140     case SVETypeFlags::ImmCheckLaneIndex:
2141       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2142                                       (128 / (1 * ElementSizeInBits)) - 1))
2143         HasError = true;
2144       break;
2145     case SVETypeFlags::ImmCheckLaneIndexCompRotate:
2146       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2147                                       (128 / (2 * ElementSizeInBits)) - 1))
2148         HasError = true;
2149       break;
2150     case SVETypeFlags::ImmCheckLaneIndexDot:
2151       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2152                                       (128 / (4 * ElementSizeInBits)) - 1))
2153         HasError = true;
2154       break;
2155     case SVETypeFlags::ImmCheckComplexRot90_270:
2156       if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
2157                               diag::err_rotation_argument_to_cadd))
2158         HasError = true;
2159       break;
2160     case SVETypeFlags::ImmCheckComplexRotAll90:
2161       if (CheckImmediateInSet(
2162               [](int64_t V) {
2163                 return V == 0 || V == 90 || V == 180 || V == 270;
2164               },
2165               diag::err_rotation_argument_to_cmla))
2166         HasError = true;
2167       break;
2168     case SVETypeFlags::ImmCheck0_1:
2169       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1))
2170         HasError = true;
2171       break;
2172     case SVETypeFlags::ImmCheck0_2:
2173       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2))
2174         HasError = true;
2175       break;
2176     case SVETypeFlags::ImmCheck0_3:
2177       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3))
2178         HasError = true;
2179       break;
2180     }
2181   }
2182 
2183   return HasError;
2184 }
2185 
2186 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
2187                                         unsigned BuiltinID, CallExpr *TheCall) {
2188   llvm::APSInt Result;
2189   uint64_t mask = 0;
2190   unsigned TV = 0;
2191   int PtrArgNum = -1;
2192   bool HasConstPtr = false;
2193   switch (BuiltinID) {
2194 #define GET_NEON_OVERLOAD_CHECK
2195 #include "clang/Basic/arm_neon.inc"
2196 #include "clang/Basic/arm_fp16.inc"
2197 #undef GET_NEON_OVERLOAD_CHECK
2198   }
2199 
2200   // For NEON intrinsics which are overloaded on vector element type, validate
2201   // the immediate which specifies which variant to emit.
2202   unsigned ImmArg = TheCall->getNumArgs()-1;
2203   if (mask) {
2204     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
2205       return true;
2206 
2207     TV = Result.getLimitedValue(64);
2208     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
2209       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
2210              << TheCall->getArg(ImmArg)->getSourceRange();
2211   }
2212 
2213   if (PtrArgNum >= 0) {
2214     // Check that pointer arguments have the specified type.
2215     Expr *Arg = TheCall->getArg(PtrArgNum);
2216     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
2217       Arg = ICE->getSubExpr();
2218     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
2219     QualType RHSTy = RHS.get()->getType();
2220 
2221     llvm::Triple::ArchType Arch = TI.getTriple().getArch();
2222     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2223                           Arch == llvm::Triple::aarch64_32 ||
2224                           Arch == llvm::Triple::aarch64_be;
2225     bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
2226     QualType EltTy =
2227         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2228     if (HasConstPtr)
2229       EltTy = EltTy.withConst();
2230     QualType LHSTy = Context.getPointerType(EltTy);
2231     AssignConvertType ConvTy;
2232     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2233     if (RHS.isInvalid())
2234       return true;
2235     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2236                                  RHS.get(), AA_Assigning))
2237       return true;
2238   }
2239 
2240   // For NEON intrinsics which take an immediate value as part of the
2241   // instruction, range check them here.
2242   unsigned i = 0, l = 0, u = 0;
2243   switch (BuiltinID) {
2244   default:
2245     return false;
2246   #define GET_NEON_IMMEDIATE_CHECK
2247   #include "clang/Basic/arm_neon.inc"
2248   #include "clang/Basic/arm_fp16.inc"
2249   #undef GET_NEON_IMMEDIATE_CHECK
2250   }
2251 
2252   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2253 }
2254 
2255 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2256   switch (BuiltinID) {
2257   default:
2258     return false;
2259   #include "clang/Basic/arm_mve_builtin_sema.inc"
2260   }
2261 }
2262 
2263 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2264                                        CallExpr *TheCall) {
2265   bool Err = false;
2266   switch (BuiltinID) {
2267   default:
2268     return false;
2269 #include "clang/Basic/arm_cde_builtin_sema.inc"
2270   }
2271 
2272   if (Err)
2273     return true;
2274 
2275   return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
2276 }
2277 
2278 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
2279                                         const Expr *CoprocArg, bool WantCDE) {
2280   if (isConstantEvaluated())
2281     return false;
2282 
2283   // We can't check the value of a dependent argument.
2284   if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
2285     return false;
2286 
2287   llvm::APSInt CoprocNoAP;
2288   bool IsICE = CoprocArg->isIntegerConstantExpr(CoprocNoAP, Context);
2289   (void)IsICE;
2290   assert(IsICE && "Coprocossor immediate is not a constant expression");
2291   int64_t CoprocNo = CoprocNoAP.getExtValue();
2292   assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
2293 
2294   uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
2295   bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
2296 
2297   if (IsCDECoproc != WantCDE)
2298     return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
2299            << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
2300 
2301   return false;
2302 }
2303 
2304 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2305                                         unsigned MaxWidth) {
2306   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
2307           BuiltinID == ARM::BI__builtin_arm_ldaex ||
2308           BuiltinID == ARM::BI__builtin_arm_strex ||
2309           BuiltinID == ARM::BI__builtin_arm_stlex ||
2310           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2311           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2312           BuiltinID == AArch64::BI__builtin_arm_strex ||
2313           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
2314          "unexpected ARM builtin");
2315   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2316                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
2317                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2318                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
2319 
2320   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2321 
2322   // Ensure that we have the proper number of arguments.
2323   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
2324     return true;
2325 
2326   // Inspect the pointer argument of the atomic builtin.  This should always be
2327   // a pointer type, whose element is an integral scalar or pointer type.
2328   // Because it is a pointer type, we don't have to worry about any implicit
2329   // casts here.
2330   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
2331   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
2332   if (PointerArgRes.isInvalid())
2333     return true;
2334   PointerArg = PointerArgRes.get();
2335 
2336   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2337   if (!pointerType) {
2338     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
2339         << PointerArg->getType() << PointerArg->getSourceRange();
2340     return true;
2341   }
2342 
2343   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
2344   // task is to insert the appropriate casts into the AST. First work out just
2345   // what the appropriate type is.
2346   QualType ValType = pointerType->getPointeeType();
2347   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
2348   if (IsLdrex)
2349     AddrType.addConst();
2350 
2351   // Issue a warning if the cast is dodgy.
2352   CastKind CastNeeded = CK_NoOp;
2353   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
2354     CastNeeded = CK_BitCast;
2355     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
2356         << PointerArg->getType() << Context.getPointerType(AddrType)
2357         << AA_Passing << PointerArg->getSourceRange();
2358   }
2359 
2360   // Finally, do the cast and replace the argument with the corrected version.
2361   AddrType = Context.getPointerType(AddrType);
2362   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
2363   if (PointerArgRes.isInvalid())
2364     return true;
2365   PointerArg = PointerArgRes.get();
2366 
2367   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
2368 
2369   // In general, we allow ints, floats and pointers to be loaded and stored.
2370   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2371       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
2372     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
2373         << PointerArg->getType() << PointerArg->getSourceRange();
2374     return true;
2375   }
2376 
2377   // But ARM doesn't have instructions to deal with 128-bit versions.
2378   if (Context.getTypeSize(ValType) > MaxWidth) {
2379     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
2380     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
2381         << PointerArg->getType() << PointerArg->getSourceRange();
2382     return true;
2383   }
2384 
2385   switch (ValType.getObjCLifetime()) {
2386   case Qualifiers::OCL_None:
2387   case Qualifiers::OCL_ExplicitNone:
2388     // okay
2389     break;
2390 
2391   case Qualifiers::OCL_Weak:
2392   case Qualifiers::OCL_Strong:
2393   case Qualifiers::OCL_Autoreleasing:
2394     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
2395         << ValType << PointerArg->getSourceRange();
2396     return true;
2397   }
2398 
2399   if (IsLdrex) {
2400     TheCall->setType(ValType);
2401     return false;
2402   }
2403 
2404   // Initialize the argument to be stored.
2405   ExprResult ValArg = TheCall->getArg(0);
2406   InitializedEntity Entity = InitializedEntity::InitializeParameter(
2407       Context, ValType, /*consume*/ false);
2408   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2409   if (ValArg.isInvalid())
2410     return true;
2411   TheCall->setArg(0, ValArg.get());
2412 
2413   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
2414   // but the custom checker bypasses all default analysis.
2415   TheCall->setType(Context.IntTy);
2416   return false;
2417 }
2418 
2419 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2420                                        CallExpr *TheCall) {
2421   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
2422       BuiltinID == ARM::BI__builtin_arm_ldaex ||
2423       BuiltinID == ARM::BI__builtin_arm_strex ||
2424       BuiltinID == ARM::BI__builtin_arm_stlex) {
2425     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
2426   }
2427 
2428   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
2429     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2430       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
2431   }
2432 
2433   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2434       BuiltinID == ARM::BI__builtin_arm_wsr64)
2435     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
2436 
2437   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
2438       BuiltinID == ARM::BI__builtin_arm_rsrp ||
2439       BuiltinID == ARM::BI__builtin_arm_wsr ||
2440       BuiltinID == ARM::BI__builtin_arm_wsrp)
2441     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2442 
2443   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2444     return true;
2445   if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
2446     return true;
2447   if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
2448     return true;
2449 
2450   // For intrinsics which take an immediate value as part of the instruction,
2451   // range check them here.
2452   // FIXME: VFP Intrinsics should error if VFP not present.
2453   switch (BuiltinID) {
2454   default: return false;
2455   case ARM::BI__builtin_arm_ssat:
2456     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
2457   case ARM::BI__builtin_arm_usat:
2458     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
2459   case ARM::BI__builtin_arm_ssat16:
2460     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
2461   case ARM::BI__builtin_arm_usat16:
2462     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2463   case ARM::BI__builtin_arm_vcvtr_f:
2464   case ARM::BI__builtin_arm_vcvtr_d:
2465     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2466   case ARM::BI__builtin_arm_dmb:
2467   case ARM::BI__builtin_arm_dsb:
2468   case ARM::BI__builtin_arm_isb:
2469   case ARM::BI__builtin_arm_dbg:
2470     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
2471   case ARM::BI__builtin_arm_cdp:
2472   case ARM::BI__builtin_arm_cdp2:
2473   case ARM::BI__builtin_arm_mcr:
2474   case ARM::BI__builtin_arm_mcr2:
2475   case ARM::BI__builtin_arm_mrc:
2476   case ARM::BI__builtin_arm_mrc2:
2477   case ARM::BI__builtin_arm_mcrr:
2478   case ARM::BI__builtin_arm_mcrr2:
2479   case ARM::BI__builtin_arm_mrrc:
2480   case ARM::BI__builtin_arm_mrrc2:
2481   case ARM::BI__builtin_arm_ldc:
2482   case ARM::BI__builtin_arm_ldcl:
2483   case ARM::BI__builtin_arm_ldc2:
2484   case ARM::BI__builtin_arm_ldc2l:
2485   case ARM::BI__builtin_arm_stc:
2486   case ARM::BI__builtin_arm_stcl:
2487   case ARM::BI__builtin_arm_stc2:
2488   case ARM::BI__builtin_arm_stc2l:
2489     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
2490            CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
2491                                         /*WantCDE*/ false);
2492   }
2493 }
2494 
2495 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
2496                                            unsigned BuiltinID,
2497                                            CallExpr *TheCall) {
2498   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2499       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2500       BuiltinID == AArch64::BI__builtin_arm_strex ||
2501       BuiltinID == AArch64::BI__builtin_arm_stlex) {
2502     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
2503   }
2504 
2505   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
2506     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2507       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
2508       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2509       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2510   }
2511 
2512   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2513       BuiltinID == AArch64::BI__builtin_arm_wsr64)
2514     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2515 
2516   // Memory Tagging Extensions (MTE) Intrinsics
2517   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2518       BuiltinID == AArch64::BI__builtin_arm_addg ||
2519       BuiltinID == AArch64::BI__builtin_arm_gmi ||
2520       BuiltinID == AArch64::BI__builtin_arm_ldg ||
2521       BuiltinID == AArch64::BI__builtin_arm_stg ||
2522       BuiltinID == AArch64::BI__builtin_arm_subp) {
2523     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2524   }
2525 
2526   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2527       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2528       BuiltinID == AArch64::BI__builtin_arm_wsr ||
2529       BuiltinID == AArch64::BI__builtin_arm_wsrp)
2530     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2531 
2532   // Only check the valid encoding range. Any constant in this range would be
2533   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2534   // an exception for incorrect registers. This matches MSVC behavior.
2535   if (BuiltinID == AArch64::BI_ReadStatusReg ||
2536       BuiltinID == AArch64::BI_WriteStatusReg)
2537     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2538 
2539   if (BuiltinID == AArch64::BI__getReg)
2540     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2541 
2542   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2543     return true;
2544 
2545   if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
2546     return true;
2547 
2548   // For intrinsics which take an immediate value as part of the instruction,
2549   // range check them here.
2550   unsigned i = 0, l = 0, u = 0;
2551   switch (BuiltinID) {
2552   default: return false;
2553   case AArch64::BI__builtin_arm_dmb:
2554   case AArch64::BI__builtin_arm_dsb:
2555   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2556   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2557   }
2558 
2559   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2560 }
2561 
2562 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
2563                                        CallExpr *TheCall) {
2564   assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
2565           BuiltinID == BPF::BI__builtin_btf_type_id) &&
2566          "unexpected ARM builtin");
2567 
2568   if (checkArgCount(*this, TheCall, 2))
2569     return true;
2570 
2571   Expr *Arg;
2572   if (BuiltinID == BPF::BI__builtin_btf_type_id) {
2573     // The second argument needs to be a constant int
2574     llvm::APSInt Value;
2575     Arg = TheCall->getArg(1);
2576     if (!Arg->isIntegerConstantExpr(Value, Context)) {
2577       Diag(Arg->getBeginLoc(), diag::err_btf_type_id_not_const)
2578           << 2 << Arg->getSourceRange();
2579       return true;
2580     }
2581 
2582     TheCall->setType(Context.UnsignedIntTy);
2583     return false;
2584   }
2585 
2586   // The first argument needs to be a record field access.
2587   // If it is an array element access, we delay decision
2588   // to BPF backend to check whether the access is a
2589   // field access or not.
2590   Arg = TheCall->getArg(0);
2591   if (Arg->getType()->getAsPlaceholderType() ||
2592       (Arg->IgnoreParens()->getObjectKind() != OK_BitField &&
2593        !dyn_cast<MemberExpr>(Arg->IgnoreParens()) &&
2594        !dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()))) {
2595     Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_field)
2596         << 1 << Arg->getSourceRange();
2597     return true;
2598   }
2599 
2600   // The second argument needs to be a constant int
2601   Arg = TheCall->getArg(1);
2602   llvm::APSInt Value;
2603   if (!Arg->isIntegerConstantExpr(Value, Context)) {
2604     Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_const)
2605         << 2 << Arg->getSourceRange();
2606     return true;
2607   }
2608 
2609   TheCall->setType(Context.UnsignedIntTy);
2610   return false;
2611 }
2612 
2613 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2614   struct ArgInfo {
2615     uint8_t OpNum;
2616     bool IsSigned;
2617     uint8_t BitWidth;
2618     uint8_t Align;
2619   };
2620   struct BuiltinInfo {
2621     unsigned BuiltinID;
2622     ArgInfo Infos[2];
2623   };
2624 
2625   static BuiltinInfo Infos[] = {
2626     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2627     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2628     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2629     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  1 }} },
2630     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2631     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2632     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2633     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2634     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2635     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2636     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2637 
2638     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2639     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2640     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2641     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2642     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2643     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2644     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2645     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2646     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2647     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2648     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2649 
2650     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2651     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2652     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2653     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2654     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2655     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2656     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2657     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2658     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2659     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2660     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2661     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2662     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2663     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2664     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2665     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2666     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2667     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2668     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2669     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2670     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2671     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2672     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2673     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2674     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2675     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2676     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2677     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2678     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2679     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2680     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2681     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
2682     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
2683     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
2684     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
2685     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
2686     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
2687     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
2688     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
2689     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
2690     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
2691     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
2692     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
2693     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
2694     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
2695     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
2696     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
2697     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
2698     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
2699     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
2700     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
2701     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2702                                                       {{ 1, false, 6,  0 }} },
2703     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
2704     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
2705     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
2706     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
2707     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
2708     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
2709     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2710                                                       {{ 1, false, 5,  0 }} },
2711     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
2712     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
2713     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
2714     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
2715     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
2716     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
2717                                                        { 2, false, 5,  0 }} },
2718     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
2719                                                        { 2, false, 6,  0 }} },
2720     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
2721                                                        { 3, false, 5,  0 }} },
2722     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
2723                                                        { 3, false, 6,  0 }} },
2724     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
2725     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
2726     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
2727     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
2728     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
2729     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
2730     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
2731     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
2732     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
2733     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
2734     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
2735     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
2736     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
2737     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
2738     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
2739     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2740                                                       {{ 2, false, 4,  0 },
2741                                                        { 3, false, 5,  0 }} },
2742     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2743                                                       {{ 2, false, 4,  0 },
2744                                                        { 3, false, 5,  0 }} },
2745     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2746                                                       {{ 2, false, 4,  0 },
2747                                                        { 3, false, 5,  0 }} },
2748     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2749                                                       {{ 2, false, 4,  0 },
2750                                                        { 3, false, 5,  0 }} },
2751     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
2752     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
2753     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
2754     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
2755     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
2756     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
2757     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
2758     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
2759     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
2760     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
2761     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
2762                                                        { 2, false, 5,  0 }} },
2763     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
2764                                                        { 2, false, 6,  0 }} },
2765     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
2766     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
2767     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
2768     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
2769     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
2770     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
2771     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
2772     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
2773     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2774                                                       {{ 1, false, 4,  0 }} },
2775     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
2776     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2777                                                       {{ 1, false, 4,  0 }} },
2778     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
2779     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
2780     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
2781     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
2782     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
2783     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
2784     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
2785     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
2786     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
2787     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
2788     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
2789     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
2790     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
2791     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
2792     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
2793     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
2794     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
2795     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
2796     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
2797     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2798                                                       {{ 3, false, 1,  0 }} },
2799     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
2800     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
2801     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
2802     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2803                                                       {{ 3, false, 1,  0 }} },
2804     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
2805     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
2806     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
2807     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2808                                                       {{ 3, false, 1,  0 }} },
2809   };
2810 
2811   // Use a dynamically initialized static to sort the table exactly once on
2812   // first run.
2813   static const bool SortOnce =
2814       (llvm::sort(Infos,
2815                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
2816                    return LHS.BuiltinID < RHS.BuiltinID;
2817                  }),
2818        true);
2819   (void)SortOnce;
2820 
2821   const BuiltinInfo *F = llvm::partition_point(
2822       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
2823   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
2824     return false;
2825 
2826   bool Error = false;
2827 
2828   for (const ArgInfo &A : F->Infos) {
2829     // Ignore empty ArgInfo elements.
2830     if (A.BitWidth == 0)
2831       continue;
2832 
2833     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
2834     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
2835     if (!A.Align) {
2836       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2837     } else {
2838       unsigned M = 1 << A.Align;
2839       Min *= M;
2840       Max *= M;
2841       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
2842                SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
2843     }
2844   }
2845   return Error;
2846 }
2847 
2848 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
2849                                            CallExpr *TheCall) {
2850   return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
2851 }
2852 
2853 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
2854                                         unsigned BuiltinID, CallExpr *TheCall) {
2855   return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
2856          CheckMipsBuiltinArgument(BuiltinID, TheCall);
2857 }
2858 
2859 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
2860                                CallExpr *TheCall) {
2861 
2862   if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
2863       BuiltinID <= Mips::BI__builtin_mips_lwx) {
2864     if (!TI.hasFeature("dsp"))
2865       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
2866   }
2867 
2868   if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
2869       BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
2870     if (!TI.hasFeature("dspr2"))
2871       return Diag(TheCall->getBeginLoc(),
2872                   diag::err_mips_builtin_requires_dspr2);
2873   }
2874 
2875   if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
2876       BuiltinID <= Mips::BI__builtin_msa_xori_b) {
2877     if (!TI.hasFeature("msa"))
2878       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
2879   }
2880 
2881   return false;
2882 }
2883 
2884 // CheckMipsBuiltinArgument - Checks the constant value passed to the
2885 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
2886 // ordering for DSP is unspecified. MSA is ordered by the data format used
2887 // by the underlying instruction i.e., df/m, df/n and then by size.
2888 //
2889 // FIXME: The size tests here should instead be tablegen'd along with the
2890 //        definitions from include/clang/Basic/BuiltinsMips.def.
2891 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
2892 //        be too.
2893 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2894   unsigned i = 0, l = 0, u = 0, m = 0;
2895   switch (BuiltinID) {
2896   default: return false;
2897   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
2898   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
2899   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
2900   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
2901   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
2902   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
2903   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
2904   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
2905   // df/m field.
2906   // These intrinsics take an unsigned 3 bit immediate.
2907   case Mips::BI__builtin_msa_bclri_b:
2908   case Mips::BI__builtin_msa_bnegi_b:
2909   case Mips::BI__builtin_msa_bseti_b:
2910   case Mips::BI__builtin_msa_sat_s_b:
2911   case Mips::BI__builtin_msa_sat_u_b:
2912   case Mips::BI__builtin_msa_slli_b:
2913   case Mips::BI__builtin_msa_srai_b:
2914   case Mips::BI__builtin_msa_srari_b:
2915   case Mips::BI__builtin_msa_srli_b:
2916   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
2917   case Mips::BI__builtin_msa_binsli_b:
2918   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
2919   // These intrinsics take an unsigned 4 bit immediate.
2920   case Mips::BI__builtin_msa_bclri_h:
2921   case Mips::BI__builtin_msa_bnegi_h:
2922   case Mips::BI__builtin_msa_bseti_h:
2923   case Mips::BI__builtin_msa_sat_s_h:
2924   case Mips::BI__builtin_msa_sat_u_h:
2925   case Mips::BI__builtin_msa_slli_h:
2926   case Mips::BI__builtin_msa_srai_h:
2927   case Mips::BI__builtin_msa_srari_h:
2928   case Mips::BI__builtin_msa_srli_h:
2929   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
2930   case Mips::BI__builtin_msa_binsli_h:
2931   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
2932   // These intrinsics take an unsigned 5 bit immediate.
2933   // The first block of intrinsics actually have an unsigned 5 bit field,
2934   // not a df/n field.
2935   case Mips::BI__builtin_msa_cfcmsa:
2936   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
2937   case Mips::BI__builtin_msa_clei_u_b:
2938   case Mips::BI__builtin_msa_clei_u_h:
2939   case Mips::BI__builtin_msa_clei_u_w:
2940   case Mips::BI__builtin_msa_clei_u_d:
2941   case Mips::BI__builtin_msa_clti_u_b:
2942   case Mips::BI__builtin_msa_clti_u_h:
2943   case Mips::BI__builtin_msa_clti_u_w:
2944   case Mips::BI__builtin_msa_clti_u_d:
2945   case Mips::BI__builtin_msa_maxi_u_b:
2946   case Mips::BI__builtin_msa_maxi_u_h:
2947   case Mips::BI__builtin_msa_maxi_u_w:
2948   case Mips::BI__builtin_msa_maxi_u_d:
2949   case Mips::BI__builtin_msa_mini_u_b:
2950   case Mips::BI__builtin_msa_mini_u_h:
2951   case Mips::BI__builtin_msa_mini_u_w:
2952   case Mips::BI__builtin_msa_mini_u_d:
2953   case Mips::BI__builtin_msa_addvi_b:
2954   case Mips::BI__builtin_msa_addvi_h:
2955   case Mips::BI__builtin_msa_addvi_w:
2956   case Mips::BI__builtin_msa_addvi_d:
2957   case Mips::BI__builtin_msa_bclri_w:
2958   case Mips::BI__builtin_msa_bnegi_w:
2959   case Mips::BI__builtin_msa_bseti_w:
2960   case Mips::BI__builtin_msa_sat_s_w:
2961   case Mips::BI__builtin_msa_sat_u_w:
2962   case Mips::BI__builtin_msa_slli_w:
2963   case Mips::BI__builtin_msa_srai_w:
2964   case Mips::BI__builtin_msa_srari_w:
2965   case Mips::BI__builtin_msa_srli_w:
2966   case Mips::BI__builtin_msa_srlri_w:
2967   case Mips::BI__builtin_msa_subvi_b:
2968   case Mips::BI__builtin_msa_subvi_h:
2969   case Mips::BI__builtin_msa_subvi_w:
2970   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
2971   case Mips::BI__builtin_msa_binsli_w:
2972   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
2973   // These intrinsics take an unsigned 6 bit immediate.
2974   case Mips::BI__builtin_msa_bclri_d:
2975   case Mips::BI__builtin_msa_bnegi_d:
2976   case Mips::BI__builtin_msa_bseti_d:
2977   case Mips::BI__builtin_msa_sat_s_d:
2978   case Mips::BI__builtin_msa_sat_u_d:
2979   case Mips::BI__builtin_msa_slli_d:
2980   case Mips::BI__builtin_msa_srai_d:
2981   case Mips::BI__builtin_msa_srari_d:
2982   case Mips::BI__builtin_msa_srli_d:
2983   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
2984   case Mips::BI__builtin_msa_binsli_d:
2985   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
2986   // These intrinsics take a signed 5 bit immediate.
2987   case Mips::BI__builtin_msa_ceqi_b:
2988   case Mips::BI__builtin_msa_ceqi_h:
2989   case Mips::BI__builtin_msa_ceqi_w:
2990   case Mips::BI__builtin_msa_ceqi_d:
2991   case Mips::BI__builtin_msa_clti_s_b:
2992   case Mips::BI__builtin_msa_clti_s_h:
2993   case Mips::BI__builtin_msa_clti_s_w:
2994   case Mips::BI__builtin_msa_clti_s_d:
2995   case Mips::BI__builtin_msa_clei_s_b:
2996   case Mips::BI__builtin_msa_clei_s_h:
2997   case Mips::BI__builtin_msa_clei_s_w:
2998   case Mips::BI__builtin_msa_clei_s_d:
2999   case Mips::BI__builtin_msa_maxi_s_b:
3000   case Mips::BI__builtin_msa_maxi_s_h:
3001   case Mips::BI__builtin_msa_maxi_s_w:
3002   case Mips::BI__builtin_msa_maxi_s_d:
3003   case Mips::BI__builtin_msa_mini_s_b:
3004   case Mips::BI__builtin_msa_mini_s_h:
3005   case Mips::BI__builtin_msa_mini_s_w:
3006   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3007   // These intrinsics take an unsigned 8 bit immediate.
3008   case Mips::BI__builtin_msa_andi_b:
3009   case Mips::BI__builtin_msa_nori_b:
3010   case Mips::BI__builtin_msa_ori_b:
3011   case Mips::BI__builtin_msa_shf_b:
3012   case Mips::BI__builtin_msa_shf_h:
3013   case Mips::BI__builtin_msa_shf_w:
3014   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3015   case Mips::BI__builtin_msa_bseli_b:
3016   case Mips::BI__builtin_msa_bmnzi_b:
3017   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3018   // df/n format
3019   // These intrinsics take an unsigned 4 bit immediate.
3020   case Mips::BI__builtin_msa_copy_s_b:
3021   case Mips::BI__builtin_msa_copy_u_b:
3022   case Mips::BI__builtin_msa_insve_b:
3023   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3024   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3025   // These intrinsics take an unsigned 3 bit immediate.
3026   case Mips::BI__builtin_msa_copy_s_h:
3027   case Mips::BI__builtin_msa_copy_u_h:
3028   case Mips::BI__builtin_msa_insve_h:
3029   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3030   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3031   // These intrinsics take an unsigned 2 bit immediate.
3032   case Mips::BI__builtin_msa_copy_s_w:
3033   case Mips::BI__builtin_msa_copy_u_w:
3034   case Mips::BI__builtin_msa_insve_w:
3035   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3036   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3037   // These intrinsics take an unsigned 1 bit immediate.
3038   case Mips::BI__builtin_msa_copy_s_d:
3039   case Mips::BI__builtin_msa_copy_u_d:
3040   case Mips::BI__builtin_msa_insve_d:
3041   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3042   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3043   // Memory offsets and immediate loads.
3044   // These intrinsics take a signed 10 bit immediate.
3045   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3046   case Mips::BI__builtin_msa_ldi_h:
3047   case Mips::BI__builtin_msa_ldi_w:
3048   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3049   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3050   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3051   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3052   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3053   case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
3054   case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
3055   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3056   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3057   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3058   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3059   case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
3060   case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
3061   }
3062 
3063   if (!m)
3064     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3065 
3066   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3067          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3068 }
3069 
3070 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3071                                        CallExpr *TheCall) {
3072   unsigned i = 0, l = 0, u = 0;
3073   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
3074                       BuiltinID == PPC::BI__builtin_divdeu ||
3075                       BuiltinID == PPC::BI__builtin_bpermd;
3076   bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
3077   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
3078                        BuiltinID == PPC::BI__builtin_divweu ||
3079                        BuiltinID == PPC::BI__builtin_divde ||
3080                        BuiltinID == PPC::BI__builtin_divdeu;
3081 
3082   if (Is64BitBltin && !IsTarget64Bit)
3083     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3084            << TheCall->getSourceRange();
3085 
3086   if ((IsBltinExtDiv && !TI.hasFeature("extdiv")) ||
3087       (BuiltinID == PPC::BI__builtin_bpermd && !TI.hasFeature("bpermd")))
3088     return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3089            << TheCall->getSourceRange();
3090 
3091   auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
3092     if (!TI.hasFeature("vsx"))
3093       return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3094              << TheCall->getSourceRange();
3095     return false;
3096   };
3097 
3098   switch (BuiltinID) {
3099   default: return false;
3100   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3101   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3102     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3103            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3104   case PPC::BI__builtin_altivec_dss:
3105     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3106   case PPC::BI__builtin_tbegin:
3107   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3108   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3109   case PPC::BI__builtin_tabortwc:
3110   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3111   case PPC::BI__builtin_tabortwci:
3112   case PPC::BI__builtin_tabortdci:
3113     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3114            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3115   case PPC::BI__builtin_altivec_dst:
3116   case PPC::BI__builtin_altivec_dstt:
3117   case PPC::BI__builtin_altivec_dstst:
3118   case PPC::BI__builtin_altivec_dststt:
3119     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3120   case PPC::BI__builtin_vsx_xxpermdi:
3121   case PPC::BI__builtin_vsx_xxsldwi:
3122     return SemaBuiltinVSX(TheCall);
3123   case PPC::BI__builtin_unpack_vector_int128:
3124     return SemaVSXCheck(TheCall) ||
3125            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3126   case PPC::BI__builtin_pack_vector_int128:
3127     return SemaVSXCheck(TheCall);
3128   case PPC::BI__builtin_altivec_vgnb:
3129      return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7);
3130   case PPC::BI__builtin_vsx_xxeval:
3131      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255);
3132   case PPC::BI__builtin_altivec_vsldbi:
3133      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3134   case PPC::BI__builtin_altivec_vsrdbi:
3135      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3136   case PPC::BI__builtin_vsx_xxpermx:
3137      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7);
3138   }
3139   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3140 }
3141 
3142 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
3143                                           CallExpr *TheCall) {
3144   // position of memory order and scope arguments in the builtin
3145   unsigned OrderIndex, ScopeIndex;
3146   switch (BuiltinID) {
3147   case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
3148   case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
3149   case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
3150   case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
3151     OrderIndex = 2;
3152     ScopeIndex = 3;
3153     break;
3154   case AMDGPU::BI__builtin_amdgcn_fence:
3155     OrderIndex = 0;
3156     ScopeIndex = 1;
3157     break;
3158   default:
3159     return false;
3160   }
3161 
3162   ExprResult Arg = TheCall->getArg(OrderIndex);
3163   auto ArgExpr = Arg.get();
3164   Expr::EvalResult ArgResult;
3165 
3166   if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
3167     return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
3168            << ArgExpr->getType();
3169   int ord = ArgResult.Val.getInt().getZExtValue();
3170 
3171   // Check valididty of memory ordering as per C11 / C++11's memody model.
3172   switch (static_cast<llvm::AtomicOrderingCABI>(ord)) {
3173   case llvm::AtomicOrderingCABI::acquire:
3174   case llvm::AtomicOrderingCABI::release:
3175   case llvm::AtomicOrderingCABI::acq_rel:
3176   case llvm::AtomicOrderingCABI::seq_cst:
3177     break;
3178   default: {
3179     return Diag(ArgExpr->getBeginLoc(),
3180                 diag::warn_atomic_op_has_invalid_memory_order)
3181            << ArgExpr->getSourceRange();
3182   }
3183   }
3184 
3185   Arg = TheCall->getArg(ScopeIndex);
3186   ArgExpr = Arg.get();
3187   Expr::EvalResult ArgResult1;
3188   // Check that sync scope is a constant literal
3189   if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Expr::EvaluateForCodeGen,
3190                                        Context))
3191     return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
3192            << ArgExpr->getType();
3193 
3194   return false;
3195 }
3196 
3197 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3198                                            CallExpr *TheCall) {
3199   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3200     Expr *Arg = TheCall->getArg(0);
3201     llvm::APSInt AbortCode(32);
3202     if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
3203         AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
3204       return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3205              << Arg->getSourceRange();
3206   }
3207 
3208   // For intrinsics which take an immediate value as part of the instruction,
3209   // range check them here.
3210   unsigned i = 0, l = 0, u = 0;
3211   switch (BuiltinID) {
3212   default: return false;
3213   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3214   case SystemZ::BI__builtin_s390_verimb:
3215   case SystemZ::BI__builtin_s390_verimh:
3216   case SystemZ::BI__builtin_s390_verimf:
3217   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3218   case SystemZ::BI__builtin_s390_vfaeb:
3219   case SystemZ::BI__builtin_s390_vfaeh:
3220   case SystemZ::BI__builtin_s390_vfaef:
3221   case SystemZ::BI__builtin_s390_vfaebs:
3222   case SystemZ::BI__builtin_s390_vfaehs:
3223   case SystemZ::BI__builtin_s390_vfaefs:
3224   case SystemZ::BI__builtin_s390_vfaezb:
3225   case SystemZ::BI__builtin_s390_vfaezh:
3226   case SystemZ::BI__builtin_s390_vfaezf:
3227   case SystemZ::BI__builtin_s390_vfaezbs:
3228   case SystemZ::BI__builtin_s390_vfaezhs:
3229   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3230   case SystemZ::BI__builtin_s390_vfisb:
3231   case SystemZ::BI__builtin_s390_vfidb:
3232     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3233            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3234   case SystemZ::BI__builtin_s390_vftcisb:
3235   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3236   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3237   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3238   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3239   case SystemZ::BI__builtin_s390_vstrcb:
3240   case SystemZ::BI__builtin_s390_vstrch:
3241   case SystemZ::BI__builtin_s390_vstrcf:
3242   case SystemZ::BI__builtin_s390_vstrczb:
3243   case SystemZ::BI__builtin_s390_vstrczh:
3244   case SystemZ::BI__builtin_s390_vstrczf:
3245   case SystemZ::BI__builtin_s390_vstrcbs:
3246   case SystemZ::BI__builtin_s390_vstrchs:
3247   case SystemZ::BI__builtin_s390_vstrcfs:
3248   case SystemZ::BI__builtin_s390_vstrczbs:
3249   case SystemZ::BI__builtin_s390_vstrczhs:
3250   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3251   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3252   case SystemZ::BI__builtin_s390_vfminsb:
3253   case SystemZ::BI__builtin_s390_vfmaxsb:
3254   case SystemZ::BI__builtin_s390_vfmindb:
3255   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3256   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
3257   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
3258   }
3259   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3260 }
3261 
3262 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3263 /// This checks that the target supports __builtin_cpu_supports and
3264 /// that the string argument is constant and valid.
3265 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
3266                                    CallExpr *TheCall) {
3267   Expr *Arg = TheCall->getArg(0);
3268 
3269   // Check if the argument is a string literal.
3270   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3271     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3272            << Arg->getSourceRange();
3273 
3274   // Check the contents of the string.
3275   StringRef Feature =
3276       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3277   if (!TI.validateCpuSupports(Feature))
3278     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3279            << Arg->getSourceRange();
3280   return false;
3281 }
3282 
3283 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3284 /// This checks that the target supports __builtin_cpu_is and
3285 /// that the string argument is constant and valid.
3286 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
3287   Expr *Arg = TheCall->getArg(0);
3288 
3289   // Check if the argument is a string literal.
3290   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3291     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3292            << Arg->getSourceRange();
3293 
3294   // Check the contents of the string.
3295   StringRef Feature =
3296       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3297   if (!TI.validateCpuIs(Feature))
3298     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3299            << Arg->getSourceRange();
3300   return false;
3301 }
3302 
3303 // Check if the rounding mode is legal.
3304 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3305   // Indicates if this instruction has rounding control or just SAE.
3306   bool HasRC = false;
3307 
3308   unsigned ArgNum = 0;
3309   switch (BuiltinID) {
3310   default:
3311     return false;
3312   case X86::BI__builtin_ia32_vcvttsd2si32:
3313   case X86::BI__builtin_ia32_vcvttsd2si64:
3314   case X86::BI__builtin_ia32_vcvttsd2usi32:
3315   case X86::BI__builtin_ia32_vcvttsd2usi64:
3316   case X86::BI__builtin_ia32_vcvttss2si32:
3317   case X86::BI__builtin_ia32_vcvttss2si64:
3318   case X86::BI__builtin_ia32_vcvttss2usi32:
3319   case X86::BI__builtin_ia32_vcvttss2usi64:
3320     ArgNum = 1;
3321     break;
3322   case X86::BI__builtin_ia32_maxpd512:
3323   case X86::BI__builtin_ia32_maxps512:
3324   case X86::BI__builtin_ia32_minpd512:
3325   case X86::BI__builtin_ia32_minps512:
3326     ArgNum = 2;
3327     break;
3328   case X86::BI__builtin_ia32_cvtps2pd512_mask:
3329   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3330   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3331   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3332   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3333   case X86::BI__builtin_ia32_cvttps2dq512_mask:
3334   case X86::BI__builtin_ia32_cvttps2qq512_mask:
3335   case X86::BI__builtin_ia32_cvttps2udq512_mask:
3336   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3337   case X86::BI__builtin_ia32_exp2pd_mask:
3338   case X86::BI__builtin_ia32_exp2ps_mask:
3339   case X86::BI__builtin_ia32_getexppd512_mask:
3340   case X86::BI__builtin_ia32_getexpps512_mask:
3341   case X86::BI__builtin_ia32_rcp28pd_mask:
3342   case X86::BI__builtin_ia32_rcp28ps_mask:
3343   case X86::BI__builtin_ia32_rsqrt28pd_mask:
3344   case X86::BI__builtin_ia32_rsqrt28ps_mask:
3345   case X86::BI__builtin_ia32_vcomisd:
3346   case X86::BI__builtin_ia32_vcomiss:
3347   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3348     ArgNum = 3;
3349     break;
3350   case X86::BI__builtin_ia32_cmppd512_mask:
3351   case X86::BI__builtin_ia32_cmpps512_mask:
3352   case X86::BI__builtin_ia32_cmpsd_mask:
3353   case X86::BI__builtin_ia32_cmpss_mask:
3354   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3355   case X86::BI__builtin_ia32_getexpsd128_round_mask:
3356   case X86::BI__builtin_ia32_getexpss128_round_mask:
3357   case X86::BI__builtin_ia32_getmantpd512_mask:
3358   case X86::BI__builtin_ia32_getmantps512_mask:
3359   case X86::BI__builtin_ia32_maxsd_round_mask:
3360   case X86::BI__builtin_ia32_maxss_round_mask:
3361   case X86::BI__builtin_ia32_minsd_round_mask:
3362   case X86::BI__builtin_ia32_minss_round_mask:
3363   case X86::BI__builtin_ia32_rcp28sd_round_mask:
3364   case X86::BI__builtin_ia32_rcp28ss_round_mask:
3365   case X86::BI__builtin_ia32_reducepd512_mask:
3366   case X86::BI__builtin_ia32_reduceps512_mask:
3367   case X86::BI__builtin_ia32_rndscalepd_mask:
3368   case X86::BI__builtin_ia32_rndscaleps_mask:
3369   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3370   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3371     ArgNum = 4;
3372     break;
3373   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3374   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3375   case X86::BI__builtin_ia32_fixupimmps512_mask:
3376   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3377   case X86::BI__builtin_ia32_fixupimmsd_mask:
3378   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3379   case X86::BI__builtin_ia32_fixupimmss_mask:
3380   case X86::BI__builtin_ia32_fixupimmss_maskz:
3381   case X86::BI__builtin_ia32_getmantsd_round_mask:
3382   case X86::BI__builtin_ia32_getmantss_round_mask:
3383   case X86::BI__builtin_ia32_rangepd512_mask:
3384   case X86::BI__builtin_ia32_rangeps512_mask:
3385   case X86::BI__builtin_ia32_rangesd128_round_mask:
3386   case X86::BI__builtin_ia32_rangess128_round_mask:
3387   case X86::BI__builtin_ia32_reducesd_mask:
3388   case X86::BI__builtin_ia32_reducess_mask:
3389   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3390   case X86::BI__builtin_ia32_rndscaless_round_mask:
3391     ArgNum = 5;
3392     break;
3393   case X86::BI__builtin_ia32_vcvtsd2si64:
3394   case X86::BI__builtin_ia32_vcvtsd2si32:
3395   case X86::BI__builtin_ia32_vcvtsd2usi32:
3396   case X86::BI__builtin_ia32_vcvtsd2usi64:
3397   case X86::BI__builtin_ia32_vcvtss2si32:
3398   case X86::BI__builtin_ia32_vcvtss2si64:
3399   case X86::BI__builtin_ia32_vcvtss2usi32:
3400   case X86::BI__builtin_ia32_vcvtss2usi64:
3401   case X86::BI__builtin_ia32_sqrtpd512:
3402   case X86::BI__builtin_ia32_sqrtps512:
3403     ArgNum = 1;
3404     HasRC = true;
3405     break;
3406   case X86::BI__builtin_ia32_addpd512:
3407   case X86::BI__builtin_ia32_addps512:
3408   case X86::BI__builtin_ia32_divpd512:
3409   case X86::BI__builtin_ia32_divps512:
3410   case X86::BI__builtin_ia32_mulpd512:
3411   case X86::BI__builtin_ia32_mulps512:
3412   case X86::BI__builtin_ia32_subpd512:
3413   case X86::BI__builtin_ia32_subps512:
3414   case X86::BI__builtin_ia32_cvtsi2sd64:
3415   case X86::BI__builtin_ia32_cvtsi2ss32:
3416   case X86::BI__builtin_ia32_cvtsi2ss64:
3417   case X86::BI__builtin_ia32_cvtusi2sd64:
3418   case X86::BI__builtin_ia32_cvtusi2ss32:
3419   case X86::BI__builtin_ia32_cvtusi2ss64:
3420     ArgNum = 2;
3421     HasRC = true;
3422     break;
3423   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3424   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3425   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
3426   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
3427   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3428   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
3429   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3430   case X86::BI__builtin_ia32_cvtps2dq512_mask:
3431   case X86::BI__builtin_ia32_cvtps2qq512_mask:
3432   case X86::BI__builtin_ia32_cvtps2udq512_mask:
3433   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3434   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3435   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3436   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3437   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3438     ArgNum = 3;
3439     HasRC = true;
3440     break;
3441   case X86::BI__builtin_ia32_addss_round_mask:
3442   case X86::BI__builtin_ia32_addsd_round_mask:
3443   case X86::BI__builtin_ia32_divss_round_mask:
3444   case X86::BI__builtin_ia32_divsd_round_mask:
3445   case X86::BI__builtin_ia32_mulss_round_mask:
3446   case X86::BI__builtin_ia32_mulsd_round_mask:
3447   case X86::BI__builtin_ia32_subss_round_mask:
3448   case X86::BI__builtin_ia32_subsd_round_mask:
3449   case X86::BI__builtin_ia32_scalefpd512_mask:
3450   case X86::BI__builtin_ia32_scalefps512_mask:
3451   case X86::BI__builtin_ia32_scalefsd_round_mask:
3452   case X86::BI__builtin_ia32_scalefss_round_mask:
3453   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3454   case X86::BI__builtin_ia32_sqrtsd_round_mask:
3455   case X86::BI__builtin_ia32_sqrtss_round_mask:
3456   case X86::BI__builtin_ia32_vfmaddsd3_mask:
3457   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3458   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
3459   case X86::BI__builtin_ia32_vfmaddss3_mask:
3460   case X86::BI__builtin_ia32_vfmaddss3_maskz:
3461   case X86::BI__builtin_ia32_vfmaddss3_mask3:
3462   case X86::BI__builtin_ia32_vfmaddpd512_mask:
3463   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
3464   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
3465   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
3466   case X86::BI__builtin_ia32_vfmaddps512_mask:
3467   case X86::BI__builtin_ia32_vfmaddps512_maskz:
3468   case X86::BI__builtin_ia32_vfmaddps512_mask3:
3469   case X86::BI__builtin_ia32_vfmsubps512_mask3:
3470   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
3471   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
3472   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
3473   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
3474   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
3475   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
3476   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
3477   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
3478     ArgNum = 4;
3479     HasRC = true;
3480     break;
3481   }
3482 
3483   llvm::APSInt Result;
3484 
3485   // We can't check the value of a dependent argument.
3486   Expr *Arg = TheCall->getArg(ArgNum);
3487   if (Arg->isTypeDependent() || Arg->isValueDependent())
3488     return false;
3489 
3490   // Check constant-ness first.
3491   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3492     return true;
3493 
3494   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
3495   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
3496   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
3497   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
3498   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
3499       Result == 8/*ROUND_NO_EXC*/ ||
3500       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
3501       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
3502     return false;
3503 
3504   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
3505          << Arg->getSourceRange();
3506 }
3507 
3508 // Check if the gather/scatter scale is legal.
3509 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
3510                                              CallExpr *TheCall) {
3511   unsigned ArgNum = 0;
3512   switch (BuiltinID) {
3513   default:
3514     return false;
3515   case X86::BI__builtin_ia32_gatherpfdpd:
3516   case X86::BI__builtin_ia32_gatherpfdps:
3517   case X86::BI__builtin_ia32_gatherpfqpd:
3518   case X86::BI__builtin_ia32_gatherpfqps:
3519   case X86::BI__builtin_ia32_scatterpfdpd:
3520   case X86::BI__builtin_ia32_scatterpfdps:
3521   case X86::BI__builtin_ia32_scatterpfqpd:
3522   case X86::BI__builtin_ia32_scatterpfqps:
3523     ArgNum = 3;
3524     break;
3525   case X86::BI__builtin_ia32_gatherd_pd:
3526   case X86::BI__builtin_ia32_gatherd_pd256:
3527   case X86::BI__builtin_ia32_gatherq_pd:
3528   case X86::BI__builtin_ia32_gatherq_pd256:
3529   case X86::BI__builtin_ia32_gatherd_ps:
3530   case X86::BI__builtin_ia32_gatherd_ps256:
3531   case X86::BI__builtin_ia32_gatherq_ps:
3532   case X86::BI__builtin_ia32_gatherq_ps256:
3533   case X86::BI__builtin_ia32_gatherd_q:
3534   case X86::BI__builtin_ia32_gatherd_q256:
3535   case X86::BI__builtin_ia32_gatherq_q:
3536   case X86::BI__builtin_ia32_gatherq_q256:
3537   case X86::BI__builtin_ia32_gatherd_d:
3538   case X86::BI__builtin_ia32_gatherd_d256:
3539   case X86::BI__builtin_ia32_gatherq_d:
3540   case X86::BI__builtin_ia32_gatherq_d256:
3541   case X86::BI__builtin_ia32_gather3div2df:
3542   case X86::BI__builtin_ia32_gather3div2di:
3543   case X86::BI__builtin_ia32_gather3div4df:
3544   case X86::BI__builtin_ia32_gather3div4di:
3545   case X86::BI__builtin_ia32_gather3div4sf:
3546   case X86::BI__builtin_ia32_gather3div4si:
3547   case X86::BI__builtin_ia32_gather3div8sf:
3548   case X86::BI__builtin_ia32_gather3div8si:
3549   case X86::BI__builtin_ia32_gather3siv2df:
3550   case X86::BI__builtin_ia32_gather3siv2di:
3551   case X86::BI__builtin_ia32_gather3siv4df:
3552   case X86::BI__builtin_ia32_gather3siv4di:
3553   case X86::BI__builtin_ia32_gather3siv4sf:
3554   case X86::BI__builtin_ia32_gather3siv4si:
3555   case X86::BI__builtin_ia32_gather3siv8sf:
3556   case X86::BI__builtin_ia32_gather3siv8si:
3557   case X86::BI__builtin_ia32_gathersiv8df:
3558   case X86::BI__builtin_ia32_gathersiv16sf:
3559   case X86::BI__builtin_ia32_gatherdiv8df:
3560   case X86::BI__builtin_ia32_gatherdiv16sf:
3561   case X86::BI__builtin_ia32_gathersiv8di:
3562   case X86::BI__builtin_ia32_gathersiv16si:
3563   case X86::BI__builtin_ia32_gatherdiv8di:
3564   case X86::BI__builtin_ia32_gatherdiv16si:
3565   case X86::BI__builtin_ia32_scatterdiv2df:
3566   case X86::BI__builtin_ia32_scatterdiv2di:
3567   case X86::BI__builtin_ia32_scatterdiv4df:
3568   case X86::BI__builtin_ia32_scatterdiv4di:
3569   case X86::BI__builtin_ia32_scatterdiv4sf:
3570   case X86::BI__builtin_ia32_scatterdiv4si:
3571   case X86::BI__builtin_ia32_scatterdiv8sf:
3572   case X86::BI__builtin_ia32_scatterdiv8si:
3573   case X86::BI__builtin_ia32_scattersiv2df:
3574   case X86::BI__builtin_ia32_scattersiv2di:
3575   case X86::BI__builtin_ia32_scattersiv4df:
3576   case X86::BI__builtin_ia32_scattersiv4di:
3577   case X86::BI__builtin_ia32_scattersiv4sf:
3578   case X86::BI__builtin_ia32_scattersiv4si:
3579   case X86::BI__builtin_ia32_scattersiv8sf:
3580   case X86::BI__builtin_ia32_scattersiv8si:
3581   case X86::BI__builtin_ia32_scattersiv8df:
3582   case X86::BI__builtin_ia32_scattersiv16sf:
3583   case X86::BI__builtin_ia32_scatterdiv8df:
3584   case X86::BI__builtin_ia32_scatterdiv16sf:
3585   case X86::BI__builtin_ia32_scattersiv8di:
3586   case X86::BI__builtin_ia32_scattersiv16si:
3587   case X86::BI__builtin_ia32_scatterdiv8di:
3588   case X86::BI__builtin_ia32_scatterdiv16si:
3589     ArgNum = 4;
3590     break;
3591   }
3592 
3593   llvm::APSInt Result;
3594 
3595   // We can't check the value of a dependent argument.
3596   Expr *Arg = TheCall->getArg(ArgNum);
3597   if (Arg->isTypeDependent() || Arg->isValueDependent())
3598     return false;
3599 
3600   // Check constant-ness first.
3601   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3602     return true;
3603 
3604   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
3605     return false;
3606 
3607   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
3608          << Arg->getSourceRange();
3609 }
3610 
3611 enum { TileRegLow = 0, TileRegHigh = 7 };
3612 
3613 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
3614                                     ArrayRef<int> ArgNums) {
3615   for (int ArgNum : ArgNums) {
3616     if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
3617       return true;
3618   }
3619   return false;
3620 }
3621 
3622 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, int ArgNum) {
3623   return SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh);
3624 }
3625 
3626 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
3627                                         ArrayRef<int> ArgNums) {
3628   // Because the max number of tile register is TileRegHigh + 1, so here we use
3629   // each bit to represent the usage of them in bitset.
3630   std::bitset<TileRegHigh + 1> ArgValues;
3631   for (int ArgNum : ArgNums) {
3632     llvm::APSInt Arg;
3633     SemaBuiltinConstantArg(TheCall, ArgNum, Arg);
3634     int ArgExtValue = Arg.getExtValue();
3635     assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) &&
3636            "Incorrect tile register num.");
3637     if (ArgValues.test(ArgExtValue))
3638       return Diag(TheCall->getBeginLoc(),
3639                   diag::err_x86_builtin_tile_arg_duplicate)
3640              << TheCall->getArg(ArgNum)->getSourceRange();
3641     ArgValues.set(ArgExtValue);
3642   }
3643   return false;
3644 }
3645 
3646 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
3647                                                 ArrayRef<int> ArgNums) {
3648   return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
3649          CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
3650 }
3651 
3652 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
3653   switch (BuiltinID) {
3654   default:
3655     return false;
3656   case X86::BI__builtin_ia32_tileloadd64:
3657   case X86::BI__builtin_ia32_tileloaddt164:
3658   case X86::BI__builtin_ia32_tilestored64:
3659   case X86::BI__builtin_ia32_tilezero:
3660     return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
3661   case X86::BI__builtin_ia32_tdpbssd:
3662   case X86::BI__builtin_ia32_tdpbsud:
3663   case X86::BI__builtin_ia32_tdpbusd:
3664   case X86::BI__builtin_ia32_tdpbuud:
3665   case X86::BI__builtin_ia32_tdpbf16ps:
3666     return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
3667   }
3668 }
3669 static bool isX86_32Builtin(unsigned BuiltinID) {
3670   // These builtins only work on x86-32 targets.
3671   switch (BuiltinID) {
3672   case X86::BI__builtin_ia32_readeflags_u32:
3673   case X86::BI__builtin_ia32_writeeflags_u32:
3674     return true;
3675   }
3676 
3677   return false;
3678 }
3679 
3680 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3681                                        CallExpr *TheCall) {
3682   if (BuiltinID == X86::BI__builtin_cpu_supports)
3683     return SemaBuiltinCpuSupports(*this, TI, TheCall);
3684 
3685   if (BuiltinID == X86::BI__builtin_cpu_is)
3686     return SemaBuiltinCpuIs(*this, TI, TheCall);
3687 
3688   // Check for 32-bit only builtins on a 64-bit target.
3689   const llvm::Triple &TT = TI.getTriple();
3690   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
3691     return Diag(TheCall->getCallee()->getBeginLoc(),
3692                 diag::err_32_bit_builtin_64_bit_tgt);
3693 
3694   // If the intrinsic has rounding or SAE make sure its valid.
3695   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
3696     return true;
3697 
3698   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
3699   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
3700     return true;
3701 
3702   // If the intrinsic has a tile arguments, make sure they are valid.
3703   if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
3704     return true;
3705 
3706   // For intrinsics which take an immediate value as part of the instruction,
3707   // range check them here.
3708   int i = 0, l = 0, u = 0;
3709   switch (BuiltinID) {
3710   default:
3711     return false;
3712   case X86::BI__builtin_ia32_vec_ext_v2si:
3713   case X86::BI__builtin_ia32_vec_ext_v2di:
3714   case X86::BI__builtin_ia32_vextractf128_pd256:
3715   case X86::BI__builtin_ia32_vextractf128_ps256:
3716   case X86::BI__builtin_ia32_vextractf128_si256:
3717   case X86::BI__builtin_ia32_extract128i256:
3718   case X86::BI__builtin_ia32_extractf64x4_mask:
3719   case X86::BI__builtin_ia32_extracti64x4_mask:
3720   case X86::BI__builtin_ia32_extractf32x8_mask:
3721   case X86::BI__builtin_ia32_extracti32x8_mask:
3722   case X86::BI__builtin_ia32_extractf64x2_256_mask:
3723   case X86::BI__builtin_ia32_extracti64x2_256_mask:
3724   case X86::BI__builtin_ia32_extractf32x4_256_mask:
3725   case X86::BI__builtin_ia32_extracti32x4_256_mask:
3726     i = 1; l = 0; u = 1;
3727     break;
3728   case X86::BI__builtin_ia32_vec_set_v2di:
3729   case X86::BI__builtin_ia32_vinsertf128_pd256:
3730   case X86::BI__builtin_ia32_vinsertf128_ps256:
3731   case X86::BI__builtin_ia32_vinsertf128_si256:
3732   case X86::BI__builtin_ia32_insert128i256:
3733   case X86::BI__builtin_ia32_insertf32x8:
3734   case X86::BI__builtin_ia32_inserti32x8:
3735   case X86::BI__builtin_ia32_insertf64x4:
3736   case X86::BI__builtin_ia32_inserti64x4:
3737   case X86::BI__builtin_ia32_insertf64x2_256:
3738   case X86::BI__builtin_ia32_inserti64x2_256:
3739   case X86::BI__builtin_ia32_insertf32x4_256:
3740   case X86::BI__builtin_ia32_inserti32x4_256:
3741     i = 2; l = 0; u = 1;
3742     break;
3743   case X86::BI__builtin_ia32_vpermilpd:
3744   case X86::BI__builtin_ia32_vec_ext_v4hi:
3745   case X86::BI__builtin_ia32_vec_ext_v4si:
3746   case X86::BI__builtin_ia32_vec_ext_v4sf:
3747   case X86::BI__builtin_ia32_vec_ext_v4di:
3748   case X86::BI__builtin_ia32_extractf32x4_mask:
3749   case X86::BI__builtin_ia32_extracti32x4_mask:
3750   case X86::BI__builtin_ia32_extractf64x2_512_mask:
3751   case X86::BI__builtin_ia32_extracti64x2_512_mask:
3752     i = 1; l = 0; u = 3;
3753     break;
3754   case X86::BI_mm_prefetch:
3755   case X86::BI__builtin_ia32_vec_ext_v8hi:
3756   case X86::BI__builtin_ia32_vec_ext_v8si:
3757     i = 1; l = 0; u = 7;
3758     break;
3759   case X86::BI__builtin_ia32_sha1rnds4:
3760   case X86::BI__builtin_ia32_blendpd:
3761   case X86::BI__builtin_ia32_shufpd:
3762   case X86::BI__builtin_ia32_vec_set_v4hi:
3763   case X86::BI__builtin_ia32_vec_set_v4si:
3764   case X86::BI__builtin_ia32_vec_set_v4di:
3765   case X86::BI__builtin_ia32_shuf_f32x4_256:
3766   case X86::BI__builtin_ia32_shuf_f64x2_256:
3767   case X86::BI__builtin_ia32_shuf_i32x4_256:
3768   case X86::BI__builtin_ia32_shuf_i64x2_256:
3769   case X86::BI__builtin_ia32_insertf64x2_512:
3770   case X86::BI__builtin_ia32_inserti64x2_512:
3771   case X86::BI__builtin_ia32_insertf32x4:
3772   case X86::BI__builtin_ia32_inserti32x4:
3773     i = 2; l = 0; u = 3;
3774     break;
3775   case X86::BI__builtin_ia32_vpermil2pd:
3776   case X86::BI__builtin_ia32_vpermil2pd256:
3777   case X86::BI__builtin_ia32_vpermil2ps:
3778   case X86::BI__builtin_ia32_vpermil2ps256:
3779     i = 3; l = 0; u = 3;
3780     break;
3781   case X86::BI__builtin_ia32_cmpb128_mask:
3782   case X86::BI__builtin_ia32_cmpw128_mask:
3783   case X86::BI__builtin_ia32_cmpd128_mask:
3784   case X86::BI__builtin_ia32_cmpq128_mask:
3785   case X86::BI__builtin_ia32_cmpb256_mask:
3786   case X86::BI__builtin_ia32_cmpw256_mask:
3787   case X86::BI__builtin_ia32_cmpd256_mask:
3788   case X86::BI__builtin_ia32_cmpq256_mask:
3789   case X86::BI__builtin_ia32_cmpb512_mask:
3790   case X86::BI__builtin_ia32_cmpw512_mask:
3791   case X86::BI__builtin_ia32_cmpd512_mask:
3792   case X86::BI__builtin_ia32_cmpq512_mask:
3793   case X86::BI__builtin_ia32_ucmpb128_mask:
3794   case X86::BI__builtin_ia32_ucmpw128_mask:
3795   case X86::BI__builtin_ia32_ucmpd128_mask:
3796   case X86::BI__builtin_ia32_ucmpq128_mask:
3797   case X86::BI__builtin_ia32_ucmpb256_mask:
3798   case X86::BI__builtin_ia32_ucmpw256_mask:
3799   case X86::BI__builtin_ia32_ucmpd256_mask:
3800   case X86::BI__builtin_ia32_ucmpq256_mask:
3801   case X86::BI__builtin_ia32_ucmpb512_mask:
3802   case X86::BI__builtin_ia32_ucmpw512_mask:
3803   case X86::BI__builtin_ia32_ucmpd512_mask:
3804   case X86::BI__builtin_ia32_ucmpq512_mask:
3805   case X86::BI__builtin_ia32_vpcomub:
3806   case X86::BI__builtin_ia32_vpcomuw:
3807   case X86::BI__builtin_ia32_vpcomud:
3808   case X86::BI__builtin_ia32_vpcomuq:
3809   case X86::BI__builtin_ia32_vpcomb:
3810   case X86::BI__builtin_ia32_vpcomw:
3811   case X86::BI__builtin_ia32_vpcomd:
3812   case X86::BI__builtin_ia32_vpcomq:
3813   case X86::BI__builtin_ia32_vec_set_v8hi:
3814   case X86::BI__builtin_ia32_vec_set_v8si:
3815     i = 2; l = 0; u = 7;
3816     break;
3817   case X86::BI__builtin_ia32_vpermilpd256:
3818   case X86::BI__builtin_ia32_roundps:
3819   case X86::BI__builtin_ia32_roundpd:
3820   case X86::BI__builtin_ia32_roundps256:
3821   case X86::BI__builtin_ia32_roundpd256:
3822   case X86::BI__builtin_ia32_getmantpd128_mask:
3823   case X86::BI__builtin_ia32_getmantpd256_mask:
3824   case X86::BI__builtin_ia32_getmantps128_mask:
3825   case X86::BI__builtin_ia32_getmantps256_mask:
3826   case X86::BI__builtin_ia32_getmantpd512_mask:
3827   case X86::BI__builtin_ia32_getmantps512_mask:
3828   case X86::BI__builtin_ia32_vec_ext_v16qi:
3829   case X86::BI__builtin_ia32_vec_ext_v16hi:
3830     i = 1; l = 0; u = 15;
3831     break;
3832   case X86::BI__builtin_ia32_pblendd128:
3833   case X86::BI__builtin_ia32_blendps:
3834   case X86::BI__builtin_ia32_blendpd256:
3835   case X86::BI__builtin_ia32_shufpd256:
3836   case X86::BI__builtin_ia32_roundss:
3837   case X86::BI__builtin_ia32_roundsd:
3838   case X86::BI__builtin_ia32_rangepd128_mask:
3839   case X86::BI__builtin_ia32_rangepd256_mask:
3840   case X86::BI__builtin_ia32_rangepd512_mask:
3841   case X86::BI__builtin_ia32_rangeps128_mask:
3842   case X86::BI__builtin_ia32_rangeps256_mask:
3843   case X86::BI__builtin_ia32_rangeps512_mask:
3844   case X86::BI__builtin_ia32_getmantsd_round_mask:
3845   case X86::BI__builtin_ia32_getmantss_round_mask:
3846   case X86::BI__builtin_ia32_vec_set_v16qi:
3847   case X86::BI__builtin_ia32_vec_set_v16hi:
3848     i = 2; l = 0; u = 15;
3849     break;
3850   case X86::BI__builtin_ia32_vec_ext_v32qi:
3851     i = 1; l = 0; u = 31;
3852     break;
3853   case X86::BI__builtin_ia32_cmpps:
3854   case X86::BI__builtin_ia32_cmpss:
3855   case X86::BI__builtin_ia32_cmppd:
3856   case X86::BI__builtin_ia32_cmpsd:
3857   case X86::BI__builtin_ia32_cmpps256:
3858   case X86::BI__builtin_ia32_cmppd256:
3859   case X86::BI__builtin_ia32_cmpps128_mask:
3860   case X86::BI__builtin_ia32_cmppd128_mask:
3861   case X86::BI__builtin_ia32_cmpps256_mask:
3862   case X86::BI__builtin_ia32_cmppd256_mask:
3863   case X86::BI__builtin_ia32_cmpps512_mask:
3864   case X86::BI__builtin_ia32_cmppd512_mask:
3865   case X86::BI__builtin_ia32_cmpsd_mask:
3866   case X86::BI__builtin_ia32_cmpss_mask:
3867   case X86::BI__builtin_ia32_vec_set_v32qi:
3868     i = 2; l = 0; u = 31;
3869     break;
3870   case X86::BI__builtin_ia32_permdf256:
3871   case X86::BI__builtin_ia32_permdi256:
3872   case X86::BI__builtin_ia32_permdf512:
3873   case X86::BI__builtin_ia32_permdi512:
3874   case X86::BI__builtin_ia32_vpermilps:
3875   case X86::BI__builtin_ia32_vpermilps256:
3876   case X86::BI__builtin_ia32_vpermilpd512:
3877   case X86::BI__builtin_ia32_vpermilps512:
3878   case X86::BI__builtin_ia32_pshufd:
3879   case X86::BI__builtin_ia32_pshufd256:
3880   case X86::BI__builtin_ia32_pshufd512:
3881   case X86::BI__builtin_ia32_pshufhw:
3882   case X86::BI__builtin_ia32_pshufhw256:
3883   case X86::BI__builtin_ia32_pshufhw512:
3884   case X86::BI__builtin_ia32_pshuflw:
3885   case X86::BI__builtin_ia32_pshuflw256:
3886   case X86::BI__builtin_ia32_pshuflw512:
3887   case X86::BI__builtin_ia32_vcvtps2ph:
3888   case X86::BI__builtin_ia32_vcvtps2ph_mask:
3889   case X86::BI__builtin_ia32_vcvtps2ph256:
3890   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
3891   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
3892   case X86::BI__builtin_ia32_rndscaleps_128_mask:
3893   case X86::BI__builtin_ia32_rndscalepd_128_mask:
3894   case X86::BI__builtin_ia32_rndscaleps_256_mask:
3895   case X86::BI__builtin_ia32_rndscalepd_256_mask:
3896   case X86::BI__builtin_ia32_rndscaleps_mask:
3897   case X86::BI__builtin_ia32_rndscalepd_mask:
3898   case X86::BI__builtin_ia32_reducepd128_mask:
3899   case X86::BI__builtin_ia32_reducepd256_mask:
3900   case X86::BI__builtin_ia32_reducepd512_mask:
3901   case X86::BI__builtin_ia32_reduceps128_mask:
3902   case X86::BI__builtin_ia32_reduceps256_mask:
3903   case X86::BI__builtin_ia32_reduceps512_mask:
3904   case X86::BI__builtin_ia32_prold512:
3905   case X86::BI__builtin_ia32_prolq512:
3906   case X86::BI__builtin_ia32_prold128:
3907   case X86::BI__builtin_ia32_prold256:
3908   case X86::BI__builtin_ia32_prolq128:
3909   case X86::BI__builtin_ia32_prolq256:
3910   case X86::BI__builtin_ia32_prord512:
3911   case X86::BI__builtin_ia32_prorq512:
3912   case X86::BI__builtin_ia32_prord128:
3913   case X86::BI__builtin_ia32_prord256:
3914   case X86::BI__builtin_ia32_prorq128:
3915   case X86::BI__builtin_ia32_prorq256:
3916   case X86::BI__builtin_ia32_fpclasspd128_mask:
3917   case X86::BI__builtin_ia32_fpclasspd256_mask:
3918   case X86::BI__builtin_ia32_fpclassps128_mask:
3919   case X86::BI__builtin_ia32_fpclassps256_mask:
3920   case X86::BI__builtin_ia32_fpclassps512_mask:
3921   case X86::BI__builtin_ia32_fpclasspd512_mask:
3922   case X86::BI__builtin_ia32_fpclasssd_mask:
3923   case X86::BI__builtin_ia32_fpclassss_mask:
3924   case X86::BI__builtin_ia32_pslldqi128_byteshift:
3925   case X86::BI__builtin_ia32_pslldqi256_byteshift:
3926   case X86::BI__builtin_ia32_pslldqi512_byteshift:
3927   case X86::BI__builtin_ia32_psrldqi128_byteshift:
3928   case X86::BI__builtin_ia32_psrldqi256_byteshift:
3929   case X86::BI__builtin_ia32_psrldqi512_byteshift:
3930   case X86::BI__builtin_ia32_kshiftliqi:
3931   case X86::BI__builtin_ia32_kshiftlihi:
3932   case X86::BI__builtin_ia32_kshiftlisi:
3933   case X86::BI__builtin_ia32_kshiftlidi:
3934   case X86::BI__builtin_ia32_kshiftriqi:
3935   case X86::BI__builtin_ia32_kshiftrihi:
3936   case X86::BI__builtin_ia32_kshiftrisi:
3937   case X86::BI__builtin_ia32_kshiftridi:
3938     i = 1; l = 0; u = 255;
3939     break;
3940   case X86::BI__builtin_ia32_vperm2f128_pd256:
3941   case X86::BI__builtin_ia32_vperm2f128_ps256:
3942   case X86::BI__builtin_ia32_vperm2f128_si256:
3943   case X86::BI__builtin_ia32_permti256:
3944   case X86::BI__builtin_ia32_pblendw128:
3945   case X86::BI__builtin_ia32_pblendw256:
3946   case X86::BI__builtin_ia32_blendps256:
3947   case X86::BI__builtin_ia32_pblendd256:
3948   case X86::BI__builtin_ia32_palignr128:
3949   case X86::BI__builtin_ia32_palignr256:
3950   case X86::BI__builtin_ia32_palignr512:
3951   case X86::BI__builtin_ia32_alignq512:
3952   case X86::BI__builtin_ia32_alignd512:
3953   case X86::BI__builtin_ia32_alignd128:
3954   case X86::BI__builtin_ia32_alignd256:
3955   case X86::BI__builtin_ia32_alignq128:
3956   case X86::BI__builtin_ia32_alignq256:
3957   case X86::BI__builtin_ia32_vcomisd:
3958   case X86::BI__builtin_ia32_vcomiss:
3959   case X86::BI__builtin_ia32_shuf_f32x4:
3960   case X86::BI__builtin_ia32_shuf_f64x2:
3961   case X86::BI__builtin_ia32_shuf_i32x4:
3962   case X86::BI__builtin_ia32_shuf_i64x2:
3963   case X86::BI__builtin_ia32_shufpd512:
3964   case X86::BI__builtin_ia32_shufps:
3965   case X86::BI__builtin_ia32_shufps256:
3966   case X86::BI__builtin_ia32_shufps512:
3967   case X86::BI__builtin_ia32_dbpsadbw128:
3968   case X86::BI__builtin_ia32_dbpsadbw256:
3969   case X86::BI__builtin_ia32_dbpsadbw512:
3970   case X86::BI__builtin_ia32_vpshldd128:
3971   case X86::BI__builtin_ia32_vpshldd256:
3972   case X86::BI__builtin_ia32_vpshldd512:
3973   case X86::BI__builtin_ia32_vpshldq128:
3974   case X86::BI__builtin_ia32_vpshldq256:
3975   case X86::BI__builtin_ia32_vpshldq512:
3976   case X86::BI__builtin_ia32_vpshldw128:
3977   case X86::BI__builtin_ia32_vpshldw256:
3978   case X86::BI__builtin_ia32_vpshldw512:
3979   case X86::BI__builtin_ia32_vpshrdd128:
3980   case X86::BI__builtin_ia32_vpshrdd256:
3981   case X86::BI__builtin_ia32_vpshrdd512:
3982   case X86::BI__builtin_ia32_vpshrdq128:
3983   case X86::BI__builtin_ia32_vpshrdq256:
3984   case X86::BI__builtin_ia32_vpshrdq512:
3985   case X86::BI__builtin_ia32_vpshrdw128:
3986   case X86::BI__builtin_ia32_vpshrdw256:
3987   case X86::BI__builtin_ia32_vpshrdw512:
3988     i = 2; l = 0; u = 255;
3989     break;
3990   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3991   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3992   case X86::BI__builtin_ia32_fixupimmps512_mask:
3993   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3994   case X86::BI__builtin_ia32_fixupimmsd_mask:
3995   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3996   case X86::BI__builtin_ia32_fixupimmss_mask:
3997   case X86::BI__builtin_ia32_fixupimmss_maskz:
3998   case X86::BI__builtin_ia32_fixupimmpd128_mask:
3999   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
4000   case X86::BI__builtin_ia32_fixupimmpd256_mask:
4001   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
4002   case X86::BI__builtin_ia32_fixupimmps128_mask:
4003   case X86::BI__builtin_ia32_fixupimmps128_maskz:
4004   case X86::BI__builtin_ia32_fixupimmps256_mask:
4005   case X86::BI__builtin_ia32_fixupimmps256_maskz:
4006   case X86::BI__builtin_ia32_pternlogd512_mask:
4007   case X86::BI__builtin_ia32_pternlogd512_maskz:
4008   case X86::BI__builtin_ia32_pternlogq512_mask:
4009   case X86::BI__builtin_ia32_pternlogq512_maskz:
4010   case X86::BI__builtin_ia32_pternlogd128_mask:
4011   case X86::BI__builtin_ia32_pternlogd128_maskz:
4012   case X86::BI__builtin_ia32_pternlogd256_mask:
4013   case X86::BI__builtin_ia32_pternlogd256_maskz:
4014   case X86::BI__builtin_ia32_pternlogq128_mask:
4015   case X86::BI__builtin_ia32_pternlogq128_maskz:
4016   case X86::BI__builtin_ia32_pternlogq256_mask:
4017   case X86::BI__builtin_ia32_pternlogq256_maskz:
4018     i = 3; l = 0; u = 255;
4019     break;
4020   case X86::BI__builtin_ia32_gatherpfdpd:
4021   case X86::BI__builtin_ia32_gatherpfdps:
4022   case X86::BI__builtin_ia32_gatherpfqpd:
4023   case X86::BI__builtin_ia32_gatherpfqps:
4024   case X86::BI__builtin_ia32_scatterpfdpd:
4025   case X86::BI__builtin_ia32_scatterpfdps:
4026   case X86::BI__builtin_ia32_scatterpfqpd:
4027   case X86::BI__builtin_ia32_scatterpfqps:
4028     i = 4; l = 2; u = 3;
4029     break;
4030   case X86::BI__builtin_ia32_reducesd_mask:
4031   case X86::BI__builtin_ia32_reducess_mask:
4032   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4033   case X86::BI__builtin_ia32_rndscaless_round_mask:
4034     i = 4; l = 0; u = 255;
4035     break;
4036   }
4037 
4038   // Note that we don't force a hard error on the range check here, allowing
4039   // template-generated or macro-generated dead code to potentially have out-of-
4040   // range values. These need to code generate, but don't need to necessarily
4041   // make any sense. We use a warning that defaults to an error.
4042   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
4043 }
4044 
4045 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
4046 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
4047 /// Returns true when the format fits the function and the FormatStringInfo has
4048 /// been populated.
4049 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
4050                                FormatStringInfo *FSI) {
4051   FSI->HasVAListArg = Format->getFirstArg() == 0;
4052   FSI->FormatIdx = Format->getFormatIdx() - 1;
4053   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
4054 
4055   // The way the format attribute works in GCC, the implicit this argument
4056   // of member functions is counted. However, it doesn't appear in our own
4057   // lists, so decrement format_idx in that case.
4058   if (IsCXXMember) {
4059     if(FSI->FormatIdx == 0)
4060       return false;
4061     --FSI->FormatIdx;
4062     if (FSI->FirstDataArg != 0)
4063       --FSI->FirstDataArg;
4064   }
4065   return true;
4066 }
4067 
4068 /// Checks if a the given expression evaluates to null.
4069 ///
4070 /// Returns true if the value evaluates to null.
4071 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4072   // If the expression has non-null type, it doesn't evaluate to null.
4073   if (auto nullability
4074         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
4075     if (*nullability == NullabilityKind::NonNull)
4076       return false;
4077   }
4078 
4079   // As a special case, transparent unions initialized with zero are
4080   // considered null for the purposes of the nonnull attribute.
4081   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
4082     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
4083       if (const CompoundLiteralExpr *CLE =
4084           dyn_cast<CompoundLiteralExpr>(Expr))
4085         if (const InitListExpr *ILE =
4086             dyn_cast<InitListExpr>(CLE->getInitializer()))
4087           Expr = ILE->getInit(0);
4088   }
4089 
4090   bool Result;
4091   return (!Expr->isValueDependent() &&
4092           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
4093           !Result);
4094 }
4095 
4096 static void CheckNonNullArgument(Sema &S,
4097                                  const Expr *ArgExpr,
4098                                  SourceLocation CallSiteLoc) {
4099   if (CheckNonNullExpr(S, ArgExpr))
4100     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4101                           S.PDiag(diag::warn_null_arg)
4102                               << ArgExpr->getSourceRange());
4103 }
4104 
4105 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
4106   FormatStringInfo FSI;
4107   if ((GetFormatStringType(Format) == FST_NSString) &&
4108       getFormatStringInfo(Format, false, &FSI)) {
4109     Idx = FSI.FormatIdx;
4110     return true;
4111   }
4112   return false;
4113 }
4114 
4115 /// Diagnose use of %s directive in an NSString which is being passed
4116 /// as formatting string to formatting method.
4117 static void
4118 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
4119                                         const NamedDecl *FDecl,
4120                                         Expr **Args,
4121                                         unsigned NumArgs) {
4122   unsigned Idx = 0;
4123   bool Format = false;
4124   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
4125   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
4126     Idx = 2;
4127     Format = true;
4128   }
4129   else
4130     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4131       if (S.GetFormatNSStringIdx(I, Idx)) {
4132         Format = true;
4133         break;
4134       }
4135     }
4136   if (!Format || NumArgs <= Idx)
4137     return;
4138   const Expr *FormatExpr = Args[Idx];
4139   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4140     FormatExpr = CSCE->getSubExpr();
4141   const StringLiteral *FormatString;
4142   if (const ObjCStringLiteral *OSL =
4143       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4144     FormatString = OSL->getString();
4145   else
4146     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4147   if (!FormatString)
4148     return;
4149   if (S.FormatStringHasSArg(FormatString)) {
4150     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4151       << "%s" << 1 << 1;
4152     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4153       << FDecl->getDeclName();
4154   }
4155 }
4156 
4157 /// Determine whether the given type has a non-null nullability annotation.
4158 static bool isNonNullType(ASTContext &ctx, QualType type) {
4159   if (auto nullability = type->getNullability(ctx))
4160     return *nullability == NullabilityKind::NonNull;
4161 
4162   return false;
4163 }
4164 
4165 static void CheckNonNullArguments(Sema &S,
4166                                   const NamedDecl *FDecl,
4167                                   const FunctionProtoType *Proto,
4168                                   ArrayRef<const Expr *> Args,
4169                                   SourceLocation CallSiteLoc) {
4170   assert((FDecl || Proto) && "Need a function declaration or prototype");
4171 
4172   // Already checked by by constant evaluator.
4173   if (S.isConstantEvaluated())
4174     return;
4175   // Check the attributes attached to the method/function itself.
4176   llvm::SmallBitVector NonNullArgs;
4177   if (FDecl) {
4178     // Handle the nonnull attribute on the function/method declaration itself.
4179     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4180       if (!NonNull->args_size()) {
4181         // Easy case: all pointer arguments are nonnull.
4182         for (const auto *Arg : Args)
4183           if (S.isValidPointerAttrType(Arg->getType()))
4184             CheckNonNullArgument(S, Arg, CallSiteLoc);
4185         return;
4186       }
4187 
4188       for (const ParamIdx &Idx : NonNull->args()) {
4189         unsigned IdxAST = Idx.getASTIndex();
4190         if (IdxAST >= Args.size())
4191           continue;
4192         if (NonNullArgs.empty())
4193           NonNullArgs.resize(Args.size());
4194         NonNullArgs.set(IdxAST);
4195       }
4196     }
4197   }
4198 
4199   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4200     // Handle the nonnull attribute on the parameters of the
4201     // function/method.
4202     ArrayRef<ParmVarDecl*> parms;
4203     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4204       parms = FD->parameters();
4205     else
4206       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4207 
4208     unsigned ParamIndex = 0;
4209     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4210          I != E; ++I, ++ParamIndex) {
4211       const ParmVarDecl *PVD = *I;
4212       if (PVD->hasAttr<NonNullAttr>() ||
4213           isNonNullType(S.Context, PVD->getType())) {
4214         if (NonNullArgs.empty())
4215           NonNullArgs.resize(Args.size());
4216 
4217         NonNullArgs.set(ParamIndex);
4218       }
4219     }
4220   } else {
4221     // If we have a non-function, non-method declaration but no
4222     // function prototype, try to dig out the function prototype.
4223     if (!Proto) {
4224       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4225         QualType type = VD->getType().getNonReferenceType();
4226         if (auto pointerType = type->getAs<PointerType>())
4227           type = pointerType->getPointeeType();
4228         else if (auto blockType = type->getAs<BlockPointerType>())
4229           type = blockType->getPointeeType();
4230         // FIXME: data member pointers?
4231 
4232         // Dig out the function prototype, if there is one.
4233         Proto = type->getAs<FunctionProtoType>();
4234       }
4235     }
4236 
4237     // Fill in non-null argument information from the nullability
4238     // information on the parameter types (if we have them).
4239     if (Proto) {
4240       unsigned Index = 0;
4241       for (auto paramType : Proto->getParamTypes()) {
4242         if (isNonNullType(S.Context, paramType)) {
4243           if (NonNullArgs.empty())
4244             NonNullArgs.resize(Args.size());
4245 
4246           NonNullArgs.set(Index);
4247         }
4248 
4249         ++Index;
4250       }
4251     }
4252   }
4253 
4254   // Check for non-null arguments.
4255   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4256        ArgIndex != ArgIndexEnd; ++ArgIndex) {
4257     if (NonNullArgs[ArgIndex])
4258       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4259   }
4260 }
4261 
4262 /// Handles the checks for format strings, non-POD arguments to vararg
4263 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4264 /// attributes.
4265 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4266                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
4267                      bool IsMemberFunction, SourceLocation Loc,
4268                      SourceRange Range, VariadicCallType CallType) {
4269   // FIXME: We should check as much as we can in the template definition.
4270   if (CurContext->isDependentContext())
4271     return;
4272 
4273   // Printf and scanf checking.
4274   llvm::SmallBitVector CheckedVarArgs;
4275   if (FDecl) {
4276     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4277       // Only create vector if there are format attributes.
4278       CheckedVarArgs.resize(Args.size());
4279 
4280       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4281                            CheckedVarArgs);
4282     }
4283   }
4284 
4285   // Refuse POD arguments that weren't caught by the format string
4286   // checks above.
4287   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4288   if (CallType != VariadicDoesNotApply &&
4289       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4290     unsigned NumParams = Proto ? Proto->getNumParams()
4291                        : FDecl && isa<FunctionDecl>(FDecl)
4292                            ? cast<FunctionDecl>(FDecl)->getNumParams()
4293                        : FDecl && isa<ObjCMethodDecl>(FDecl)
4294                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
4295                        : 0;
4296 
4297     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4298       // Args[ArgIdx] can be null in malformed code.
4299       if (const Expr *Arg = Args[ArgIdx]) {
4300         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4301           checkVariadicArgument(Arg, CallType);
4302       }
4303     }
4304   }
4305 
4306   if (FDecl || Proto) {
4307     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4308 
4309     // Type safety checking.
4310     if (FDecl) {
4311       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4312         CheckArgumentWithTypeTag(I, Args, Loc);
4313     }
4314   }
4315 
4316   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4317     auto *AA = FDecl->getAttr<AllocAlignAttr>();
4318     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4319     if (!Arg->isValueDependent()) {
4320       Expr::EvalResult Align;
4321       if (Arg->EvaluateAsInt(Align, Context)) {
4322         const llvm::APSInt &I = Align.Val.getInt();
4323         if (!I.isPowerOf2())
4324           Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
4325               << Arg->getSourceRange();
4326 
4327         if (I > Sema::MaximumAlignment)
4328           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
4329               << Arg->getSourceRange() << Sema::MaximumAlignment;
4330       }
4331     }
4332   }
4333 
4334   if (FD)
4335     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4336 }
4337 
4338 /// CheckConstructorCall - Check a constructor call for correctness and safety
4339 /// properties not enforced by the C type system.
4340 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
4341                                 ArrayRef<const Expr *> Args,
4342                                 const FunctionProtoType *Proto,
4343                                 SourceLocation Loc) {
4344   VariadicCallType CallType =
4345     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4346   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4347             Loc, SourceRange(), CallType);
4348 }
4349 
4350 /// CheckFunctionCall - Check a direct function call for various correctness
4351 /// and safety properties not strictly enforced by the C type system.
4352 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4353                              const FunctionProtoType *Proto) {
4354   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4355                               isa<CXXMethodDecl>(FDecl);
4356   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4357                           IsMemberOperatorCall;
4358   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4359                                                   TheCall->getCallee());
4360   Expr** Args = TheCall->getArgs();
4361   unsigned NumArgs = TheCall->getNumArgs();
4362 
4363   Expr *ImplicitThis = nullptr;
4364   if (IsMemberOperatorCall) {
4365     // If this is a call to a member operator, hide the first argument
4366     // from checkCall.
4367     // FIXME: Our choice of AST representation here is less than ideal.
4368     ImplicitThis = Args[0];
4369     ++Args;
4370     --NumArgs;
4371   } else if (IsMemberFunction)
4372     ImplicitThis =
4373         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4374 
4375   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
4376             IsMemberFunction, TheCall->getRParenLoc(),
4377             TheCall->getCallee()->getSourceRange(), CallType);
4378 
4379   IdentifierInfo *FnInfo = FDecl->getIdentifier();
4380   // None of the checks below are needed for functions that don't have
4381   // simple names (e.g., C++ conversion functions).
4382   if (!FnInfo)
4383     return false;
4384 
4385   CheckAbsoluteValueFunction(TheCall, FDecl);
4386   CheckMaxUnsignedZero(TheCall, FDecl);
4387 
4388   if (getLangOpts().ObjC)
4389     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
4390 
4391   unsigned CMId = FDecl->getMemoryFunctionKind();
4392   if (CMId == 0)
4393     return false;
4394 
4395   // Handle memory setting and copying functions.
4396   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
4397     CheckStrlcpycatArguments(TheCall, FnInfo);
4398   else if (CMId == Builtin::BIstrncat)
4399     CheckStrncatArguments(TheCall, FnInfo);
4400   else
4401     CheckMemaccessArguments(TheCall, CMId, FnInfo);
4402 
4403   return false;
4404 }
4405 
4406 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
4407                                ArrayRef<const Expr *> Args) {
4408   VariadicCallType CallType =
4409       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
4410 
4411   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
4412             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
4413             CallType);
4414 
4415   return false;
4416 }
4417 
4418 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4419                             const FunctionProtoType *Proto) {
4420   QualType Ty;
4421   if (const auto *V = dyn_cast<VarDecl>(NDecl))
4422     Ty = V->getType().getNonReferenceType();
4423   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4424     Ty = F->getType().getNonReferenceType();
4425   else
4426     return false;
4427 
4428   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4429       !Ty->isFunctionProtoType())
4430     return false;
4431 
4432   VariadicCallType CallType;
4433   if (!Proto || !Proto->isVariadic()) {
4434     CallType = VariadicDoesNotApply;
4435   } else if (Ty->isBlockPointerType()) {
4436     CallType = VariadicBlock;
4437   } else { // Ty->isFunctionPointerType()
4438     CallType = VariadicFunction;
4439   }
4440 
4441   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4442             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4443             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4444             TheCall->getCallee()->getSourceRange(), CallType);
4445 
4446   return false;
4447 }
4448 
4449 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
4450 /// such as function pointers returned from functions.
4451 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4452   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4453                                                   TheCall->getCallee());
4454   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4455             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4456             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4457             TheCall->getCallee()->getSourceRange(), CallType);
4458 
4459   return false;
4460 }
4461 
4462 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4463   if (!llvm::isValidAtomicOrderingCABI(Ordering))
4464     return false;
4465 
4466   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4467   switch (Op) {
4468   case AtomicExpr::AO__c11_atomic_init:
4469   case AtomicExpr::AO__opencl_atomic_init:
4470     llvm_unreachable("There is no ordering argument for an init");
4471 
4472   case AtomicExpr::AO__c11_atomic_load:
4473   case AtomicExpr::AO__opencl_atomic_load:
4474   case AtomicExpr::AO__atomic_load_n:
4475   case AtomicExpr::AO__atomic_load:
4476     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4477            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4478 
4479   case AtomicExpr::AO__c11_atomic_store:
4480   case AtomicExpr::AO__opencl_atomic_store:
4481   case AtomicExpr::AO__atomic_store:
4482   case AtomicExpr::AO__atomic_store_n:
4483     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4484            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4485            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4486 
4487   default:
4488     return true;
4489   }
4490 }
4491 
4492 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
4493                                          AtomicExpr::AtomicOp Op) {
4494   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4495   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4496   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4497   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
4498                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
4499                          Op);
4500 }
4501 
4502 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
4503                                  SourceLocation RParenLoc, MultiExprArg Args,
4504                                  AtomicExpr::AtomicOp Op,
4505                                  AtomicArgumentOrder ArgOrder) {
4506   // All the non-OpenCL operations take one of the following forms.
4507   // The OpenCL operations take the __c11 forms with one extra argument for
4508   // synchronization scope.
4509   enum {
4510     // C    __c11_atomic_init(A *, C)
4511     Init,
4512 
4513     // C    __c11_atomic_load(A *, int)
4514     Load,
4515 
4516     // void __atomic_load(A *, CP, int)
4517     LoadCopy,
4518 
4519     // void __atomic_store(A *, CP, int)
4520     Copy,
4521 
4522     // C    __c11_atomic_add(A *, M, int)
4523     Arithmetic,
4524 
4525     // C    __atomic_exchange_n(A *, CP, int)
4526     Xchg,
4527 
4528     // void __atomic_exchange(A *, C *, CP, int)
4529     GNUXchg,
4530 
4531     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4532     C11CmpXchg,
4533 
4534     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4535     GNUCmpXchg
4536   } Form = Init;
4537 
4538   const unsigned NumForm = GNUCmpXchg + 1;
4539   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
4540   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
4541   // where:
4542   //   C is an appropriate type,
4543   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4544   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4545   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4546   //   the int parameters are for orderings.
4547 
4548   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4549       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4550       "need to update code for modified forms");
4551   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
4552                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
4553                         AtomicExpr::AO__atomic_load,
4554                 "need to update code for modified C11 atomics");
4555   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
4556                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
4557   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
4558                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
4559                IsOpenCL;
4560   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4561              Op == AtomicExpr::AO__atomic_store_n ||
4562              Op == AtomicExpr::AO__atomic_exchange_n ||
4563              Op == AtomicExpr::AO__atomic_compare_exchange_n;
4564   bool IsAddSub = false;
4565 
4566   switch (Op) {
4567   case AtomicExpr::AO__c11_atomic_init:
4568   case AtomicExpr::AO__opencl_atomic_init:
4569     Form = Init;
4570     break;
4571 
4572   case AtomicExpr::AO__c11_atomic_load:
4573   case AtomicExpr::AO__opencl_atomic_load:
4574   case AtomicExpr::AO__atomic_load_n:
4575     Form = Load;
4576     break;
4577 
4578   case AtomicExpr::AO__atomic_load:
4579     Form = LoadCopy;
4580     break;
4581 
4582   case AtomicExpr::AO__c11_atomic_store:
4583   case AtomicExpr::AO__opencl_atomic_store:
4584   case AtomicExpr::AO__atomic_store:
4585   case AtomicExpr::AO__atomic_store_n:
4586     Form = Copy;
4587     break;
4588 
4589   case AtomicExpr::AO__c11_atomic_fetch_add:
4590   case AtomicExpr::AO__c11_atomic_fetch_sub:
4591   case AtomicExpr::AO__opencl_atomic_fetch_add:
4592   case AtomicExpr::AO__opencl_atomic_fetch_sub:
4593   case AtomicExpr::AO__atomic_fetch_add:
4594   case AtomicExpr::AO__atomic_fetch_sub:
4595   case AtomicExpr::AO__atomic_add_fetch:
4596   case AtomicExpr::AO__atomic_sub_fetch:
4597     IsAddSub = true;
4598     LLVM_FALLTHROUGH;
4599   case AtomicExpr::AO__c11_atomic_fetch_and:
4600   case AtomicExpr::AO__c11_atomic_fetch_or:
4601   case AtomicExpr::AO__c11_atomic_fetch_xor:
4602   case AtomicExpr::AO__opencl_atomic_fetch_and:
4603   case AtomicExpr::AO__opencl_atomic_fetch_or:
4604   case AtomicExpr::AO__opencl_atomic_fetch_xor:
4605   case AtomicExpr::AO__atomic_fetch_and:
4606   case AtomicExpr::AO__atomic_fetch_or:
4607   case AtomicExpr::AO__atomic_fetch_xor:
4608   case AtomicExpr::AO__atomic_fetch_nand:
4609   case AtomicExpr::AO__atomic_and_fetch:
4610   case AtomicExpr::AO__atomic_or_fetch:
4611   case AtomicExpr::AO__atomic_xor_fetch:
4612   case AtomicExpr::AO__atomic_nand_fetch:
4613   case AtomicExpr::AO__c11_atomic_fetch_min:
4614   case AtomicExpr::AO__c11_atomic_fetch_max:
4615   case AtomicExpr::AO__opencl_atomic_fetch_min:
4616   case AtomicExpr::AO__opencl_atomic_fetch_max:
4617   case AtomicExpr::AO__atomic_min_fetch:
4618   case AtomicExpr::AO__atomic_max_fetch:
4619   case AtomicExpr::AO__atomic_fetch_min:
4620   case AtomicExpr::AO__atomic_fetch_max:
4621     Form = Arithmetic;
4622     break;
4623 
4624   case AtomicExpr::AO__c11_atomic_exchange:
4625   case AtomicExpr::AO__opencl_atomic_exchange:
4626   case AtomicExpr::AO__atomic_exchange_n:
4627     Form = Xchg;
4628     break;
4629 
4630   case AtomicExpr::AO__atomic_exchange:
4631     Form = GNUXchg;
4632     break;
4633 
4634   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4635   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4636   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4637   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4638     Form = C11CmpXchg;
4639     break;
4640 
4641   case AtomicExpr::AO__atomic_compare_exchange:
4642   case AtomicExpr::AO__atomic_compare_exchange_n:
4643     Form = GNUCmpXchg;
4644     break;
4645   }
4646 
4647   unsigned AdjustedNumArgs = NumArgs[Form];
4648   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
4649     ++AdjustedNumArgs;
4650   // Check we have the right number of arguments.
4651   if (Args.size() < AdjustedNumArgs) {
4652     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
4653         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4654         << ExprRange;
4655     return ExprError();
4656   } else if (Args.size() > AdjustedNumArgs) {
4657     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
4658          diag::err_typecheck_call_too_many_args)
4659         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4660         << ExprRange;
4661     return ExprError();
4662   }
4663 
4664   // Inspect the first argument of the atomic operation.
4665   Expr *Ptr = Args[0];
4666   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
4667   if (ConvertedPtr.isInvalid())
4668     return ExprError();
4669 
4670   Ptr = ConvertedPtr.get();
4671   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4672   if (!pointerType) {
4673     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
4674         << Ptr->getType() << Ptr->getSourceRange();
4675     return ExprError();
4676   }
4677 
4678   // For a __c11 builtin, this should be a pointer to an _Atomic type.
4679   QualType AtomTy = pointerType->getPointeeType(); // 'A'
4680   QualType ValType = AtomTy; // 'C'
4681   if (IsC11) {
4682     if (!AtomTy->isAtomicType()) {
4683       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
4684           << Ptr->getType() << Ptr->getSourceRange();
4685       return ExprError();
4686     }
4687     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
4688         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
4689       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
4690           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4691           << Ptr->getSourceRange();
4692       return ExprError();
4693     }
4694     ValType = AtomTy->castAs<AtomicType>()->getValueType();
4695   } else if (Form != Load && Form != LoadCopy) {
4696     if (ValType.isConstQualified()) {
4697       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
4698           << Ptr->getType() << Ptr->getSourceRange();
4699       return ExprError();
4700     }
4701   }
4702 
4703   // For an arithmetic operation, the implied arithmetic must be well-formed.
4704   if (Form == Arithmetic) {
4705     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
4706     if (IsAddSub && !ValType->isIntegerType()
4707         && !ValType->isPointerType()) {
4708       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4709           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4710       return ExprError();
4711     }
4712     if (!IsAddSub && !ValType->isIntegerType()) {
4713       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
4714           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4715       return ExprError();
4716     }
4717     if (IsC11 && ValType->isPointerType() &&
4718         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
4719                             diag::err_incomplete_type)) {
4720       return ExprError();
4721     }
4722   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
4723     // For __atomic_*_n operations, the value type must be a scalar integral or
4724     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
4725     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4726         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4727     return ExprError();
4728   }
4729 
4730   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4731       !AtomTy->isScalarType()) {
4732     // For GNU atomics, require a trivially-copyable type. This is not part of
4733     // the GNU atomics specification, but we enforce it for sanity.
4734     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
4735         << Ptr->getType() << Ptr->getSourceRange();
4736     return ExprError();
4737   }
4738 
4739   switch (ValType.getObjCLifetime()) {
4740   case Qualifiers::OCL_None:
4741   case Qualifiers::OCL_ExplicitNone:
4742     // okay
4743     break;
4744 
4745   case Qualifiers::OCL_Weak:
4746   case Qualifiers::OCL_Strong:
4747   case Qualifiers::OCL_Autoreleasing:
4748     // FIXME: Can this happen? By this point, ValType should be known
4749     // to be trivially copyable.
4750     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
4751         << ValType << Ptr->getSourceRange();
4752     return ExprError();
4753   }
4754 
4755   // All atomic operations have an overload which takes a pointer to a volatile
4756   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
4757   // into the result or the other operands. Similarly atomic_load takes a
4758   // pointer to a const 'A'.
4759   ValType.removeLocalVolatile();
4760   ValType.removeLocalConst();
4761   QualType ResultType = ValType;
4762   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
4763       Form == Init)
4764     ResultType = Context.VoidTy;
4765   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
4766     ResultType = Context.BoolTy;
4767 
4768   // The type of a parameter passed 'by value'. In the GNU atomics, such
4769   // arguments are actually passed as pointers.
4770   QualType ByValType = ValType; // 'CP'
4771   bool IsPassedByAddress = false;
4772   if (!IsC11 && !IsN) {
4773     ByValType = Ptr->getType();
4774     IsPassedByAddress = true;
4775   }
4776 
4777   SmallVector<Expr *, 5> APIOrderedArgs;
4778   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
4779     APIOrderedArgs.push_back(Args[0]);
4780     switch (Form) {
4781     case Init:
4782     case Load:
4783       APIOrderedArgs.push_back(Args[1]); // Val1/Order
4784       break;
4785     case LoadCopy:
4786     case Copy:
4787     case Arithmetic:
4788     case Xchg:
4789       APIOrderedArgs.push_back(Args[2]); // Val1
4790       APIOrderedArgs.push_back(Args[1]); // Order
4791       break;
4792     case GNUXchg:
4793       APIOrderedArgs.push_back(Args[2]); // Val1
4794       APIOrderedArgs.push_back(Args[3]); // Val2
4795       APIOrderedArgs.push_back(Args[1]); // Order
4796       break;
4797     case C11CmpXchg:
4798       APIOrderedArgs.push_back(Args[2]); // Val1
4799       APIOrderedArgs.push_back(Args[4]); // Val2
4800       APIOrderedArgs.push_back(Args[1]); // Order
4801       APIOrderedArgs.push_back(Args[3]); // OrderFail
4802       break;
4803     case GNUCmpXchg:
4804       APIOrderedArgs.push_back(Args[2]); // Val1
4805       APIOrderedArgs.push_back(Args[4]); // Val2
4806       APIOrderedArgs.push_back(Args[5]); // Weak
4807       APIOrderedArgs.push_back(Args[1]); // Order
4808       APIOrderedArgs.push_back(Args[3]); // OrderFail
4809       break;
4810     }
4811   } else
4812     APIOrderedArgs.append(Args.begin(), Args.end());
4813 
4814   // The first argument's non-CV pointer type is used to deduce the type of
4815   // subsequent arguments, except for:
4816   //  - weak flag (always converted to bool)
4817   //  - memory order (always converted to int)
4818   //  - scope  (always converted to int)
4819   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
4820     QualType Ty;
4821     if (i < NumVals[Form] + 1) {
4822       switch (i) {
4823       case 0:
4824         // The first argument is always a pointer. It has a fixed type.
4825         // It is always dereferenced, a nullptr is undefined.
4826         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4827         // Nothing else to do: we already know all we want about this pointer.
4828         continue;
4829       case 1:
4830         // The second argument is the non-atomic operand. For arithmetic, this
4831         // is always passed by value, and for a compare_exchange it is always
4832         // passed by address. For the rest, GNU uses by-address and C11 uses
4833         // by-value.
4834         assert(Form != Load);
4835         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
4836           Ty = ValType;
4837         else if (Form == Copy || Form == Xchg) {
4838           if (IsPassedByAddress) {
4839             // The value pointer is always dereferenced, a nullptr is undefined.
4840             CheckNonNullArgument(*this, APIOrderedArgs[i],
4841                                  ExprRange.getBegin());
4842           }
4843           Ty = ByValType;
4844         } else if (Form == Arithmetic)
4845           Ty = Context.getPointerDiffType();
4846         else {
4847           Expr *ValArg = APIOrderedArgs[i];
4848           // The value pointer is always dereferenced, a nullptr is undefined.
4849           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
4850           LangAS AS = LangAS::Default;
4851           // Keep address space of non-atomic pointer type.
4852           if (const PointerType *PtrTy =
4853                   ValArg->getType()->getAs<PointerType>()) {
4854             AS = PtrTy->getPointeeType().getAddressSpace();
4855           }
4856           Ty = Context.getPointerType(
4857               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
4858         }
4859         break;
4860       case 2:
4861         // The third argument to compare_exchange / GNU exchange is the desired
4862         // value, either by-value (for the C11 and *_n variant) or as a pointer.
4863         if (IsPassedByAddress)
4864           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4865         Ty = ByValType;
4866         break;
4867       case 3:
4868         // The fourth argument to GNU compare_exchange is a 'weak' flag.
4869         Ty = Context.BoolTy;
4870         break;
4871       }
4872     } else {
4873       // The order(s) and scope are always converted to int.
4874       Ty = Context.IntTy;
4875     }
4876 
4877     InitializedEntity Entity =
4878         InitializedEntity::InitializeParameter(Context, Ty, false);
4879     ExprResult Arg = APIOrderedArgs[i];
4880     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4881     if (Arg.isInvalid())
4882       return true;
4883     APIOrderedArgs[i] = Arg.get();
4884   }
4885 
4886   // Permute the arguments into a 'consistent' order.
4887   SmallVector<Expr*, 5> SubExprs;
4888   SubExprs.push_back(Ptr);
4889   switch (Form) {
4890   case Init:
4891     // Note, AtomicExpr::getVal1() has a special case for this atomic.
4892     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4893     break;
4894   case Load:
4895     SubExprs.push_back(APIOrderedArgs[1]); // Order
4896     break;
4897   case LoadCopy:
4898   case Copy:
4899   case Arithmetic:
4900   case Xchg:
4901     SubExprs.push_back(APIOrderedArgs[2]); // Order
4902     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4903     break;
4904   case GNUXchg:
4905     // Note, AtomicExpr::getVal2() has a special case for this atomic.
4906     SubExprs.push_back(APIOrderedArgs[3]); // Order
4907     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4908     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4909     break;
4910   case C11CmpXchg:
4911     SubExprs.push_back(APIOrderedArgs[3]); // Order
4912     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4913     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
4914     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4915     break;
4916   case GNUCmpXchg:
4917     SubExprs.push_back(APIOrderedArgs[4]); // Order
4918     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4919     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
4920     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4921     SubExprs.push_back(APIOrderedArgs[3]); // Weak
4922     break;
4923   }
4924 
4925   if (SubExprs.size() >= 2 && Form != Init) {
4926     llvm::APSInt Result(32);
4927     if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
4928         !isValidOrderingForOp(Result.getSExtValue(), Op))
4929       Diag(SubExprs[1]->getBeginLoc(),
4930            diag::warn_atomic_op_has_invalid_memory_order)
4931           << SubExprs[1]->getSourceRange();
4932   }
4933 
4934   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
4935     auto *Scope = Args[Args.size() - 1];
4936     llvm::APSInt Result(32);
4937     if (Scope->isIntegerConstantExpr(Result, Context) &&
4938         !ScopeModel->isValid(Result.getZExtValue())) {
4939       Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
4940           << Scope->getSourceRange();
4941     }
4942     SubExprs.push_back(Scope);
4943   }
4944 
4945   AtomicExpr *AE = new (Context)
4946       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
4947 
4948   if ((Op == AtomicExpr::AO__c11_atomic_load ||
4949        Op == AtomicExpr::AO__c11_atomic_store ||
4950        Op == AtomicExpr::AO__opencl_atomic_load ||
4951        Op == AtomicExpr::AO__opencl_atomic_store ) &&
4952       Context.AtomicUsesUnsupportedLibcall(AE))
4953     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
4954         << ((Op == AtomicExpr::AO__c11_atomic_load ||
4955              Op == AtomicExpr::AO__opencl_atomic_load)
4956                 ? 0
4957                 : 1);
4958 
4959   if (ValType->isExtIntType()) {
4960     Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit);
4961     return ExprError();
4962   }
4963 
4964   return AE;
4965 }
4966 
4967 /// checkBuiltinArgument - Given a call to a builtin function, perform
4968 /// normal type-checking on the given argument, updating the call in
4969 /// place.  This is useful when a builtin function requires custom
4970 /// type-checking for some of its arguments but not necessarily all of
4971 /// them.
4972 ///
4973 /// Returns true on error.
4974 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
4975   FunctionDecl *Fn = E->getDirectCallee();
4976   assert(Fn && "builtin call without direct callee!");
4977 
4978   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
4979   InitializedEntity Entity =
4980     InitializedEntity::InitializeParameter(S.Context, Param);
4981 
4982   ExprResult Arg = E->getArg(0);
4983   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
4984   if (Arg.isInvalid())
4985     return true;
4986 
4987   E->setArg(ArgIndex, Arg.get());
4988   return false;
4989 }
4990 
4991 /// We have a call to a function like __sync_fetch_and_add, which is an
4992 /// overloaded function based on the pointer type of its first argument.
4993 /// The main BuildCallExpr routines have already promoted the types of
4994 /// arguments because all of these calls are prototyped as void(...).
4995 ///
4996 /// This function goes through and does final semantic checking for these
4997 /// builtins, as well as generating any warnings.
4998 ExprResult
4999 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
5000   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5001   Expr *Callee = TheCall->getCallee();
5002   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
5003   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5004 
5005   // Ensure that we have at least one argument to do type inference from.
5006   if (TheCall->getNumArgs() < 1) {
5007     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5008         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
5009     return ExprError();
5010   }
5011 
5012   // Inspect the first argument of the atomic builtin.  This should always be
5013   // a pointer type, whose element is an integral scalar or pointer type.
5014   // Because it is a pointer type, we don't have to worry about any implicit
5015   // casts here.
5016   // FIXME: We don't allow floating point scalars as input.
5017   Expr *FirstArg = TheCall->getArg(0);
5018   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5019   if (FirstArgResult.isInvalid())
5020     return ExprError();
5021   FirstArg = FirstArgResult.get();
5022   TheCall->setArg(0, FirstArg);
5023 
5024   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5025   if (!pointerType) {
5026     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5027         << FirstArg->getType() << FirstArg->getSourceRange();
5028     return ExprError();
5029   }
5030 
5031   QualType ValType = pointerType->getPointeeType();
5032   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5033       !ValType->isBlockPointerType()) {
5034     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5035         << FirstArg->getType() << FirstArg->getSourceRange();
5036     return ExprError();
5037   }
5038 
5039   if (ValType.isConstQualified()) {
5040     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5041         << FirstArg->getType() << FirstArg->getSourceRange();
5042     return ExprError();
5043   }
5044 
5045   switch (ValType.getObjCLifetime()) {
5046   case Qualifiers::OCL_None:
5047   case Qualifiers::OCL_ExplicitNone:
5048     // okay
5049     break;
5050 
5051   case Qualifiers::OCL_Weak:
5052   case Qualifiers::OCL_Strong:
5053   case Qualifiers::OCL_Autoreleasing:
5054     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5055         << ValType << FirstArg->getSourceRange();
5056     return ExprError();
5057   }
5058 
5059   // Strip any qualifiers off ValType.
5060   ValType = ValType.getUnqualifiedType();
5061 
5062   // The majority of builtins return a value, but a few have special return
5063   // types, so allow them to override appropriately below.
5064   QualType ResultType = ValType;
5065 
5066   // We need to figure out which concrete builtin this maps onto.  For example,
5067   // __sync_fetch_and_add with a 2 byte object turns into
5068   // __sync_fetch_and_add_2.
5069 #define BUILTIN_ROW(x) \
5070   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5071     Builtin::BI##x##_8, Builtin::BI##x##_16 }
5072 
5073   static const unsigned BuiltinIndices[][5] = {
5074     BUILTIN_ROW(__sync_fetch_and_add),
5075     BUILTIN_ROW(__sync_fetch_and_sub),
5076     BUILTIN_ROW(__sync_fetch_and_or),
5077     BUILTIN_ROW(__sync_fetch_and_and),
5078     BUILTIN_ROW(__sync_fetch_and_xor),
5079     BUILTIN_ROW(__sync_fetch_and_nand),
5080 
5081     BUILTIN_ROW(__sync_add_and_fetch),
5082     BUILTIN_ROW(__sync_sub_and_fetch),
5083     BUILTIN_ROW(__sync_and_and_fetch),
5084     BUILTIN_ROW(__sync_or_and_fetch),
5085     BUILTIN_ROW(__sync_xor_and_fetch),
5086     BUILTIN_ROW(__sync_nand_and_fetch),
5087 
5088     BUILTIN_ROW(__sync_val_compare_and_swap),
5089     BUILTIN_ROW(__sync_bool_compare_and_swap),
5090     BUILTIN_ROW(__sync_lock_test_and_set),
5091     BUILTIN_ROW(__sync_lock_release),
5092     BUILTIN_ROW(__sync_swap)
5093   };
5094 #undef BUILTIN_ROW
5095 
5096   // Determine the index of the size.
5097   unsigned SizeIndex;
5098   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5099   case 1: SizeIndex = 0; break;
5100   case 2: SizeIndex = 1; break;
5101   case 4: SizeIndex = 2; break;
5102   case 8: SizeIndex = 3; break;
5103   case 16: SizeIndex = 4; break;
5104   default:
5105     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5106         << FirstArg->getType() << FirstArg->getSourceRange();
5107     return ExprError();
5108   }
5109 
5110   // Each of these builtins has one pointer argument, followed by some number of
5111   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5112   // that we ignore.  Find out which row of BuiltinIndices to read from as well
5113   // as the number of fixed args.
5114   unsigned BuiltinID = FDecl->getBuiltinID();
5115   unsigned BuiltinIndex, NumFixed = 1;
5116   bool WarnAboutSemanticsChange = false;
5117   switch (BuiltinID) {
5118   default: llvm_unreachable("Unknown overloaded atomic builtin!");
5119   case Builtin::BI__sync_fetch_and_add:
5120   case Builtin::BI__sync_fetch_and_add_1:
5121   case Builtin::BI__sync_fetch_and_add_2:
5122   case Builtin::BI__sync_fetch_and_add_4:
5123   case Builtin::BI__sync_fetch_and_add_8:
5124   case Builtin::BI__sync_fetch_and_add_16:
5125     BuiltinIndex = 0;
5126     break;
5127 
5128   case Builtin::BI__sync_fetch_and_sub:
5129   case Builtin::BI__sync_fetch_and_sub_1:
5130   case Builtin::BI__sync_fetch_and_sub_2:
5131   case Builtin::BI__sync_fetch_and_sub_4:
5132   case Builtin::BI__sync_fetch_and_sub_8:
5133   case Builtin::BI__sync_fetch_and_sub_16:
5134     BuiltinIndex = 1;
5135     break;
5136 
5137   case Builtin::BI__sync_fetch_and_or:
5138   case Builtin::BI__sync_fetch_and_or_1:
5139   case Builtin::BI__sync_fetch_and_or_2:
5140   case Builtin::BI__sync_fetch_and_or_4:
5141   case Builtin::BI__sync_fetch_and_or_8:
5142   case Builtin::BI__sync_fetch_and_or_16:
5143     BuiltinIndex = 2;
5144     break;
5145 
5146   case Builtin::BI__sync_fetch_and_and:
5147   case Builtin::BI__sync_fetch_and_and_1:
5148   case Builtin::BI__sync_fetch_and_and_2:
5149   case Builtin::BI__sync_fetch_and_and_4:
5150   case Builtin::BI__sync_fetch_and_and_8:
5151   case Builtin::BI__sync_fetch_and_and_16:
5152     BuiltinIndex = 3;
5153     break;
5154 
5155   case Builtin::BI__sync_fetch_and_xor:
5156   case Builtin::BI__sync_fetch_and_xor_1:
5157   case Builtin::BI__sync_fetch_and_xor_2:
5158   case Builtin::BI__sync_fetch_and_xor_4:
5159   case Builtin::BI__sync_fetch_and_xor_8:
5160   case Builtin::BI__sync_fetch_and_xor_16:
5161     BuiltinIndex = 4;
5162     break;
5163 
5164   case Builtin::BI__sync_fetch_and_nand:
5165   case Builtin::BI__sync_fetch_and_nand_1:
5166   case Builtin::BI__sync_fetch_and_nand_2:
5167   case Builtin::BI__sync_fetch_and_nand_4:
5168   case Builtin::BI__sync_fetch_and_nand_8:
5169   case Builtin::BI__sync_fetch_and_nand_16:
5170     BuiltinIndex = 5;
5171     WarnAboutSemanticsChange = true;
5172     break;
5173 
5174   case Builtin::BI__sync_add_and_fetch:
5175   case Builtin::BI__sync_add_and_fetch_1:
5176   case Builtin::BI__sync_add_and_fetch_2:
5177   case Builtin::BI__sync_add_and_fetch_4:
5178   case Builtin::BI__sync_add_and_fetch_8:
5179   case Builtin::BI__sync_add_and_fetch_16:
5180     BuiltinIndex = 6;
5181     break;
5182 
5183   case Builtin::BI__sync_sub_and_fetch:
5184   case Builtin::BI__sync_sub_and_fetch_1:
5185   case Builtin::BI__sync_sub_and_fetch_2:
5186   case Builtin::BI__sync_sub_and_fetch_4:
5187   case Builtin::BI__sync_sub_and_fetch_8:
5188   case Builtin::BI__sync_sub_and_fetch_16:
5189     BuiltinIndex = 7;
5190     break;
5191 
5192   case Builtin::BI__sync_and_and_fetch:
5193   case Builtin::BI__sync_and_and_fetch_1:
5194   case Builtin::BI__sync_and_and_fetch_2:
5195   case Builtin::BI__sync_and_and_fetch_4:
5196   case Builtin::BI__sync_and_and_fetch_8:
5197   case Builtin::BI__sync_and_and_fetch_16:
5198     BuiltinIndex = 8;
5199     break;
5200 
5201   case Builtin::BI__sync_or_and_fetch:
5202   case Builtin::BI__sync_or_and_fetch_1:
5203   case Builtin::BI__sync_or_and_fetch_2:
5204   case Builtin::BI__sync_or_and_fetch_4:
5205   case Builtin::BI__sync_or_and_fetch_8:
5206   case Builtin::BI__sync_or_and_fetch_16:
5207     BuiltinIndex = 9;
5208     break;
5209 
5210   case Builtin::BI__sync_xor_and_fetch:
5211   case Builtin::BI__sync_xor_and_fetch_1:
5212   case Builtin::BI__sync_xor_and_fetch_2:
5213   case Builtin::BI__sync_xor_and_fetch_4:
5214   case Builtin::BI__sync_xor_and_fetch_8:
5215   case Builtin::BI__sync_xor_and_fetch_16:
5216     BuiltinIndex = 10;
5217     break;
5218 
5219   case Builtin::BI__sync_nand_and_fetch:
5220   case Builtin::BI__sync_nand_and_fetch_1:
5221   case Builtin::BI__sync_nand_and_fetch_2:
5222   case Builtin::BI__sync_nand_and_fetch_4:
5223   case Builtin::BI__sync_nand_and_fetch_8:
5224   case Builtin::BI__sync_nand_and_fetch_16:
5225     BuiltinIndex = 11;
5226     WarnAboutSemanticsChange = true;
5227     break;
5228 
5229   case Builtin::BI__sync_val_compare_and_swap:
5230   case Builtin::BI__sync_val_compare_and_swap_1:
5231   case Builtin::BI__sync_val_compare_and_swap_2:
5232   case Builtin::BI__sync_val_compare_and_swap_4:
5233   case Builtin::BI__sync_val_compare_and_swap_8:
5234   case Builtin::BI__sync_val_compare_and_swap_16:
5235     BuiltinIndex = 12;
5236     NumFixed = 2;
5237     break;
5238 
5239   case Builtin::BI__sync_bool_compare_and_swap:
5240   case Builtin::BI__sync_bool_compare_and_swap_1:
5241   case Builtin::BI__sync_bool_compare_and_swap_2:
5242   case Builtin::BI__sync_bool_compare_and_swap_4:
5243   case Builtin::BI__sync_bool_compare_and_swap_8:
5244   case Builtin::BI__sync_bool_compare_and_swap_16:
5245     BuiltinIndex = 13;
5246     NumFixed = 2;
5247     ResultType = Context.BoolTy;
5248     break;
5249 
5250   case Builtin::BI__sync_lock_test_and_set:
5251   case Builtin::BI__sync_lock_test_and_set_1:
5252   case Builtin::BI__sync_lock_test_and_set_2:
5253   case Builtin::BI__sync_lock_test_and_set_4:
5254   case Builtin::BI__sync_lock_test_and_set_8:
5255   case Builtin::BI__sync_lock_test_and_set_16:
5256     BuiltinIndex = 14;
5257     break;
5258 
5259   case Builtin::BI__sync_lock_release:
5260   case Builtin::BI__sync_lock_release_1:
5261   case Builtin::BI__sync_lock_release_2:
5262   case Builtin::BI__sync_lock_release_4:
5263   case Builtin::BI__sync_lock_release_8:
5264   case Builtin::BI__sync_lock_release_16:
5265     BuiltinIndex = 15;
5266     NumFixed = 0;
5267     ResultType = Context.VoidTy;
5268     break;
5269 
5270   case Builtin::BI__sync_swap:
5271   case Builtin::BI__sync_swap_1:
5272   case Builtin::BI__sync_swap_2:
5273   case Builtin::BI__sync_swap_4:
5274   case Builtin::BI__sync_swap_8:
5275   case Builtin::BI__sync_swap_16:
5276     BuiltinIndex = 16;
5277     break;
5278   }
5279 
5280   // Now that we know how many fixed arguments we expect, first check that we
5281   // have at least that many.
5282   if (TheCall->getNumArgs() < 1+NumFixed) {
5283     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5284         << 0 << 1 + NumFixed << TheCall->getNumArgs()
5285         << Callee->getSourceRange();
5286     return ExprError();
5287   }
5288 
5289   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5290       << Callee->getSourceRange();
5291 
5292   if (WarnAboutSemanticsChange) {
5293     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5294         << Callee->getSourceRange();
5295   }
5296 
5297   // Get the decl for the concrete builtin from this, we can tell what the
5298   // concrete integer type we should convert to is.
5299   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5300   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5301   FunctionDecl *NewBuiltinDecl;
5302   if (NewBuiltinID == BuiltinID)
5303     NewBuiltinDecl = FDecl;
5304   else {
5305     // Perform builtin lookup to avoid redeclaring it.
5306     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5307     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5308     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5309     assert(Res.getFoundDecl());
5310     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5311     if (!NewBuiltinDecl)
5312       return ExprError();
5313   }
5314 
5315   // The first argument --- the pointer --- has a fixed type; we
5316   // deduce the types of the rest of the arguments accordingly.  Walk
5317   // the remaining arguments, converting them to the deduced value type.
5318   for (unsigned i = 0; i != NumFixed; ++i) {
5319     ExprResult Arg = TheCall->getArg(i+1);
5320 
5321     // GCC does an implicit conversion to the pointer or integer ValType.  This
5322     // can fail in some cases (1i -> int**), check for this error case now.
5323     // Initialize the argument.
5324     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5325                                                    ValType, /*consume*/ false);
5326     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5327     if (Arg.isInvalid())
5328       return ExprError();
5329 
5330     // Okay, we have something that *can* be converted to the right type.  Check
5331     // to see if there is a potentially weird extension going on here.  This can
5332     // happen when you do an atomic operation on something like an char* and
5333     // pass in 42.  The 42 gets converted to char.  This is even more strange
5334     // for things like 45.123 -> char, etc.
5335     // FIXME: Do this check.
5336     TheCall->setArg(i+1, Arg.get());
5337   }
5338 
5339   // Create a new DeclRefExpr to refer to the new decl.
5340   DeclRefExpr *NewDRE = DeclRefExpr::Create(
5341       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5342       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5343       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
5344 
5345   // Set the callee in the CallExpr.
5346   // FIXME: This loses syntactic information.
5347   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5348   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5349                                               CK_BuiltinFnToFnPtr);
5350   TheCall->setCallee(PromotedCall.get());
5351 
5352   // Change the result type of the call to match the original value type. This
5353   // is arbitrary, but the codegen for these builtins ins design to handle it
5354   // gracefully.
5355   TheCall->setType(ResultType);
5356 
5357   // Prohibit use of _ExtInt with atomic builtins.
5358   // The arguments would have already been converted to the first argument's
5359   // type, so only need to check the first argument.
5360   const auto *ExtIntValType = ValType->getAs<ExtIntType>();
5361   if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) {
5362     Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
5363     return ExprError();
5364   }
5365 
5366   return TheCallResult;
5367 }
5368 
5369 /// SemaBuiltinNontemporalOverloaded - We have a call to
5370 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
5371 /// overloaded function based on the pointer type of its last argument.
5372 ///
5373 /// This function goes through and does final semantic checking for these
5374 /// builtins.
5375 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5376   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5377   DeclRefExpr *DRE =
5378       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5379   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5380   unsigned BuiltinID = FDecl->getBuiltinID();
5381   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5382           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5383          "Unexpected nontemporal load/store builtin!");
5384   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5385   unsigned numArgs = isStore ? 2 : 1;
5386 
5387   // Ensure that we have the proper number of arguments.
5388   if (checkArgCount(*this, TheCall, numArgs))
5389     return ExprError();
5390 
5391   // Inspect the last argument of the nontemporal builtin.  This should always
5392   // be a pointer type, from which we imply the type of the memory access.
5393   // Because it is a pointer type, we don't have to worry about any implicit
5394   // casts here.
5395   Expr *PointerArg = TheCall->getArg(numArgs - 1);
5396   ExprResult PointerArgResult =
5397       DefaultFunctionArrayLvalueConversion(PointerArg);
5398 
5399   if (PointerArgResult.isInvalid())
5400     return ExprError();
5401   PointerArg = PointerArgResult.get();
5402   TheCall->setArg(numArgs - 1, PointerArg);
5403 
5404   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5405   if (!pointerType) {
5406     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5407         << PointerArg->getType() << PointerArg->getSourceRange();
5408     return ExprError();
5409   }
5410 
5411   QualType ValType = pointerType->getPointeeType();
5412 
5413   // Strip any qualifiers off ValType.
5414   ValType = ValType.getUnqualifiedType();
5415   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5416       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5417       !ValType->isVectorType()) {
5418     Diag(DRE->getBeginLoc(),
5419          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5420         << PointerArg->getType() << PointerArg->getSourceRange();
5421     return ExprError();
5422   }
5423 
5424   if (!isStore) {
5425     TheCall->setType(ValType);
5426     return TheCallResult;
5427   }
5428 
5429   ExprResult ValArg = TheCall->getArg(0);
5430   InitializedEntity Entity = InitializedEntity::InitializeParameter(
5431       Context, ValType, /*consume*/ false);
5432   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5433   if (ValArg.isInvalid())
5434     return ExprError();
5435 
5436   TheCall->setArg(0, ValArg.get());
5437   TheCall->setType(Context.VoidTy);
5438   return TheCallResult;
5439 }
5440 
5441 /// CheckObjCString - Checks that the argument to the builtin
5442 /// CFString constructor is correct
5443 /// Note: It might also make sense to do the UTF-16 conversion here (would
5444 /// simplify the backend).
5445 bool Sema::CheckObjCString(Expr *Arg) {
5446   Arg = Arg->IgnoreParenCasts();
5447   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
5448 
5449   if (!Literal || !Literal->isAscii()) {
5450     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
5451         << Arg->getSourceRange();
5452     return true;
5453   }
5454 
5455   if (Literal->containsNonAsciiOrNull()) {
5456     StringRef String = Literal->getString();
5457     unsigned NumBytes = String.size();
5458     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
5459     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5460     llvm::UTF16 *ToPtr = &ToBuf[0];
5461 
5462     llvm::ConversionResult Result =
5463         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5464                                  ToPtr + NumBytes, llvm::strictConversion);
5465     // Check for conversion failure.
5466     if (Result != llvm::conversionOK)
5467       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
5468           << Arg->getSourceRange();
5469   }
5470   return false;
5471 }
5472 
5473 /// CheckObjCString - Checks that the format string argument to the os_log()
5474 /// and os_trace() functions is correct, and converts it to const char *.
5475 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5476   Arg = Arg->IgnoreParenCasts();
5477   auto *Literal = dyn_cast<StringLiteral>(Arg);
5478   if (!Literal) {
5479     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5480       Literal = ObjcLiteral->getString();
5481     }
5482   }
5483 
5484   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
5485     return ExprError(
5486         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5487         << Arg->getSourceRange());
5488   }
5489 
5490   ExprResult Result(Literal);
5491   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5492   InitializedEntity Entity =
5493       InitializedEntity::InitializeParameter(Context, ResultTy, false);
5494   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5495   return Result;
5496 }
5497 
5498 /// Check that the user is calling the appropriate va_start builtin for the
5499 /// target and calling convention.
5500 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5501   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5502   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5503   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
5504                     TT.getArch() == llvm::Triple::aarch64_32);
5505   bool IsWindows = TT.isOSWindows();
5506   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5507   if (IsX64 || IsAArch64) {
5508     CallingConv CC = CC_C;
5509     if (const FunctionDecl *FD = S.getCurFunctionDecl())
5510       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
5511     if (IsMSVAStart) {
5512       // Don't allow this in System V ABI functions.
5513       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
5514         return S.Diag(Fn->getBeginLoc(),
5515                       diag::err_ms_va_start_used_in_sysv_function);
5516     } else {
5517       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5518       // On x64 Windows, don't allow this in System V ABI functions.
5519       // (Yes, that means there's no corresponding way to support variadic
5520       // System V ABI functions on Windows.)
5521       if ((IsWindows && CC == CC_X86_64SysV) ||
5522           (!IsWindows && CC == CC_Win64))
5523         return S.Diag(Fn->getBeginLoc(),
5524                       diag::err_va_start_used_in_wrong_abi_function)
5525                << !IsWindows;
5526     }
5527     return false;
5528   }
5529 
5530   if (IsMSVAStart)
5531     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5532   return false;
5533 }
5534 
5535 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
5536                                              ParmVarDecl **LastParam = nullptr) {
5537   // Determine whether the current function, block, or obj-c method is variadic
5538   // and get its parameter list.
5539   bool IsVariadic = false;
5540   ArrayRef<ParmVarDecl *> Params;
5541   DeclContext *Caller = S.CurContext;
5542   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5543     IsVariadic = Block->isVariadic();
5544     Params = Block->parameters();
5545   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5546     IsVariadic = FD->isVariadic();
5547     Params = FD->parameters();
5548   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5549     IsVariadic = MD->isVariadic();
5550     // FIXME: This isn't correct for methods (results in bogus warning).
5551     Params = MD->parameters();
5552   } else if (isa<CapturedDecl>(Caller)) {
5553     // We don't support va_start in a CapturedDecl.
5554     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5555     return true;
5556   } else {
5557     // This must be some other declcontext that parses exprs.
5558     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5559     return true;
5560   }
5561 
5562   if (!IsVariadic) {
5563     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
5564     return true;
5565   }
5566 
5567   if (LastParam)
5568     *LastParam = Params.empty() ? nullptr : Params.back();
5569 
5570   return false;
5571 }
5572 
5573 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
5574 /// for validity.  Emit an error and return true on failure; return false
5575 /// on success.
5576 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5577   Expr *Fn = TheCall->getCallee();
5578 
5579   if (checkVAStartABI(*this, BuiltinID, Fn))
5580     return true;
5581 
5582   if (TheCall->getNumArgs() > 2) {
5583     Diag(TheCall->getArg(2)->getBeginLoc(),
5584          diag::err_typecheck_call_too_many_args)
5585         << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5586         << Fn->getSourceRange()
5587         << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5588                        (*(TheCall->arg_end() - 1))->getEndLoc());
5589     return true;
5590   }
5591 
5592   if (TheCall->getNumArgs() < 2) {
5593     return Diag(TheCall->getEndLoc(),
5594                 diag::err_typecheck_call_too_few_args_at_least)
5595            << 0 /*function call*/ << 2 << TheCall->getNumArgs();
5596   }
5597 
5598   // Type-check the first argument normally.
5599   if (checkBuiltinArgument(*this, TheCall, 0))
5600     return true;
5601 
5602   // Check that the current function is variadic, and get its last parameter.
5603   ParmVarDecl *LastParam;
5604   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5605     return true;
5606 
5607   // Verify that the second argument to the builtin is the last argument of the
5608   // current function or method.
5609   bool SecondArgIsLastNamedArgument = false;
5610   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5611 
5612   // These are valid if SecondArgIsLastNamedArgument is false after the next
5613   // block.
5614   QualType Type;
5615   SourceLocation ParamLoc;
5616   bool IsCRegister = false;
5617 
5618   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5619     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5620       SecondArgIsLastNamedArgument = PV == LastParam;
5621 
5622       Type = PV->getType();
5623       ParamLoc = PV->getLocation();
5624       IsCRegister =
5625           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5626     }
5627   }
5628 
5629   if (!SecondArgIsLastNamedArgument)
5630     Diag(TheCall->getArg(1)->getBeginLoc(),
5631          diag::warn_second_arg_of_va_start_not_last_named_param);
5632   else if (IsCRegister || Type->isReferenceType() ||
5633            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5634              // Promotable integers are UB, but enumerations need a bit of
5635              // extra checking to see what their promotable type actually is.
5636              if (!Type->isPromotableIntegerType())
5637                return false;
5638              if (!Type->isEnumeralType())
5639                return true;
5640              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
5641              return !(ED &&
5642                       Context.typesAreCompatible(ED->getPromotionType(), Type));
5643            }()) {
5644     unsigned Reason = 0;
5645     if (Type->isReferenceType())  Reason = 1;
5646     else if (IsCRegister)         Reason = 2;
5647     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
5648     Diag(ParamLoc, diag::note_parameter_type) << Type;
5649   }
5650 
5651   TheCall->setType(Context.VoidTy);
5652   return false;
5653 }
5654 
5655 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
5656   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5657   //                 const char *named_addr);
5658 
5659   Expr *Func = Call->getCallee();
5660 
5661   if (Call->getNumArgs() < 3)
5662     return Diag(Call->getEndLoc(),
5663                 diag::err_typecheck_call_too_few_args_at_least)
5664            << 0 /*function call*/ << 3 << Call->getNumArgs();
5665 
5666   // Type-check the first argument normally.
5667   if (checkBuiltinArgument(*this, Call, 0))
5668     return true;
5669 
5670   // Check that the current function is variadic.
5671   if (checkVAStartIsInVariadicFunction(*this, Func))
5672     return true;
5673 
5674   // __va_start on Windows does not validate the parameter qualifiers
5675 
5676   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5677   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5678 
5679   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5680   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5681 
5682   const QualType &ConstCharPtrTy =
5683       Context.getPointerType(Context.CharTy.withConst());
5684   if (!Arg1Ty->isPointerType() ||
5685       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
5686     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5687         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5688         << 0                                      /* qualifier difference */
5689         << 3                                      /* parameter mismatch */
5690         << 2 << Arg1->getType() << ConstCharPtrTy;
5691 
5692   const QualType SizeTy = Context.getSizeType();
5693   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
5694     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5695         << Arg2->getType() << SizeTy << 1 /* different class */
5696         << 0                              /* qualifier difference */
5697         << 3                              /* parameter mismatch */
5698         << 3 << Arg2->getType() << SizeTy;
5699 
5700   return false;
5701 }
5702 
5703 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
5704 /// friends.  This is declared to take (...), so we have to check everything.
5705 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
5706   if (TheCall->getNumArgs() < 2)
5707     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5708            << 0 << 2 << TheCall->getNumArgs() /*function call*/;
5709   if (TheCall->getNumArgs() > 2)
5710     return Diag(TheCall->getArg(2)->getBeginLoc(),
5711                 diag::err_typecheck_call_too_many_args)
5712            << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5713            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5714                           (*(TheCall->arg_end() - 1))->getEndLoc());
5715 
5716   ExprResult OrigArg0 = TheCall->getArg(0);
5717   ExprResult OrigArg1 = TheCall->getArg(1);
5718 
5719   // Do standard promotions between the two arguments, returning their common
5720   // type.
5721   QualType Res = UsualArithmeticConversions(
5722       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
5723   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5724     return true;
5725 
5726   // Make sure any conversions are pushed back into the call; this is
5727   // type safe since unordered compare builtins are declared as "_Bool
5728   // foo(...)".
5729   TheCall->setArg(0, OrigArg0.get());
5730   TheCall->setArg(1, OrigArg1.get());
5731 
5732   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5733     return false;
5734 
5735   // If the common type isn't a real floating type, then the arguments were
5736   // invalid for this operation.
5737   if (Res.isNull() || !Res->isRealFloatingType())
5738     return Diag(OrigArg0.get()->getBeginLoc(),
5739                 diag::err_typecheck_call_invalid_ordered_compare)
5740            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5741            << SourceRange(OrigArg0.get()->getBeginLoc(),
5742                           OrigArg1.get()->getEndLoc());
5743 
5744   return false;
5745 }
5746 
5747 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
5748 /// __builtin_isnan and friends.  This is declared to take (...), so we have
5749 /// to check everything. We expect the last argument to be a floating point
5750 /// value.
5751 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
5752   if (TheCall->getNumArgs() < NumArgs)
5753     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5754            << 0 << NumArgs << TheCall->getNumArgs() /*function call*/;
5755   if (TheCall->getNumArgs() > NumArgs)
5756     return Diag(TheCall->getArg(NumArgs)->getBeginLoc(),
5757                 diag::err_typecheck_call_too_many_args)
5758            << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
5759            << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(),
5760                           (*(TheCall->arg_end() - 1))->getEndLoc());
5761 
5762   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
5763   // on all preceding parameters just being int.  Try all of those.
5764   for (unsigned i = 0; i < NumArgs - 1; ++i) {
5765     Expr *Arg = TheCall->getArg(i);
5766 
5767     if (Arg->isTypeDependent())
5768       return false;
5769 
5770     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
5771 
5772     if (Res.isInvalid())
5773       return true;
5774     TheCall->setArg(i, Res.get());
5775   }
5776 
5777   Expr *OrigArg = TheCall->getArg(NumArgs-1);
5778 
5779   if (OrigArg->isTypeDependent())
5780     return false;
5781 
5782   // Usual Unary Conversions will convert half to float, which we want for
5783   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
5784   // type how it is, but do normal L->Rvalue conversions.
5785   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
5786     OrigArg = UsualUnaryConversions(OrigArg).get();
5787   else
5788     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
5789   TheCall->setArg(NumArgs - 1, OrigArg);
5790 
5791   // This operation requires a non-_Complex floating-point number.
5792   if (!OrigArg->getType()->isRealFloatingType())
5793     return Diag(OrigArg->getBeginLoc(),
5794                 diag::err_typecheck_call_invalid_unary_fp)
5795            << OrigArg->getType() << OrigArg->getSourceRange();
5796 
5797   return false;
5798 }
5799 
5800 // Customized Sema Checking for VSX builtins that have the following signature:
5801 // vector [...] builtinName(vector [...], vector [...], const int);
5802 // Which takes the same type of vectors (any legal vector type) for the first
5803 // two arguments and takes compile time constant for the third argument.
5804 // Example builtins are :
5805 // vector double vec_xxpermdi(vector double, vector double, int);
5806 // vector short vec_xxsldwi(vector short, vector short, int);
5807 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
5808   unsigned ExpectedNumArgs = 3;
5809   if (TheCall->getNumArgs() < ExpectedNumArgs)
5810     return Diag(TheCall->getEndLoc(),
5811                 diag::err_typecheck_call_too_few_args_at_least)
5812            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5813            << TheCall->getSourceRange();
5814 
5815   if (TheCall->getNumArgs() > ExpectedNumArgs)
5816     return Diag(TheCall->getEndLoc(),
5817                 diag::err_typecheck_call_too_many_args_at_most)
5818            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5819            << TheCall->getSourceRange();
5820 
5821   // Check the third argument is a compile time constant
5822   llvm::APSInt Value;
5823   if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
5824     return Diag(TheCall->getBeginLoc(),
5825                 diag::err_vsx_builtin_nonconstant_argument)
5826            << 3 /* argument index */ << TheCall->getDirectCallee()
5827            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5828                           TheCall->getArg(2)->getEndLoc());
5829 
5830   QualType Arg1Ty = TheCall->getArg(0)->getType();
5831   QualType Arg2Ty = TheCall->getArg(1)->getType();
5832 
5833   // Check the type of argument 1 and argument 2 are vectors.
5834   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
5835   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
5836       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
5837     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
5838            << TheCall->getDirectCallee()
5839            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5840                           TheCall->getArg(1)->getEndLoc());
5841   }
5842 
5843   // Check the first two arguments are the same type.
5844   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
5845     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
5846            << TheCall->getDirectCallee()
5847            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5848                           TheCall->getArg(1)->getEndLoc());
5849   }
5850 
5851   // When default clang type checking is turned off and the customized type
5852   // checking is used, the returning type of the function must be explicitly
5853   // set. Otherwise it is _Bool by default.
5854   TheCall->setType(Arg1Ty);
5855 
5856   return false;
5857 }
5858 
5859 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
5860 // This is declared to take (...), so we have to check everything.
5861 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
5862   if (TheCall->getNumArgs() < 2)
5863     return ExprError(Diag(TheCall->getEndLoc(),
5864                           diag::err_typecheck_call_too_few_args_at_least)
5865                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5866                      << TheCall->getSourceRange());
5867 
5868   // Determine which of the following types of shufflevector we're checking:
5869   // 1) unary, vector mask: (lhs, mask)
5870   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
5871   QualType resType = TheCall->getArg(0)->getType();
5872   unsigned numElements = 0;
5873 
5874   if (!TheCall->getArg(0)->isTypeDependent() &&
5875       !TheCall->getArg(1)->isTypeDependent()) {
5876     QualType LHSType = TheCall->getArg(0)->getType();
5877     QualType RHSType = TheCall->getArg(1)->getType();
5878 
5879     if (!LHSType->isVectorType() || !RHSType->isVectorType())
5880       return ExprError(
5881           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
5882           << TheCall->getDirectCallee()
5883           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5884                          TheCall->getArg(1)->getEndLoc()));
5885 
5886     numElements = LHSType->castAs<VectorType>()->getNumElements();
5887     unsigned numResElements = TheCall->getNumArgs() - 2;
5888 
5889     // Check to see if we have a call with 2 vector arguments, the unary shuffle
5890     // with mask.  If so, verify that RHS is an integer vector type with the
5891     // same number of elts as lhs.
5892     if (TheCall->getNumArgs() == 2) {
5893       if (!RHSType->hasIntegerRepresentation() ||
5894           RHSType->castAs<VectorType>()->getNumElements() != numElements)
5895         return ExprError(Diag(TheCall->getBeginLoc(),
5896                               diag::err_vec_builtin_incompatible_vector)
5897                          << TheCall->getDirectCallee()
5898                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
5899                                         TheCall->getArg(1)->getEndLoc()));
5900     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
5901       return ExprError(Diag(TheCall->getBeginLoc(),
5902                             diag::err_vec_builtin_incompatible_vector)
5903                        << TheCall->getDirectCallee()
5904                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5905                                       TheCall->getArg(1)->getEndLoc()));
5906     } else if (numElements != numResElements) {
5907       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
5908       resType = Context.getVectorType(eltType, numResElements,
5909                                       VectorType::GenericVector);
5910     }
5911   }
5912 
5913   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
5914     if (TheCall->getArg(i)->isTypeDependent() ||
5915         TheCall->getArg(i)->isValueDependent())
5916       continue;
5917 
5918     llvm::APSInt Result(32);
5919     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
5920       return ExprError(Diag(TheCall->getBeginLoc(),
5921                             diag::err_shufflevector_nonconstant_argument)
5922                        << TheCall->getArg(i)->getSourceRange());
5923 
5924     // Allow -1 which will be translated to undef in the IR.
5925     if (Result.isSigned() && Result.isAllOnesValue())
5926       continue;
5927 
5928     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
5929       return ExprError(Diag(TheCall->getBeginLoc(),
5930                             diag::err_shufflevector_argument_too_large)
5931                        << TheCall->getArg(i)->getSourceRange());
5932   }
5933 
5934   SmallVector<Expr*, 32> exprs;
5935 
5936   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
5937     exprs.push_back(TheCall->getArg(i));
5938     TheCall->setArg(i, nullptr);
5939   }
5940 
5941   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
5942                                          TheCall->getCallee()->getBeginLoc(),
5943                                          TheCall->getRParenLoc());
5944 }
5945 
5946 /// SemaConvertVectorExpr - Handle __builtin_convertvector
5947 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
5948                                        SourceLocation BuiltinLoc,
5949                                        SourceLocation RParenLoc) {
5950   ExprValueKind VK = VK_RValue;
5951   ExprObjectKind OK = OK_Ordinary;
5952   QualType DstTy = TInfo->getType();
5953   QualType SrcTy = E->getType();
5954 
5955   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
5956     return ExprError(Diag(BuiltinLoc,
5957                           diag::err_convertvector_non_vector)
5958                      << E->getSourceRange());
5959   if (!DstTy->isVectorType() && !DstTy->isDependentType())
5960     return ExprError(Diag(BuiltinLoc,
5961                           diag::err_convertvector_non_vector_type));
5962 
5963   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
5964     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
5965     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
5966     if (SrcElts != DstElts)
5967       return ExprError(Diag(BuiltinLoc,
5968                             diag::err_convertvector_incompatible_vector)
5969                        << E->getSourceRange());
5970   }
5971 
5972   return new (Context)
5973       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5974 }
5975 
5976 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
5977 // This is declared to take (const void*, ...) and can take two
5978 // optional constant int args.
5979 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
5980   unsigned NumArgs = TheCall->getNumArgs();
5981 
5982   if (NumArgs > 3)
5983     return Diag(TheCall->getEndLoc(),
5984                 diag::err_typecheck_call_too_many_args_at_most)
5985            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
5986 
5987   // Argument 0 is checked for us and the remaining arguments must be
5988   // constant integers.
5989   for (unsigned i = 1; i != NumArgs; ++i)
5990     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
5991       return true;
5992 
5993   return false;
5994 }
5995 
5996 /// SemaBuiltinAssume - Handle __assume (MS Extension).
5997 // __assume does not evaluate its arguments, and should warn if its argument
5998 // has side effects.
5999 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
6000   Expr *Arg = TheCall->getArg(0);
6001   if (Arg->isInstantiationDependent()) return false;
6002 
6003   if (Arg->HasSideEffects(Context))
6004     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6005         << Arg->getSourceRange()
6006         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
6007 
6008   return false;
6009 }
6010 
6011 /// Handle __builtin_alloca_with_align. This is declared
6012 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
6013 /// than 8.
6014 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
6015   // The alignment must be a constant integer.
6016   Expr *Arg = TheCall->getArg(1);
6017 
6018   // We can't check the value of a dependent argument.
6019   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6020     if (const auto *UE =
6021             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6022       if (UE->getKind() == UETT_AlignOf ||
6023           UE->getKind() == UETT_PreferredAlignOf)
6024         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6025             << Arg->getSourceRange();
6026 
6027     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6028 
6029     if (!Result.isPowerOf2())
6030       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6031              << Arg->getSourceRange();
6032 
6033     if (Result < Context.getCharWidth())
6034       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6035              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6036 
6037     if (Result > std::numeric_limits<int32_t>::max())
6038       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6039              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6040   }
6041 
6042   return false;
6043 }
6044 
6045 /// Handle __builtin_assume_aligned. This is declared
6046 /// as (const void*, size_t, ...) and can take one optional constant int arg.
6047 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
6048   unsigned NumArgs = TheCall->getNumArgs();
6049 
6050   if (NumArgs > 3)
6051     return Diag(TheCall->getEndLoc(),
6052                 diag::err_typecheck_call_too_many_args_at_most)
6053            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6054 
6055   // The alignment must be a constant integer.
6056   Expr *Arg = TheCall->getArg(1);
6057 
6058   // We can't check the value of a dependent argument.
6059   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6060     llvm::APSInt Result;
6061     if (SemaBuiltinConstantArg(TheCall, 1, Result))
6062       return true;
6063 
6064     if (!Result.isPowerOf2())
6065       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6066              << Arg->getSourceRange();
6067 
6068     if (Result > Sema::MaximumAlignment)
6069       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6070           << Arg->getSourceRange() << Sema::MaximumAlignment;
6071   }
6072 
6073   if (NumArgs > 2) {
6074     ExprResult Arg(TheCall->getArg(2));
6075     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6076       Context.getSizeType(), false);
6077     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6078     if (Arg.isInvalid()) return true;
6079     TheCall->setArg(2, Arg.get());
6080   }
6081 
6082   return false;
6083 }
6084 
6085 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
6086   unsigned BuiltinID =
6087       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6088   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6089 
6090   unsigned NumArgs = TheCall->getNumArgs();
6091   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6092   if (NumArgs < NumRequiredArgs) {
6093     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6094            << 0 /* function call */ << NumRequiredArgs << NumArgs
6095            << TheCall->getSourceRange();
6096   }
6097   if (NumArgs >= NumRequiredArgs + 0x100) {
6098     return Diag(TheCall->getEndLoc(),
6099                 diag::err_typecheck_call_too_many_args_at_most)
6100            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6101            << TheCall->getSourceRange();
6102   }
6103   unsigned i = 0;
6104 
6105   // For formatting call, check buffer arg.
6106   if (!IsSizeCall) {
6107     ExprResult Arg(TheCall->getArg(i));
6108     InitializedEntity Entity = InitializedEntity::InitializeParameter(
6109         Context, Context.VoidPtrTy, false);
6110     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6111     if (Arg.isInvalid())
6112       return true;
6113     TheCall->setArg(i, Arg.get());
6114     i++;
6115   }
6116 
6117   // Check string literal arg.
6118   unsigned FormatIdx = i;
6119   {
6120     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6121     if (Arg.isInvalid())
6122       return true;
6123     TheCall->setArg(i, Arg.get());
6124     i++;
6125   }
6126 
6127   // Make sure variadic args are scalar.
6128   unsigned FirstDataArg = i;
6129   while (i < NumArgs) {
6130     ExprResult Arg = DefaultVariadicArgumentPromotion(
6131         TheCall->getArg(i), VariadicFunction, nullptr);
6132     if (Arg.isInvalid())
6133       return true;
6134     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6135     if (ArgSize.getQuantity() >= 0x100) {
6136       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6137              << i << (int)ArgSize.getQuantity() << 0xff
6138              << TheCall->getSourceRange();
6139     }
6140     TheCall->setArg(i, Arg.get());
6141     i++;
6142   }
6143 
6144   // Check formatting specifiers. NOTE: We're only doing this for the non-size
6145   // call to avoid duplicate diagnostics.
6146   if (!IsSizeCall) {
6147     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6148     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6149     bool Success = CheckFormatArguments(
6150         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
6151         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
6152         CheckedVarArgs);
6153     if (!Success)
6154       return true;
6155   }
6156 
6157   if (IsSizeCall) {
6158     TheCall->setType(Context.getSizeType());
6159   } else {
6160     TheCall->setType(Context.VoidPtrTy);
6161   }
6162   return false;
6163 }
6164 
6165 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
6166 /// TheCall is a constant expression.
6167 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
6168                                   llvm::APSInt &Result) {
6169   Expr *Arg = TheCall->getArg(ArgNum);
6170   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6171   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6172 
6173   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
6174 
6175   if (!Arg->isIntegerConstantExpr(Result, Context))
6176     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6177            << FDecl->getDeclName() << Arg->getSourceRange();
6178 
6179   return false;
6180 }
6181 
6182 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
6183 /// TheCall is a constant expression in the range [Low, High].
6184 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
6185                                        int Low, int High, bool RangeIsError) {
6186   if (isConstantEvaluated())
6187     return false;
6188   llvm::APSInt Result;
6189 
6190   // We can't check the value of a dependent argument.
6191   Expr *Arg = TheCall->getArg(ArgNum);
6192   if (Arg->isTypeDependent() || Arg->isValueDependent())
6193     return false;
6194 
6195   // Check constant-ness first.
6196   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6197     return true;
6198 
6199   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6200     if (RangeIsError)
6201       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6202              << Result.toString(10) << Low << High << Arg->getSourceRange();
6203     else
6204       // Defer the warning until we know if the code will be emitted so that
6205       // dead code can ignore this.
6206       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6207                           PDiag(diag::warn_argument_invalid_range)
6208                               << Result.toString(10) << Low << High
6209                               << Arg->getSourceRange());
6210   }
6211 
6212   return false;
6213 }
6214 
6215 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
6216 /// TheCall is a constant expression is a multiple of Num..
6217 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
6218                                           unsigned Num) {
6219   llvm::APSInt Result;
6220 
6221   // We can't check the value of a dependent argument.
6222   Expr *Arg = TheCall->getArg(ArgNum);
6223   if (Arg->isTypeDependent() || Arg->isValueDependent())
6224     return false;
6225 
6226   // Check constant-ness first.
6227   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6228     return true;
6229 
6230   if (Result.getSExtValue() % Num != 0)
6231     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6232            << Num << Arg->getSourceRange();
6233 
6234   return false;
6235 }
6236 
6237 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
6238 /// constant expression representing a power of 2.
6239 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
6240   llvm::APSInt Result;
6241 
6242   // We can't check the value of a dependent argument.
6243   Expr *Arg = TheCall->getArg(ArgNum);
6244   if (Arg->isTypeDependent() || Arg->isValueDependent())
6245     return false;
6246 
6247   // Check constant-ness first.
6248   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6249     return true;
6250 
6251   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
6252   // and only if x is a power of 2.
6253   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
6254     return false;
6255 
6256   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
6257          << Arg->getSourceRange();
6258 }
6259 
6260 static bool IsShiftedByte(llvm::APSInt Value) {
6261   if (Value.isNegative())
6262     return false;
6263 
6264   // Check if it's a shifted byte, by shifting it down
6265   while (true) {
6266     // If the value fits in the bottom byte, the check passes.
6267     if (Value < 0x100)
6268       return true;
6269 
6270     // Otherwise, if the value has _any_ bits in the bottom byte, the check
6271     // fails.
6272     if ((Value & 0xFF) != 0)
6273       return false;
6274 
6275     // If the bottom 8 bits are all 0, but something above that is nonzero,
6276     // then shifting the value right by 8 bits won't affect whether it's a
6277     // shifted byte or not. So do that, and go round again.
6278     Value >>= 8;
6279   }
6280 }
6281 
6282 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
6283 /// a constant expression representing an arbitrary byte value shifted left by
6284 /// a multiple of 8 bits.
6285 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
6286                                              unsigned ArgBits) {
6287   llvm::APSInt Result;
6288 
6289   // We can't check the value of a dependent argument.
6290   Expr *Arg = TheCall->getArg(ArgNum);
6291   if (Arg->isTypeDependent() || Arg->isValueDependent())
6292     return false;
6293 
6294   // Check constant-ness first.
6295   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6296     return true;
6297 
6298   // Truncate to the given size.
6299   Result = Result.getLoBits(ArgBits);
6300   Result.setIsUnsigned(true);
6301 
6302   if (IsShiftedByte(Result))
6303     return false;
6304 
6305   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
6306          << Arg->getSourceRange();
6307 }
6308 
6309 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
6310 /// TheCall is a constant expression representing either a shifted byte value,
6311 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
6312 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
6313 /// Arm MVE intrinsics.
6314 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
6315                                                    int ArgNum,
6316                                                    unsigned ArgBits) {
6317   llvm::APSInt Result;
6318 
6319   // We can't check the value of a dependent argument.
6320   Expr *Arg = TheCall->getArg(ArgNum);
6321   if (Arg->isTypeDependent() || Arg->isValueDependent())
6322     return false;
6323 
6324   // Check constant-ness first.
6325   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6326     return true;
6327 
6328   // Truncate to the given size.
6329   Result = Result.getLoBits(ArgBits);
6330   Result.setIsUnsigned(true);
6331 
6332   // Check to see if it's in either of the required forms.
6333   if (IsShiftedByte(Result) ||
6334       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
6335     return false;
6336 
6337   return Diag(TheCall->getBeginLoc(),
6338               diag::err_argument_not_shifted_byte_or_xxff)
6339          << Arg->getSourceRange();
6340 }
6341 
6342 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
6343 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
6344   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
6345     if (checkArgCount(*this, TheCall, 2))
6346       return true;
6347     Expr *Arg0 = TheCall->getArg(0);
6348     Expr *Arg1 = TheCall->getArg(1);
6349 
6350     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6351     if (FirstArg.isInvalid())
6352       return true;
6353     QualType FirstArgType = FirstArg.get()->getType();
6354     if (!FirstArgType->isAnyPointerType())
6355       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6356                << "first" << FirstArgType << Arg0->getSourceRange();
6357     TheCall->setArg(0, FirstArg.get());
6358 
6359     ExprResult SecArg = DefaultLvalueConversion(Arg1);
6360     if (SecArg.isInvalid())
6361       return true;
6362     QualType SecArgType = SecArg.get()->getType();
6363     if (!SecArgType->isIntegerType())
6364       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6365                << "second" << SecArgType << Arg1->getSourceRange();
6366 
6367     // Derive the return type from the pointer argument.
6368     TheCall->setType(FirstArgType);
6369     return false;
6370   }
6371 
6372   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
6373     if (checkArgCount(*this, TheCall, 2))
6374       return true;
6375 
6376     Expr *Arg0 = TheCall->getArg(0);
6377     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6378     if (FirstArg.isInvalid())
6379       return true;
6380     QualType FirstArgType = FirstArg.get()->getType();
6381     if (!FirstArgType->isAnyPointerType())
6382       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6383                << "first" << FirstArgType << Arg0->getSourceRange();
6384     TheCall->setArg(0, FirstArg.get());
6385 
6386     // Derive the return type from the pointer argument.
6387     TheCall->setType(FirstArgType);
6388 
6389     // Second arg must be an constant in range [0,15]
6390     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6391   }
6392 
6393   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
6394     if (checkArgCount(*this, TheCall, 2))
6395       return true;
6396     Expr *Arg0 = TheCall->getArg(0);
6397     Expr *Arg1 = TheCall->getArg(1);
6398 
6399     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6400     if (FirstArg.isInvalid())
6401       return true;
6402     QualType FirstArgType = FirstArg.get()->getType();
6403     if (!FirstArgType->isAnyPointerType())
6404       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6405                << "first" << FirstArgType << Arg0->getSourceRange();
6406 
6407     QualType SecArgType = Arg1->getType();
6408     if (!SecArgType->isIntegerType())
6409       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6410                << "second" << SecArgType << Arg1->getSourceRange();
6411     TheCall->setType(Context.IntTy);
6412     return false;
6413   }
6414 
6415   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
6416       BuiltinID == AArch64::BI__builtin_arm_stg) {
6417     if (checkArgCount(*this, TheCall, 1))
6418       return true;
6419     Expr *Arg0 = TheCall->getArg(0);
6420     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6421     if (FirstArg.isInvalid())
6422       return true;
6423 
6424     QualType FirstArgType = FirstArg.get()->getType();
6425     if (!FirstArgType->isAnyPointerType())
6426       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6427                << "first" << FirstArgType << Arg0->getSourceRange();
6428     TheCall->setArg(0, FirstArg.get());
6429 
6430     // Derive the return type from the pointer argument.
6431     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
6432       TheCall->setType(FirstArgType);
6433     return false;
6434   }
6435 
6436   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
6437     Expr *ArgA = TheCall->getArg(0);
6438     Expr *ArgB = TheCall->getArg(1);
6439 
6440     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
6441     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
6442 
6443     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
6444       return true;
6445 
6446     QualType ArgTypeA = ArgExprA.get()->getType();
6447     QualType ArgTypeB = ArgExprB.get()->getType();
6448 
6449     auto isNull = [&] (Expr *E) -> bool {
6450       return E->isNullPointerConstant(
6451                         Context, Expr::NPC_ValueDependentIsNotNull); };
6452 
6453     // argument should be either a pointer or null
6454     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
6455       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6456         << "first" << ArgTypeA << ArgA->getSourceRange();
6457 
6458     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
6459       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6460         << "second" << ArgTypeB << ArgB->getSourceRange();
6461 
6462     // Ensure Pointee types are compatible
6463     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
6464         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
6465       QualType pointeeA = ArgTypeA->getPointeeType();
6466       QualType pointeeB = ArgTypeB->getPointeeType();
6467       if (!Context.typesAreCompatible(
6468              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
6469              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
6470         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
6471           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
6472           << ArgB->getSourceRange();
6473       }
6474     }
6475 
6476     // at least one argument should be pointer type
6477     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
6478       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
6479         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
6480 
6481     if (isNull(ArgA)) // adopt type of the other pointer
6482       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
6483 
6484     if (isNull(ArgB))
6485       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
6486 
6487     TheCall->setArg(0, ArgExprA.get());
6488     TheCall->setArg(1, ArgExprB.get());
6489     TheCall->setType(Context.LongLongTy);
6490     return false;
6491   }
6492   assert(false && "Unhandled ARM MTE intrinsic");
6493   return true;
6494 }
6495 
6496 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
6497 /// TheCall is an ARM/AArch64 special register string literal.
6498 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
6499                                     int ArgNum, unsigned ExpectedFieldNum,
6500                                     bool AllowName) {
6501   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
6502                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
6503                       BuiltinID == ARM::BI__builtin_arm_rsr ||
6504                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
6505                       BuiltinID == ARM::BI__builtin_arm_wsr ||
6506                       BuiltinID == ARM::BI__builtin_arm_wsrp;
6507   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
6508                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
6509                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
6510                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
6511                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
6512                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
6513   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
6514 
6515   // We can't check the value of a dependent argument.
6516   Expr *Arg = TheCall->getArg(ArgNum);
6517   if (Arg->isTypeDependent() || Arg->isValueDependent())
6518     return false;
6519 
6520   // Check if the argument is a string literal.
6521   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
6522     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
6523            << Arg->getSourceRange();
6524 
6525   // Check the type of special register given.
6526   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
6527   SmallVector<StringRef, 6> Fields;
6528   Reg.split(Fields, ":");
6529 
6530   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
6531     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6532            << Arg->getSourceRange();
6533 
6534   // If the string is the name of a register then we cannot check that it is
6535   // valid here but if the string is of one the forms described in ACLE then we
6536   // can check that the supplied fields are integers and within the valid
6537   // ranges.
6538   if (Fields.size() > 1) {
6539     bool FiveFields = Fields.size() == 5;
6540 
6541     bool ValidString = true;
6542     if (IsARMBuiltin) {
6543       ValidString &= Fields[0].startswith_lower("cp") ||
6544                      Fields[0].startswith_lower("p");
6545       if (ValidString)
6546         Fields[0] =
6547           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
6548 
6549       ValidString &= Fields[2].startswith_lower("c");
6550       if (ValidString)
6551         Fields[2] = Fields[2].drop_front(1);
6552 
6553       if (FiveFields) {
6554         ValidString &= Fields[3].startswith_lower("c");
6555         if (ValidString)
6556           Fields[3] = Fields[3].drop_front(1);
6557       }
6558     }
6559 
6560     SmallVector<int, 5> Ranges;
6561     if (FiveFields)
6562       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
6563     else
6564       Ranges.append({15, 7, 15});
6565 
6566     for (unsigned i=0; i<Fields.size(); ++i) {
6567       int IntField;
6568       ValidString &= !Fields[i].getAsInteger(10, IntField);
6569       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
6570     }
6571 
6572     if (!ValidString)
6573       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6574              << Arg->getSourceRange();
6575   } else if (IsAArch64Builtin && Fields.size() == 1) {
6576     // If the register name is one of those that appear in the condition below
6577     // and the special register builtin being used is one of the write builtins,
6578     // then we require that the argument provided for writing to the register
6579     // is an integer constant expression. This is because it will be lowered to
6580     // an MSR (immediate) instruction, so we need to know the immediate at
6581     // compile time.
6582     if (TheCall->getNumArgs() != 2)
6583       return false;
6584 
6585     std::string RegLower = Reg.lower();
6586     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
6587         RegLower != "pan" && RegLower != "uao")
6588       return false;
6589 
6590     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6591   }
6592 
6593   return false;
6594 }
6595 
6596 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
6597 /// This checks that the target supports __builtin_longjmp and
6598 /// that val is a constant 1.
6599 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
6600   if (!Context.getTargetInfo().hasSjLjLowering())
6601     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
6602            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6603 
6604   Expr *Arg = TheCall->getArg(1);
6605   llvm::APSInt Result;
6606 
6607   // TODO: This is less than ideal. Overload this to take a value.
6608   if (SemaBuiltinConstantArg(TheCall, 1, Result))
6609     return true;
6610 
6611   if (Result != 1)
6612     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
6613            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6614 
6615   return false;
6616 }
6617 
6618 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
6619 /// This checks that the target supports __builtin_setjmp.
6620 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
6621   if (!Context.getTargetInfo().hasSjLjLowering())
6622     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
6623            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6624   return false;
6625 }
6626 
6627 namespace {
6628 
6629 class UncoveredArgHandler {
6630   enum { Unknown = -1, AllCovered = -2 };
6631 
6632   signed FirstUncoveredArg = Unknown;
6633   SmallVector<const Expr *, 4> DiagnosticExprs;
6634 
6635 public:
6636   UncoveredArgHandler() = default;
6637 
6638   bool hasUncoveredArg() const {
6639     return (FirstUncoveredArg >= 0);
6640   }
6641 
6642   unsigned getUncoveredArg() const {
6643     assert(hasUncoveredArg() && "no uncovered argument");
6644     return FirstUncoveredArg;
6645   }
6646 
6647   void setAllCovered() {
6648     // A string has been found with all arguments covered, so clear out
6649     // the diagnostics.
6650     DiagnosticExprs.clear();
6651     FirstUncoveredArg = AllCovered;
6652   }
6653 
6654   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6655     assert(NewFirstUncoveredArg >= 0 && "Outside range");
6656 
6657     // Don't update if a previous string covers all arguments.
6658     if (FirstUncoveredArg == AllCovered)
6659       return;
6660 
6661     // UncoveredArgHandler tracks the highest uncovered argument index
6662     // and with it all the strings that match this index.
6663     if (NewFirstUncoveredArg == FirstUncoveredArg)
6664       DiagnosticExprs.push_back(StrExpr);
6665     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6666       DiagnosticExprs.clear();
6667       DiagnosticExprs.push_back(StrExpr);
6668       FirstUncoveredArg = NewFirstUncoveredArg;
6669     }
6670   }
6671 
6672   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6673 };
6674 
6675 enum StringLiteralCheckType {
6676   SLCT_NotALiteral,
6677   SLCT_UncheckedLiteral,
6678   SLCT_CheckedLiteral
6679 };
6680 
6681 } // namespace
6682 
6683 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6684                                      BinaryOperatorKind BinOpKind,
6685                                      bool AddendIsRight) {
6686   unsigned BitWidth = Offset.getBitWidth();
6687   unsigned AddendBitWidth = Addend.getBitWidth();
6688   // There might be negative interim results.
6689   if (Addend.isUnsigned()) {
6690     Addend = Addend.zext(++AddendBitWidth);
6691     Addend.setIsSigned(true);
6692   }
6693   // Adjust the bit width of the APSInts.
6694   if (AddendBitWidth > BitWidth) {
6695     Offset = Offset.sext(AddendBitWidth);
6696     BitWidth = AddendBitWidth;
6697   } else if (BitWidth > AddendBitWidth) {
6698     Addend = Addend.sext(BitWidth);
6699   }
6700 
6701   bool Ov = false;
6702   llvm::APSInt ResOffset = Offset;
6703   if (BinOpKind == BO_Add)
6704     ResOffset = Offset.sadd_ov(Addend, Ov);
6705   else {
6706     assert(AddendIsRight && BinOpKind == BO_Sub &&
6707            "operator must be add or sub with addend on the right");
6708     ResOffset = Offset.ssub_ov(Addend, Ov);
6709   }
6710 
6711   // We add an offset to a pointer here so we should support an offset as big as
6712   // possible.
6713   if (Ov) {
6714     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6715            "index (intermediate) result too big");
6716     Offset = Offset.sext(2 * BitWidth);
6717     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6718     return;
6719   }
6720 
6721   Offset = ResOffset;
6722 }
6723 
6724 namespace {
6725 
6726 // This is a wrapper class around StringLiteral to support offsetted string
6727 // literals as format strings. It takes the offset into account when returning
6728 // the string and its length or the source locations to display notes correctly.
6729 class FormatStringLiteral {
6730   const StringLiteral *FExpr;
6731   int64_t Offset;
6732 
6733  public:
6734   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
6735       : FExpr(fexpr), Offset(Offset) {}
6736 
6737   StringRef getString() const {
6738     return FExpr->getString().drop_front(Offset);
6739   }
6740 
6741   unsigned getByteLength() const {
6742     return FExpr->getByteLength() - getCharByteWidth() * Offset;
6743   }
6744 
6745   unsigned getLength() const { return FExpr->getLength() - Offset; }
6746   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
6747 
6748   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
6749 
6750   QualType getType() const { return FExpr->getType(); }
6751 
6752   bool isAscii() const { return FExpr->isAscii(); }
6753   bool isWide() const { return FExpr->isWide(); }
6754   bool isUTF8() const { return FExpr->isUTF8(); }
6755   bool isUTF16() const { return FExpr->isUTF16(); }
6756   bool isUTF32() const { return FExpr->isUTF32(); }
6757   bool isPascal() const { return FExpr->isPascal(); }
6758 
6759   SourceLocation getLocationOfByte(
6760       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
6761       const TargetInfo &Target, unsigned *StartToken = nullptr,
6762       unsigned *StartTokenByteOffset = nullptr) const {
6763     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
6764                                     StartToken, StartTokenByteOffset);
6765   }
6766 
6767   SourceLocation getBeginLoc() const LLVM_READONLY {
6768     return FExpr->getBeginLoc().getLocWithOffset(Offset);
6769   }
6770 
6771   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
6772 };
6773 
6774 }  // namespace
6775 
6776 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
6777                               const Expr *OrigFormatExpr,
6778                               ArrayRef<const Expr *> Args,
6779                               bool HasVAListArg, unsigned format_idx,
6780                               unsigned firstDataArg,
6781                               Sema::FormatStringType Type,
6782                               bool inFunctionCall,
6783                               Sema::VariadicCallType CallType,
6784                               llvm::SmallBitVector &CheckedVarArgs,
6785                               UncoveredArgHandler &UncoveredArg,
6786                               bool IgnoreStringsWithoutSpecifiers);
6787 
6788 // Determine if an expression is a string literal or constant string.
6789 // If this function returns false on the arguments to a function expecting a
6790 // format string, we will usually need to emit a warning.
6791 // True string literals are then checked by CheckFormatString.
6792 static StringLiteralCheckType
6793 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
6794                       bool HasVAListArg, unsigned format_idx,
6795                       unsigned firstDataArg, Sema::FormatStringType Type,
6796                       Sema::VariadicCallType CallType, bool InFunctionCall,
6797                       llvm::SmallBitVector &CheckedVarArgs,
6798                       UncoveredArgHandler &UncoveredArg,
6799                       llvm::APSInt Offset,
6800                       bool IgnoreStringsWithoutSpecifiers = false) {
6801   if (S.isConstantEvaluated())
6802     return SLCT_NotALiteral;
6803  tryAgain:
6804   assert(Offset.isSigned() && "invalid offset");
6805 
6806   if (E->isTypeDependent() || E->isValueDependent())
6807     return SLCT_NotALiteral;
6808 
6809   E = E->IgnoreParenCasts();
6810 
6811   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
6812     // Technically -Wformat-nonliteral does not warn about this case.
6813     // The behavior of printf and friends in this case is implementation
6814     // dependent.  Ideally if the format string cannot be null then
6815     // it should have a 'nonnull' attribute in the function prototype.
6816     return SLCT_UncheckedLiteral;
6817 
6818   switch (E->getStmtClass()) {
6819   case Stmt::BinaryConditionalOperatorClass:
6820   case Stmt::ConditionalOperatorClass: {
6821     // The expression is a literal if both sub-expressions were, and it was
6822     // completely checked only if both sub-expressions were checked.
6823     const AbstractConditionalOperator *C =
6824         cast<AbstractConditionalOperator>(E);
6825 
6826     // Determine whether it is necessary to check both sub-expressions, for
6827     // example, because the condition expression is a constant that can be
6828     // evaluated at compile time.
6829     bool CheckLeft = true, CheckRight = true;
6830 
6831     bool Cond;
6832     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
6833                                                  S.isConstantEvaluated())) {
6834       if (Cond)
6835         CheckRight = false;
6836       else
6837         CheckLeft = false;
6838     }
6839 
6840     // We need to maintain the offsets for the right and the left hand side
6841     // separately to check if every possible indexed expression is a valid
6842     // string literal. They might have different offsets for different string
6843     // literals in the end.
6844     StringLiteralCheckType Left;
6845     if (!CheckLeft)
6846       Left = SLCT_UncheckedLiteral;
6847     else {
6848       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
6849                                    HasVAListArg, format_idx, firstDataArg,
6850                                    Type, CallType, InFunctionCall,
6851                                    CheckedVarArgs, UncoveredArg, Offset,
6852                                    IgnoreStringsWithoutSpecifiers);
6853       if (Left == SLCT_NotALiteral || !CheckRight) {
6854         return Left;
6855       }
6856     }
6857 
6858     StringLiteralCheckType Right = checkFormatStringExpr(
6859         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
6860         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6861         IgnoreStringsWithoutSpecifiers);
6862 
6863     return (CheckLeft && Left < Right) ? Left : Right;
6864   }
6865 
6866   case Stmt::ImplicitCastExprClass:
6867     E = cast<ImplicitCastExpr>(E)->getSubExpr();
6868     goto tryAgain;
6869 
6870   case Stmt::OpaqueValueExprClass:
6871     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
6872       E = src;
6873       goto tryAgain;
6874     }
6875     return SLCT_NotALiteral;
6876 
6877   case Stmt::PredefinedExprClass:
6878     // While __func__, etc., are technically not string literals, they
6879     // cannot contain format specifiers and thus are not a security
6880     // liability.
6881     return SLCT_UncheckedLiteral;
6882 
6883   case Stmt::DeclRefExprClass: {
6884     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6885 
6886     // As an exception, do not flag errors for variables binding to
6887     // const string literals.
6888     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
6889       bool isConstant = false;
6890       QualType T = DR->getType();
6891 
6892       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
6893         isConstant = AT->getElementType().isConstant(S.Context);
6894       } else if (const PointerType *PT = T->getAs<PointerType>()) {
6895         isConstant = T.isConstant(S.Context) &&
6896                      PT->getPointeeType().isConstant(S.Context);
6897       } else if (T->isObjCObjectPointerType()) {
6898         // In ObjC, there is usually no "const ObjectPointer" type,
6899         // so don't check if the pointee type is constant.
6900         isConstant = T.isConstant(S.Context);
6901       }
6902 
6903       if (isConstant) {
6904         if (const Expr *Init = VD->getAnyInitializer()) {
6905           // Look through initializers like const char c[] = { "foo" }
6906           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
6907             if (InitList->isStringLiteralInit())
6908               Init = InitList->getInit(0)->IgnoreParenImpCasts();
6909           }
6910           return checkFormatStringExpr(S, Init, Args,
6911                                        HasVAListArg, format_idx,
6912                                        firstDataArg, Type, CallType,
6913                                        /*InFunctionCall*/ false, CheckedVarArgs,
6914                                        UncoveredArg, Offset);
6915         }
6916       }
6917 
6918       // For vprintf* functions (i.e., HasVAListArg==true), we add a
6919       // special check to see if the format string is a function parameter
6920       // of the function calling the printf function.  If the function
6921       // has an attribute indicating it is a printf-like function, then we
6922       // should suppress warnings concerning non-literals being used in a call
6923       // to a vprintf function.  For example:
6924       //
6925       // void
6926       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
6927       //      va_list ap;
6928       //      va_start(ap, fmt);
6929       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
6930       //      ...
6931       // }
6932       if (HasVAListArg) {
6933         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
6934           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
6935             int PVIndex = PV->getFunctionScopeIndex() + 1;
6936             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
6937               // adjust for implicit parameter
6938               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6939                 if (MD->isInstance())
6940                   ++PVIndex;
6941               // We also check if the formats are compatible.
6942               // We can't pass a 'scanf' string to a 'printf' function.
6943               if (PVIndex == PVFormat->getFormatIdx() &&
6944                   Type == S.GetFormatStringType(PVFormat))
6945                 return SLCT_UncheckedLiteral;
6946             }
6947           }
6948         }
6949       }
6950     }
6951 
6952     return SLCT_NotALiteral;
6953   }
6954 
6955   case Stmt::CallExprClass:
6956   case Stmt::CXXMemberCallExprClass: {
6957     const CallExpr *CE = cast<CallExpr>(E);
6958     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
6959       bool IsFirst = true;
6960       StringLiteralCheckType CommonResult;
6961       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
6962         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
6963         StringLiteralCheckType Result = checkFormatStringExpr(
6964             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6965             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6966             IgnoreStringsWithoutSpecifiers);
6967         if (IsFirst) {
6968           CommonResult = Result;
6969           IsFirst = false;
6970         }
6971       }
6972       if (!IsFirst)
6973         return CommonResult;
6974 
6975       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
6976         unsigned BuiltinID = FD->getBuiltinID();
6977         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
6978             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
6979           const Expr *Arg = CE->getArg(0);
6980           return checkFormatStringExpr(S, Arg, Args,
6981                                        HasVAListArg, format_idx,
6982                                        firstDataArg, Type, CallType,
6983                                        InFunctionCall, CheckedVarArgs,
6984                                        UncoveredArg, Offset,
6985                                        IgnoreStringsWithoutSpecifiers);
6986         }
6987       }
6988     }
6989 
6990     return SLCT_NotALiteral;
6991   }
6992   case Stmt::ObjCMessageExprClass: {
6993     const auto *ME = cast<ObjCMessageExpr>(E);
6994     if (const auto *MD = ME->getMethodDecl()) {
6995       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
6996         // As a special case heuristic, if we're using the method -[NSBundle
6997         // localizedStringForKey:value:table:], ignore any key strings that lack
6998         // format specifiers. The idea is that if the key doesn't have any
6999         // format specifiers then its probably just a key to map to the
7000         // localized strings. If it does have format specifiers though, then its
7001         // likely that the text of the key is the format string in the
7002         // programmer's language, and should be checked.
7003         const ObjCInterfaceDecl *IFace;
7004         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7005             IFace->getIdentifier()->isStr("NSBundle") &&
7006             MD->getSelector().isKeywordSelector(
7007                 {"localizedStringForKey", "value", "table"})) {
7008           IgnoreStringsWithoutSpecifiers = true;
7009         }
7010 
7011         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
7012         return checkFormatStringExpr(
7013             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7014             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7015             IgnoreStringsWithoutSpecifiers);
7016       }
7017     }
7018 
7019     return SLCT_NotALiteral;
7020   }
7021   case Stmt::ObjCStringLiteralClass:
7022   case Stmt::StringLiteralClass: {
7023     const StringLiteral *StrE = nullptr;
7024 
7025     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
7026       StrE = ObjCFExpr->getString();
7027     else
7028       StrE = cast<StringLiteral>(E);
7029 
7030     if (StrE) {
7031       if (Offset.isNegative() || Offset > StrE->getLength()) {
7032         // TODO: It would be better to have an explicit warning for out of
7033         // bounds literals.
7034         return SLCT_NotALiteral;
7035       }
7036       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
7037       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
7038                         firstDataArg, Type, InFunctionCall, CallType,
7039                         CheckedVarArgs, UncoveredArg,
7040                         IgnoreStringsWithoutSpecifiers);
7041       return SLCT_CheckedLiteral;
7042     }
7043 
7044     return SLCT_NotALiteral;
7045   }
7046   case Stmt::BinaryOperatorClass: {
7047     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
7048 
7049     // A string literal + an int offset is still a string literal.
7050     if (BinOp->isAdditiveOp()) {
7051       Expr::EvalResult LResult, RResult;
7052 
7053       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7054           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7055       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7056           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7057 
7058       if (LIsInt != RIsInt) {
7059         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7060 
7061         if (LIsInt) {
7062           if (BinOpKind == BO_Add) {
7063             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
7064             E = BinOp->getRHS();
7065             goto tryAgain;
7066           }
7067         } else {
7068           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
7069           E = BinOp->getLHS();
7070           goto tryAgain;
7071         }
7072       }
7073     }
7074 
7075     return SLCT_NotALiteral;
7076   }
7077   case Stmt::UnaryOperatorClass: {
7078     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
7079     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
7080     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7081       Expr::EvalResult IndexResult;
7082       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
7083                                        Expr::SE_NoSideEffects,
7084                                        S.isConstantEvaluated())) {
7085         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
7086                    /*RHS is int*/ true);
7087         E = ASE->getBase();
7088         goto tryAgain;
7089       }
7090     }
7091 
7092     return SLCT_NotALiteral;
7093   }
7094 
7095   default:
7096     return SLCT_NotALiteral;
7097   }
7098 }
7099 
7100 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
7101   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
7102       .Case("scanf", FST_Scanf)
7103       .Cases("printf", "printf0", FST_Printf)
7104       .Cases("NSString", "CFString", FST_NSString)
7105       .Case("strftime", FST_Strftime)
7106       .Case("strfmon", FST_Strfmon)
7107       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
7108       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
7109       .Case("os_trace", FST_OSLog)
7110       .Case("os_log", FST_OSLog)
7111       .Default(FST_Unknown);
7112 }
7113 
7114 /// CheckFormatArguments - Check calls to printf and scanf (and similar
7115 /// functions) for correct use of format strings.
7116 /// Returns true if a format string has been fully checked.
7117 bool Sema::CheckFormatArguments(const FormatAttr *Format,
7118                                 ArrayRef<const Expr *> Args,
7119                                 bool IsCXXMember,
7120                                 VariadicCallType CallType,
7121                                 SourceLocation Loc, SourceRange Range,
7122                                 llvm::SmallBitVector &CheckedVarArgs) {
7123   FormatStringInfo FSI;
7124   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
7125     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
7126                                 FSI.FirstDataArg, GetFormatStringType(Format),
7127                                 CallType, Loc, Range, CheckedVarArgs);
7128   return false;
7129 }
7130 
7131 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7132                                 bool HasVAListArg, unsigned format_idx,
7133                                 unsigned firstDataArg, FormatStringType Type,
7134                                 VariadicCallType CallType,
7135                                 SourceLocation Loc, SourceRange Range,
7136                                 llvm::SmallBitVector &CheckedVarArgs) {
7137   // CHECK: printf/scanf-like function is called with no format string.
7138   if (format_idx >= Args.size()) {
7139     Diag(Loc, diag::warn_missing_format_string) << Range;
7140     return false;
7141   }
7142 
7143   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
7144 
7145   // CHECK: format string is not a string literal.
7146   //
7147   // Dynamically generated format strings are difficult to
7148   // automatically vet at compile time.  Requiring that format strings
7149   // are string literals: (1) permits the checking of format strings by
7150   // the compiler and thereby (2) can practically remove the source of
7151   // many format string exploits.
7152 
7153   // Format string can be either ObjC string (e.g. @"%d") or
7154   // C string (e.g. "%d")
7155   // ObjC string uses the same format specifiers as C string, so we can use
7156   // the same format string checking logic for both ObjC and C strings.
7157   UncoveredArgHandler UncoveredArg;
7158   StringLiteralCheckType CT =
7159       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
7160                             format_idx, firstDataArg, Type, CallType,
7161                             /*IsFunctionCall*/ true, CheckedVarArgs,
7162                             UncoveredArg,
7163                             /*no string offset*/ llvm::APSInt(64, false) = 0);
7164 
7165   // Generate a diagnostic where an uncovered argument is detected.
7166   if (UncoveredArg.hasUncoveredArg()) {
7167     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
7168     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
7169     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
7170   }
7171 
7172   if (CT != SLCT_NotALiteral)
7173     // Literal format string found, check done!
7174     return CT == SLCT_CheckedLiteral;
7175 
7176   // Strftime is particular as it always uses a single 'time' argument,
7177   // so it is safe to pass a non-literal string.
7178   if (Type == FST_Strftime)
7179     return false;
7180 
7181   // Do not emit diag when the string param is a macro expansion and the
7182   // format is either NSString or CFString. This is a hack to prevent
7183   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
7184   // which are usually used in place of NS and CF string literals.
7185   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
7186   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
7187     return false;
7188 
7189   // If there are no arguments specified, warn with -Wformat-security, otherwise
7190   // warn only with -Wformat-nonliteral.
7191   if (Args.size() == firstDataArg) {
7192     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
7193       << OrigFormatExpr->getSourceRange();
7194     switch (Type) {
7195     default:
7196       break;
7197     case FST_Kprintf:
7198     case FST_FreeBSDKPrintf:
7199     case FST_Printf:
7200       Diag(FormatLoc, diag::note_format_security_fixit)
7201         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
7202       break;
7203     case FST_NSString:
7204       Diag(FormatLoc, diag::note_format_security_fixit)
7205         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
7206       break;
7207     }
7208   } else {
7209     Diag(FormatLoc, diag::warn_format_nonliteral)
7210       << OrigFormatExpr->getSourceRange();
7211   }
7212   return false;
7213 }
7214 
7215 namespace {
7216 
7217 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7218 protected:
7219   Sema &S;
7220   const FormatStringLiteral *FExpr;
7221   const Expr *OrigFormatExpr;
7222   const Sema::FormatStringType FSType;
7223   const unsigned FirstDataArg;
7224   const unsigned NumDataArgs;
7225   const char *Beg; // Start of format string.
7226   const bool HasVAListArg;
7227   ArrayRef<const Expr *> Args;
7228   unsigned FormatIdx;
7229   llvm::SmallBitVector CoveredArgs;
7230   bool usesPositionalArgs = false;
7231   bool atFirstArg = true;
7232   bool inFunctionCall;
7233   Sema::VariadicCallType CallType;
7234   llvm::SmallBitVector &CheckedVarArgs;
7235   UncoveredArgHandler &UncoveredArg;
7236 
7237 public:
7238   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
7239                      const Expr *origFormatExpr,
7240                      const Sema::FormatStringType type, unsigned firstDataArg,
7241                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
7242                      ArrayRef<const Expr *> Args, unsigned formatIdx,
7243                      bool inFunctionCall, Sema::VariadicCallType callType,
7244                      llvm::SmallBitVector &CheckedVarArgs,
7245                      UncoveredArgHandler &UncoveredArg)
7246       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7247         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7248         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
7249         inFunctionCall(inFunctionCall), CallType(callType),
7250         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
7251     CoveredArgs.resize(numDataArgs);
7252     CoveredArgs.reset();
7253   }
7254 
7255   void DoneProcessing();
7256 
7257   void HandleIncompleteSpecifier(const char *startSpecifier,
7258                                  unsigned specifierLen) override;
7259 
7260   void HandleInvalidLengthModifier(
7261                            const analyze_format_string::FormatSpecifier &FS,
7262                            const analyze_format_string::ConversionSpecifier &CS,
7263                            const char *startSpecifier, unsigned specifierLen,
7264                            unsigned DiagID);
7265 
7266   void HandleNonStandardLengthModifier(
7267                     const analyze_format_string::FormatSpecifier &FS,
7268                     const char *startSpecifier, unsigned specifierLen);
7269 
7270   void HandleNonStandardConversionSpecifier(
7271                     const analyze_format_string::ConversionSpecifier &CS,
7272                     const char *startSpecifier, unsigned specifierLen);
7273 
7274   void HandlePosition(const char *startPos, unsigned posLen) override;
7275 
7276   void HandleInvalidPosition(const char *startSpecifier,
7277                              unsigned specifierLen,
7278                              analyze_format_string::PositionContext p) override;
7279 
7280   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
7281 
7282   void HandleNullChar(const char *nullCharacter) override;
7283 
7284   template <typename Range>
7285   static void
7286   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
7287                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
7288                        bool IsStringLocation, Range StringRange,
7289                        ArrayRef<FixItHint> Fixit = None);
7290 
7291 protected:
7292   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
7293                                         const char *startSpec,
7294                                         unsigned specifierLen,
7295                                         const char *csStart, unsigned csLen);
7296 
7297   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7298                                          const char *startSpec,
7299                                          unsigned specifierLen);
7300 
7301   SourceRange getFormatStringRange();
7302   CharSourceRange getSpecifierRange(const char *startSpecifier,
7303                                     unsigned specifierLen);
7304   SourceLocation getLocationOfByte(const char *x);
7305 
7306   const Expr *getDataArg(unsigned i) const;
7307 
7308   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7309                     const analyze_format_string::ConversionSpecifier &CS,
7310                     const char *startSpecifier, unsigned specifierLen,
7311                     unsigned argIndex);
7312 
7313   template <typename Range>
7314   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7315                             bool IsStringLocation, Range StringRange,
7316                             ArrayRef<FixItHint> Fixit = None);
7317 };
7318 
7319 } // namespace
7320 
7321 SourceRange CheckFormatHandler::getFormatStringRange() {
7322   return OrigFormatExpr->getSourceRange();
7323 }
7324 
7325 CharSourceRange CheckFormatHandler::
7326 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
7327   SourceLocation Start = getLocationOfByte(startSpecifier);
7328   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
7329 
7330   // Advance the end SourceLocation by one due to half-open ranges.
7331   End = End.getLocWithOffset(1);
7332 
7333   return CharSourceRange::getCharRange(Start, End);
7334 }
7335 
7336 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
7337   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
7338                                   S.getLangOpts(), S.Context.getTargetInfo());
7339 }
7340 
7341 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7342                                                    unsigned specifierLen){
7343   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
7344                        getLocationOfByte(startSpecifier),
7345                        /*IsStringLocation*/true,
7346                        getSpecifierRange(startSpecifier, specifierLen));
7347 }
7348 
7349 void CheckFormatHandler::HandleInvalidLengthModifier(
7350     const analyze_format_string::FormatSpecifier &FS,
7351     const analyze_format_string::ConversionSpecifier &CS,
7352     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
7353   using namespace analyze_format_string;
7354 
7355   const LengthModifier &LM = FS.getLengthModifier();
7356   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7357 
7358   // See if we know how to fix this length modifier.
7359   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7360   if (FixedLM) {
7361     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7362                          getLocationOfByte(LM.getStart()),
7363                          /*IsStringLocation*/true,
7364                          getSpecifierRange(startSpecifier, specifierLen));
7365 
7366     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7367       << FixedLM->toString()
7368       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7369 
7370   } else {
7371     FixItHint Hint;
7372     if (DiagID == diag::warn_format_nonsensical_length)
7373       Hint = FixItHint::CreateRemoval(LMRange);
7374 
7375     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7376                          getLocationOfByte(LM.getStart()),
7377                          /*IsStringLocation*/true,
7378                          getSpecifierRange(startSpecifier, specifierLen),
7379                          Hint);
7380   }
7381 }
7382 
7383 void CheckFormatHandler::HandleNonStandardLengthModifier(
7384     const analyze_format_string::FormatSpecifier &FS,
7385     const char *startSpecifier, unsigned specifierLen) {
7386   using namespace analyze_format_string;
7387 
7388   const LengthModifier &LM = FS.getLengthModifier();
7389   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7390 
7391   // See if we know how to fix this length modifier.
7392   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7393   if (FixedLM) {
7394     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7395                            << LM.toString() << 0,
7396                          getLocationOfByte(LM.getStart()),
7397                          /*IsStringLocation*/true,
7398                          getSpecifierRange(startSpecifier, specifierLen));
7399 
7400     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7401       << FixedLM->toString()
7402       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7403 
7404   } else {
7405     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7406                            << LM.toString() << 0,
7407                          getLocationOfByte(LM.getStart()),
7408                          /*IsStringLocation*/true,
7409                          getSpecifierRange(startSpecifier, specifierLen));
7410   }
7411 }
7412 
7413 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
7414     const analyze_format_string::ConversionSpecifier &CS,
7415     const char *startSpecifier, unsigned specifierLen) {
7416   using namespace analyze_format_string;
7417 
7418   // See if we know how to fix this conversion specifier.
7419   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
7420   if (FixedCS) {
7421     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7422                           << CS.toString() << /*conversion specifier*/1,
7423                          getLocationOfByte(CS.getStart()),
7424                          /*IsStringLocation*/true,
7425                          getSpecifierRange(startSpecifier, specifierLen));
7426 
7427     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
7428     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
7429       << FixedCS->toString()
7430       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
7431   } else {
7432     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7433                           << CS.toString() << /*conversion specifier*/1,
7434                          getLocationOfByte(CS.getStart()),
7435                          /*IsStringLocation*/true,
7436                          getSpecifierRange(startSpecifier, specifierLen));
7437   }
7438 }
7439 
7440 void CheckFormatHandler::HandlePosition(const char *startPos,
7441                                         unsigned posLen) {
7442   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
7443                                getLocationOfByte(startPos),
7444                                /*IsStringLocation*/true,
7445                                getSpecifierRange(startPos, posLen));
7446 }
7447 
7448 void
7449 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
7450                                      analyze_format_string::PositionContext p) {
7451   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
7452                          << (unsigned) p,
7453                        getLocationOfByte(startPos), /*IsStringLocation*/true,
7454                        getSpecifierRange(startPos, posLen));
7455 }
7456 
7457 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
7458                                             unsigned posLen) {
7459   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
7460                                getLocationOfByte(startPos),
7461                                /*IsStringLocation*/true,
7462                                getSpecifierRange(startPos, posLen));
7463 }
7464 
7465 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
7466   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
7467     // The presence of a null character is likely an error.
7468     EmitFormatDiagnostic(
7469       S.PDiag(diag::warn_printf_format_string_contains_null_char),
7470       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
7471       getFormatStringRange());
7472   }
7473 }
7474 
7475 // Note that this may return NULL if there was an error parsing or building
7476 // one of the argument expressions.
7477 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
7478   return Args[FirstDataArg + i];
7479 }
7480 
7481 void CheckFormatHandler::DoneProcessing() {
7482   // Does the number of data arguments exceed the number of
7483   // format conversions in the format string?
7484   if (!HasVAListArg) {
7485       // Find any arguments that weren't covered.
7486     CoveredArgs.flip();
7487     signed notCoveredArg = CoveredArgs.find_first();
7488     if (notCoveredArg >= 0) {
7489       assert((unsigned)notCoveredArg < NumDataArgs);
7490       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
7491     } else {
7492       UncoveredArg.setAllCovered();
7493     }
7494   }
7495 }
7496 
7497 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7498                                    const Expr *ArgExpr) {
7499   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
7500          "Invalid state");
7501 
7502   if (!ArgExpr)
7503     return;
7504 
7505   SourceLocation Loc = ArgExpr->getBeginLoc();
7506 
7507   if (S.getSourceManager().isInSystemMacro(Loc))
7508     return;
7509 
7510   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
7511   for (auto E : DiagnosticExprs)
7512     PDiag << E->getSourceRange();
7513 
7514   CheckFormatHandler::EmitFormatDiagnostic(
7515                                   S, IsFunctionCall, DiagnosticExprs[0],
7516                                   PDiag, Loc, /*IsStringLocation*/false,
7517                                   DiagnosticExprs[0]->getSourceRange());
7518 }
7519 
7520 bool
7521 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7522                                                      SourceLocation Loc,
7523                                                      const char *startSpec,
7524                                                      unsigned specifierLen,
7525                                                      const char *csStart,
7526                                                      unsigned csLen) {
7527   bool keepGoing = true;
7528   if (argIndex < NumDataArgs) {
7529     // Consider the argument coverered, even though the specifier doesn't
7530     // make sense.
7531     CoveredArgs.set(argIndex);
7532   }
7533   else {
7534     // If argIndex exceeds the number of data arguments we
7535     // don't issue a warning because that is just a cascade of warnings (and
7536     // they may have intended '%%' anyway). We don't want to continue processing
7537     // the format string after this point, however, as we will like just get
7538     // gibberish when trying to match arguments.
7539     keepGoing = false;
7540   }
7541 
7542   StringRef Specifier(csStart, csLen);
7543 
7544   // If the specifier in non-printable, it could be the first byte of a UTF-8
7545   // sequence. In that case, print the UTF-8 code point. If not, print the byte
7546   // hex value.
7547   std::string CodePointStr;
7548   if (!llvm::sys::locale::isPrint(*csStart)) {
7549     llvm::UTF32 CodePoint;
7550     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7551     const llvm::UTF8 *E =
7552         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7553     llvm::ConversionResult Result =
7554         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
7555 
7556     if (Result != llvm::conversionOK) {
7557       unsigned char FirstChar = *csStart;
7558       CodePoint = (llvm::UTF32)FirstChar;
7559     }
7560 
7561     llvm::raw_string_ostream OS(CodePointStr);
7562     if (CodePoint < 256)
7563       OS << "\\x" << llvm::format("%02x", CodePoint);
7564     else if (CodePoint <= 0xFFFF)
7565       OS << "\\u" << llvm::format("%04x", CodePoint);
7566     else
7567       OS << "\\U" << llvm::format("%08x", CodePoint);
7568     OS.flush();
7569     Specifier = CodePointStr;
7570   }
7571 
7572   EmitFormatDiagnostic(
7573       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
7574       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
7575 
7576   return keepGoing;
7577 }
7578 
7579 void
7580 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7581                                                       const char *startSpec,
7582                                                       unsigned specifierLen) {
7583   EmitFormatDiagnostic(
7584     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
7585     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
7586 }
7587 
7588 bool
7589 CheckFormatHandler::CheckNumArgs(
7590   const analyze_format_string::FormatSpecifier &FS,
7591   const analyze_format_string::ConversionSpecifier &CS,
7592   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7593 
7594   if (argIndex >= NumDataArgs) {
7595     PartialDiagnostic PDiag = FS.usesPositionalArg()
7596       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
7597            << (argIndex+1) << NumDataArgs)
7598       : S.PDiag(diag::warn_printf_insufficient_data_args);
7599     EmitFormatDiagnostic(
7600       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
7601       getSpecifierRange(startSpecifier, specifierLen));
7602 
7603     // Since more arguments than conversion tokens are given, by extension
7604     // all arguments are covered, so mark this as so.
7605     UncoveredArg.setAllCovered();
7606     return false;
7607   }
7608   return true;
7609 }
7610 
7611 template<typename Range>
7612 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
7613                                               SourceLocation Loc,
7614                                               bool IsStringLocation,
7615                                               Range StringRange,
7616                                               ArrayRef<FixItHint> FixIt) {
7617   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
7618                        Loc, IsStringLocation, StringRange, FixIt);
7619 }
7620 
7621 /// If the format string is not within the function call, emit a note
7622 /// so that the function call and string are in diagnostic messages.
7623 ///
7624 /// \param InFunctionCall if true, the format string is within the function
7625 /// call and only one diagnostic message will be produced.  Otherwise, an
7626 /// extra note will be emitted pointing to location of the format string.
7627 ///
7628 /// \param ArgumentExpr the expression that is passed as the format string
7629 /// argument in the function call.  Used for getting locations when two
7630 /// diagnostics are emitted.
7631 ///
7632 /// \param PDiag the callee should already have provided any strings for the
7633 /// diagnostic message.  This function only adds locations and fixits
7634 /// to diagnostics.
7635 ///
7636 /// \param Loc primary location for diagnostic.  If two diagnostics are
7637 /// required, one will be at Loc and a new SourceLocation will be created for
7638 /// the other one.
7639 ///
7640 /// \param IsStringLocation if true, Loc points to the format string should be
7641 /// used for the note.  Otherwise, Loc points to the argument list and will
7642 /// be used with PDiag.
7643 ///
7644 /// \param StringRange some or all of the string to highlight.  This is
7645 /// templated so it can accept either a CharSourceRange or a SourceRange.
7646 ///
7647 /// \param FixIt optional fix it hint for the format string.
7648 template <typename Range>
7649 void CheckFormatHandler::EmitFormatDiagnostic(
7650     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
7651     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
7652     Range StringRange, ArrayRef<FixItHint> FixIt) {
7653   if (InFunctionCall) {
7654     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
7655     D << StringRange;
7656     D << FixIt;
7657   } else {
7658     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
7659       << ArgumentExpr->getSourceRange();
7660 
7661     const Sema::SemaDiagnosticBuilder &Note =
7662       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
7663              diag::note_format_string_defined);
7664 
7665     Note << StringRange;
7666     Note << FixIt;
7667   }
7668 }
7669 
7670 //===--- CHECK: Printf format string checking ------------------------------===//
7671 
7672 namespace {
7673 
7674 class CheckPrintfHandler : public CheckFormatHandler {
7675 public:
7676   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7677                      const Expr *origFormatExpr,
7678                      const Sema::FormatStringType type, unsigned firstDataArg,
7679                      unsigned numDataArgs, bool isObjC, const char *beg,
7680                      bool hasVAListArg, ArrayRef<const Expr *> Args,
7681                      unsigned formatIdx, bool inFunctionCall,
7682                      Sema::VariadicCallType CallType,
7683                      llvm::SmallBitVector &CheckedVarArgs,
7684                      UncoveredArgHandler &UncoveredArg)
7685       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7686                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
7687                            inFunctionCall, CallType, CheckedVarArgs,
7688                            UncoveredArg) {}
7689 
7690   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
7691 
7692   /// Returns true if '%@' specifiers are allowed in the format string.
7693   bool allowsObjCArg() const {
7694     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
7695            FSType == Sema::FST_OSTrace;
7696   }
7697 
7698   bool HandleInvalidPrintfConversionSpecifier(
7699                                       const analyze_printf::PrintfSpecifier &FS,
7700                                       const char *startSpecifier,
7701                                       unsigned specifierLen) override;
7702 
7703   void handleInvalidMaskType(StringRef MaskType) override;
7704 
7705   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7706                              const char *startSpecifier,
7707                              unsigned specifierLen) override;
7708   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7709                        const char *StartSpecifier,
7710                        unsigned SpecifierLen,
7711                        const Expr *E);
7712 
7713   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
7714                     const char *startSpecifier, unsigned specifierLen);
7715   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
7716                            const analyze_printf::OptionalAmount &Amt,
7717                            unsigned type,
7718                            const char *startSpecifier, unsigned specifierLen);
7719   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7720                   const analyze_printf::OptionalFlag &flag,
7721                   const char *startSpecifier, unsigned specifierLen);
7722   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
7723                          const analyze_printf::OptionalFlag &ignoredFlag,
7724                          const analyze_printf::OptionalFlag &flag,
7725                          const char *startSpecifier, unsigned specifierLen);
7726   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
7727                            const Expr *E);
7728 
7729   void HandleEmptyObjCModifierFlag(const char *startFlag,
7730                                    unsigned flagLen) override;
7731 
7732   void HandleInvalidObjCModifierFlag(const char *startFlag,
7733                                             unsigned flagLen) override;
7734 
7735   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
7736                                            const char *flagsEnd,
7737                                            const char *conversionPosition)
7738                                              override;
7739 };
7740 
7741 } // namespace
7742 
7743 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
7744                                       const analyze_printf::PrintfSpecifier &FS,
7745                                       const char *startSpecifier,
7746                                       unsigned specifierLen) {
7747   const analyze_printf::PrintfConversionSpecifier &CS =
7748     FS.getConversionSpecifier();
7749 
7750   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7751                                           getLocationOfByte(CS.getStart()),
7752                                           startSpecifier, specifierLen,
7753                                           CS.getStart(), CS.getLength());
7754 }
7755 
7756 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
7757   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
7758 }
7759 
7760 bool CheckPrintfHandler::HandleAmount(
7761                                const analyze_format_string::OptionalAmount &Amt,
7762                                unsigned k, const char *startSpecifier,
7763                                unsigned specifierLen) {
7764   if (Amt.hasDataArgument()) {
7765     if (!HasVAListArg) {
7766       unsigned argIndex = Amt.getArgIndex();
7767       if (argIndex >= NumDataArgs) {
7768         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
7769                                << k,
7770                              getLocationOfByte(Amt.getStart()),
7771                              /*IsStringLocation*/true,
7772                              getSpecifierRange(startSpecifier, specifierLen));
7773         // Don't do any more checking.  We will just emit
7774         // spurious errors.
7775         return false;
7776       }
7777 
7778       // Type check the data argument.  It should be an 'int'.
7779       // Although not in conformance with C99, we also allow the argument to be
7780       // an 'unsigned int' as that is a reasonably safe case.  GCC also
7781       // doesn't emit a warning for that case.
7782       CoveredArgs.set(argIndex);
7783       const Expr *Arg = getDataArg(argIndex);
7784       if (!Arg)
7785         return false;
7786 
7787       QualType T = Arg->getType();
7788 
7789       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
7790       assert(AT.isValid());
7791 
7792       if (!AT.matchesType(S.Context, T)) {
7793         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
7794                                << k << AT.getRepresentativeTypeName(S.Context)
7795                                << T << Arg->getSourceRange(),
7796                              getLocationOfByte(Amt.getStart()),
7797                              /*IsStringLocation*/true,
7798                              getSpecifierRange(startSpecifier, specifierLen));
7799         // Don't do any more checking.  We will just emit
7800         // spurious errors.
7801         return false;
7802       }
7803     }
7804   }
7805   return true;
7806 }
7807 
7808 void CheckPrintfHandler::HandleInvalidAmount(
7809                                       const analyze_printf::PrintfSpecifier &FS,
7810                                       const analyze_printf::OptionalAmount &Amt,
7811                                       unsigned type,
7812                                       const char *startSpecifier,
7813                                       unsigned specifierLen) {
7814   const analyze_printf::PrintfConversionSpecifier &CS =
7815     FS.getConversionSpecifier();
7816 
7817   FixItHint fixit =
7818     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
7819       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
7820                                  Amt.getConstantLength()))
7821       : FixItHint();
7822 
7823   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
7824                          << type << CS.toString(),
7825                        getLocationOfByte(Amt.getStart()),
7826                        /*IsStringLocation*/true,
7827                        getSpecifierRange(startSpecifier, specifierLen),
7828                        fixit);
7829 }
7830 
7831 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7832                                     const analyze_printf::OptionalFlag &flag,
7833                                     const char *startSpecifier,
7834                                     unsigned specifierLen) {
7835   // Warn about pointless flag with a fixit removal.
7836   const analyze_printf::PrintfConversionSpecifier &CS =
7837     FS.getConversionSpecifier();
7838   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
7839                          << flag.toString() << CS.toString(),
7840                        getLocationOfByte(flag.getPosition()),
7841                        /*IsStringLocation*/true,
7842                        getSpecifierRange(startSpecifier, specifierLen),
7843                        FixItHint::CreateRemoval(
7844                          getSpecifierRange(flag.getPosition(), 1)));
7845 }
7846 
7847 void CheckPrintfHandler::HandleIgnoredFlag(
7848                                 const analyze_printf::PrintfSpecifier &FS,
7849                                 const analyze_printf::OptionalFlag &ignoredFlag,
7850                                 const analyze_printf::OptionalFlag &flag,
7851                                 const char *startSpecifier,
7852                                 unsigned specifierLen) {
7853   // Warn about ignored flag with a fixit removal.
7854   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
7855                          << ignoredFlag.toString() << flag.toString(),
7856                        getLocationOfByte(ignoredFlag.getPosition()),
7857                        /*IsStringLocation*/true,
7858                        getSpecifierRange(startSpecifier, specifierLen),
7859                        FixItHint::CreateRemoval(
7860                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
7861 }
7862 
7863 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
7864                                                      unsigned flagLen) {
7865   // Warn about an empty flag.
7866   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
7867                        getLocationOfByte(startFlag),
7868                        /*IsStringLocation*/true,
7869                        getSpecifierRange(startFlag, flagLen));
7870 }
7871 
7872 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
7873                                                        unsigned flagLen) {
7874   // Warn about an invalid flag.
7875   auto Range = getSpecifierRange(startFlag, flagLen);
7876   StringRef flag(startFlag, flagLen);
7877   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
7878                       getLocationOfByte(startFlag),
7879                       /*IsStringLocation*/true,
7880                       Range, FixItHint::CreateRemoval(Range));
7881 }
7882 
7883 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
7884     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
7885     // Warn about using '[...]' without a '@' conversion.
7886     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
7887     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
7888     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
7889                          getLocationOfByte(conversionPosition),
7890                          /*IsStringLocation*/true,
7891                          Range, FixItHint::CreateRemoval(Range));
7892 }
7893 
7894 // Determines if the specified is a C++ class or struct containing
7895 // a member with the specified name and kind (e.g. a CXXMethodDecl named
7896 // "c_str()").
7897 template<typename MemberKind>
7898 static llvm::SmallPtrSet<MemberKind*, 1>
7899 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
7900   const RecordType *RT = Ty->getAs<RecordType>();
7901   llvm::SmallPtrSet<MemberKind*, 1> Results;
7902 
7903   if (!RT)
7904     return Results;
7905   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
7906   if (!RD || !RD->getDefinition())
7907     return Results;
7908 
7909   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
7910                  Sema::LookupMemberName);
7911   R.suppressDiagnostics();
7912 
7913   // We just need to include all members of the right kind turned up by the
7914   // filter, at this point.
7915   if (S.LookupQualifiedName(R, RT->getDecl()))
7916     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7917       NamedDecl *decl = (*I)->getUnderlyingDecl();
7918       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
7919         Results.insert(FK);
7920     }
7921   return Results;
7922 }
7923 
7924 /// Check if we could call '.c_str()' on an object.
7925 ///
7926 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
7927 /// allow the call, or if it would be ambiguous).
7928 bool Sema::hasCStrMethod(const Expr *E) {
7929   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7930 
7931   MethodSet Results =
7932       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
7933   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7934        MI != ME; ++MI)
7935     if ((*MI)->getMinRequiredArguments() == 0)
7936       return true;
7937   return false;
7938 }
7939 
7940 // Check if a (w)string was passed when a (w)char* was needed, and offer a
7941 // better diagnostic if so. AT is assumed to be valid.
7942 // Returns true when a c_str() conversion method is found.
7943 bool CheckPrintfHandler::checkForCStrMembers(
7944     const analyze_printf::ArgType &AT, const Expr *E) {
7945   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7946 
7947   MethodSet Results =
7948       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
7949 
7950   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7951        MI != ME; ++MI) {
7952     const CXXMethodDecl *Method = *MI;
7953     if (Method->getMinRequiredArguments() == 0 &&
7954         AT.matchesType(S.Context, Method->getReturnType())) {
7955       // FIXME: Suggest parens if the expression needs them.
7956       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
7957       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
7958           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
7959       return true;
7960     }
7961   }
7962 
7963   return false;
7964 }
7965 
7966 bool
7967 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
7968                                             &FS,
7969                                           const char *startSpecifier,
7970                                           unsigned specifierLen) {
7971   using namespace analyze_format_string;
7972   using namespace analyze_printf;
7973 
7974   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
7975 
7976   if (FS.consumesDataArgument()) {
7977     if (atFirstArg) {
7978         atFirstArg = false;
7979         usesPositionalArgs = FS.usesPositionalArg();
7980     }
7981     else if (usesPositionalArgs != FS.usesPositionalArg()) {
7982       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
7983                                         startSpecifier, specifierLen);
7984       return false;
7985     }
7986   }
7987 
7988   // First check if the field width, precision, and conversion specifier
7989   // have matching data arguments.
7990   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
7991                     startSpecifier, specifierLen)) {
7992     return false;
7993   }
7994 
7995   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
7996                     startSpecifier, specifierLen)) {
7997     return false;
7998   }
7999 
8000   if (!CS.consumesDataArgument()) {
8001     // FIXME: Technically specifying a precision or field width here
8002     // makes no sense.  Worth issuing a warning at some point.
8003     return true;
8004   }
8005 
8006   // Consume the argument.
8007   unsigned argIndex = FS.getArgIndex();
8008   if (argIndex < NumDataArgs) {
8009     // The check to see if the argIndex is valid will come later.
8010     // We set the bit here because we may exit early from this
8011     // function if we encounter some other error.
8012     CoveredArgs.set(argIndex);
8013   }
8014 
8015   // FreeBSD kernel extensions.
8016   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
8017       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8018     // We need at least two arguments.
8019     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
8020       return false;
8021 
8022     // Claim the second argument.
8023     CoveredArgs.set(argIndex + 1);
8024 
8025     // Type check the first argument (int for %b, pointer for %D)
8026     const Expr *Ex = getDataArg(argIndex);
8027     const analyze_printf::ArgType &AT =
8028       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
8029         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
8030     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
8031       EmitFormatDiagnostic(
8032           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8033               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
8034               << false << Ex->getSourceRange(),
8035           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8036           getSpecifierRange(startSpecifier, specifierLen));
8037 
8038     // Type check the second argument (char * for both %b and %D)
8039     Ex = getDataArg(argIndex + 1);
8040     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
8041     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
8042       EmitFormatDiagnostic(
8043           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8044               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
8045               << false << Ex->getSourceRange(),
8046           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8047           getSpecifierRange(startSpecifier, specifierLen));
8048 
8049      return true;
8050   }
8051 
8052   // Check for using an Objective-C specific conversion specifier
8053   // in a non-ObjC literal.
8054   if (!allowsObjCArg() && CS.isObjCArg()) {
8055     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8056                                                   specifierLen);
8057   }
8058 
8059   // %P can only be used with os_log.
8060   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
8061     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8062                                                   specifierLen);
8063   }
8064 
8065   // %n is not allowed with os_log.
8066   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
8067     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
8068                          getLocationOfByte(CS.getStart()),
8069                          /*IsStringLocation*/ false,
8070                          getSpecifierRange(startSpecifier, specifierLen));
8071 
8072     return true;
8073   }
8074 
8075   // Only scalars are allowed for os_trace.
8076   if (FSType == Sema::FST_OSTrace &&
8077       (CS.getKind() == ConversionSpecifier::PArg ||
8078        CS.getKind() == ConversionSpecifier::sArg ||
8079        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
8080     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8081                                                   specifierLen);
8082   }
8083 
8084   // Check for use of public/private annotation outside of os_log().
8085   if (FSType != Sema::FST_OSLog) {
8086     if (FS.isPublic().isSet()) {
8087       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8088                                << "public",
8089                            getLocationOfByte(FS.isPublic().getPosition()),
8090                            /*IsStringLocation*/ false,
8091                            getSpecifierRange(startSpecifier, specifierLen));
8092     }
8093     if (FS.isPrivate().isSet()) {
8094       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8095                                << "private",
8096                            getLocationOfByte(FS.isPrivate().getPosition()),
8097                            /*IsStringLocation*/ false,
8098                            getSpecifierRange(startSpecifier, specifierLen));
8099     }
8100   }
8101 
8102   // Check for invalid use of field width
8103   if (!FS.hasValidFieldWidth()) {
8104     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
8105         startSpecifier, specifierLen);
8106   }
8107 
8108   // Check for invalid use of precision
8109   if (!FS.hasValidPrecision()) {
8110     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
8111         startSpecifier, specifierLen);
8112   }
8113 
8114   // Precision is mandatory for %P specifier.
8115   if (CS.getKind() == ConversionSpecifier::PArg &&
8116       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
8117     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
8118                          getLocationOfByte(startSpecifier),
8119                          /*IsStringLocation*/ false,
8120                          getSpecifierRange(startSpecifier, specifierLen));
8121   }
8122 
8123   // Check each flag does not conflict with any other component.
8124   if (!FS.hasValidThousandsGroupingPrefix())
8125     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
8126   if (!FS.hasValidLeadingZeros())
8127     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
8128   if (!FS.hasValidPlusPrefix())
8129     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
8130   if (!FS.hasValidSpacePrefix())
8131     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
8132   if (!FS.hasValidAlternativeForm())
8133     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
8134   if (!FS.hasValidLeftJustified())
8135     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
8136 
8137   // Check that flags are not ignored by another flag
8138   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
8139     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
8140         startSpecifier, specifierLen);
8141   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
8142     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
8143             startSpecifier, specifierLen);
8144 
8145   // Check the length modifier is valid with the given conversion specifier.
8146   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8147                                  S.getLangOpts()))
8148     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8149                                 diag::warn_format_nonsensical_length);
8150   else if (!FS.hasStandardLengthModifier())
8151     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8152   else if (!FS.hasStandardLengthConversionCombination())
8153     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8154                                 diag::warn_format_non_standard_conversion_spec);
8155 
8156   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8157     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8158 
8159   // The remaining checks depend on the data arguments.
8160   if (HasVAListArg)
8161     return true;
8162 
8163   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8164     return false;
8165 
8166   const Expr *Arg = getDataArg(argIndex);
8167   if (!Arg)
8168     return true;
8169 
8170   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
8171 }
8172 
8173 static bool requiresParensToAddCast(const Expr *E) {
8174   // FIXME: We should have a general way to reason about operator
8175   // precedence and whether parens are actually needed here.
8176   // Take care of a few common cases where they aren't.
8177   const Expr *Inside = E->IgnoreImpCasts();
8178   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
8179     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
8180 
8181   switch (Inside->getStmtClass()) {
8182   case Stmt::ArraySubscriptExprClass:
8183   case Stmt::CallExprClass:
8184   case Stmt::CharacterLiteralClass:
8185   case Stmt::CXXBoolLiteralExprClass:
8186   case Stmt::DeclRefExprClass:
8187   case Stmt::FloatingLiteralClass:
8188   case Stmt::IntegerLiteralClass:
8189   case Stmt::MemberExprClass:
8190   case Stmt::ObjCArrayLiteralClass:
8191   case Stmt::ObjCBoolLiteralExprClass:
8192   case Stmt::ObjCBoxedExprClass:
8193   case Stmt::ObjCDictionaryLiteralClass:
8194   case Stmt::ObjCEncodeExprClass:
8195   case Stmt::ObjCIvarRefExprClass:
8196   case Stmt::ObjCMessageExprClass:
8197   case Stmt::ObjCPropertyRefExprClass:
8198   case Stmt::ObjCStringLiteralClass:
8199   case Stmt::ObjCSubscriptRefExprClass:
8200   case Stmt::ParenExprClass:
8201   case Stmt::StringLiteralClass:
8202   case Stmt::UnaryOperatorClass:
8203     return false;
8204   default:
8205     return true;
8206   }
8207 }
8208 
8209 static std::pair<QualType, StringRef>
8210 shouldNotPrintDirectly(const ASTContext &Context,
8211                        QualType IntendedTy,
8212                        const Expr *E) {
8213   // Use a 'while' to peel off layers of typedefs.
8214   QualType TyTy = IntendedTy;
8215   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
8216     StringRef Name = UserTy->getDecl()->getName();
8217     QualType CastTy = llvm::StringSwitch<QualType>(Name)
8218       .Case("CFIndex", Context.getNSIntegerType())
8219       .Case("NSInteger", Context.getNSIntegerType())
8220       .Case("NSUInteger", Context.getNSUIntegerType())
8221       .Case("SInt32", Context.IntTy)
8222       .Case("UInt32", Context.UnsignedIntTy)
8223       .Default(QualType());
8224 
8225     if (!CastTy.isNull())
8226       return std::make_pair(CastTy, Name);
8227 
8228     TyTy = UserTy->desugar();
8229   }
8230 
8231   // Strip parens if necessary.
8232   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
8233     return shouldNotPrintDirectly(Context,
8234                                   PE->getSubExpr()->getType(),
8235                                   PE->getSubExpr());
8236 
8237   // If this is a conditional expression, then its result type is constructed
8238   // via usual arithmetic conversions and thus there might be no necessary
8239   // typedef sugar there.  Recurse to operands to check for NSInteger &
8240   // Co. usage condition.
8241   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8242     QualType TrueTy, FalseTy;
8243     StringRef TrueName, FalseName;
8244 
8245     std::tie(TrueTy, TrueName) =
8246       shouldNotPrintDirectly(Context,
8247                              CO->getTrueExpr()->getType(),
8248                              CO->getTrueExpr());
8249     std::tie(FalseTy, FalseName) =
8250       shouldNotPrintDirectly(Context,
8251                              CO->getFalseExpr()->getType(),
8252                              CO->getFalseExpr());
8253 
8254     if (TrueTy == FalseTy)
8255       return std::make_pair(TrueTy, TrueName);
8256     else if (TrueTy.isNull())
8257       return std::make_pair(FalseTy, FalseName);
8258     else if (FalseTy.isNull())
8259       return std::make_pair(TrueTy, TrueName);
8260   }
8261 
8262   return std::make_pair(QualType(), StringRef());
8263 }
8264 
8265 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
8266 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
8267 /// type do not count.
8268 static bool
8269 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
8270   QualType From = ICE->getSubExpr()->getType();
8271   QualType To = ICE->getType();
8272   // It's an integer promotion if the destination type is the promoted
8273   // source type.
8274   if (ICE->getCastKind() == CK_IntegralCast &&
8275       From->isPromotableIntegerType() &&
8276       S.Context.getPromotedIntegerType(From) == To)
8277     return true;
8278   // Look through vector types, since we do default argument promotion for
8279   // those in OpenCL.
8280   if (const auto *VecTy = From->getAs<ExtVectorType>())
8281     From = VecTy->getElementType();
8282   if (const auto *VecTy = To->getAs<ExtVectorType>())
8283     To = VecTy->getElementType();
8284   // It's a floating promotion if the source type is a lower rank.
8285   return ICE->getCastKind() == CK_FloatingCast &&
8286          S.Context.getFloatingTypeOrder(From, To) < 0;
8287 }
8288 
8289 bool
8290 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8291                                     const char *StartSpecifier,
8292                                     unsigned SpecifierLen,
8293                                     const Expr *E) {
8294   using namespace analyze_format_string;
8295   using namespace analyze_printf;
8296 
8297   // Now type check the data expression that matches the
8298   // format specifier.
8299   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
8300   if (!AT.isValid())
8301     return true;
8302 
8303   QualType ExprTy = E->getType();
8304   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
8305     ExprTy = TET->getUnderlyingExpr()->getType();
8306   }
8307 
8308   // Diagnose attempts to print a boolean value as a character. Unlike other
8309   // -Wformat diagnostics, this is fine from a type perspective, but it still
8310   // doesn't make sense.
8311   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
8312       E->isKnownToHaveBooleanValue()) {
8313     const CharSourceRange &CSR =
8314         getSpecifierRange(StartSpecifier, SpecifierLen);
8315     SmallString<4> FSString;
8316     llvm::raw_svector_ostream os(FSString);
8317     FS.toString(os);
8318     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
8319                              << FSString,
8320                          E->getExprLoc(), false, CSR);
8321     return true;
8322   }
8323 
8324   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
8325   if (Match == analyze_printf::ArgType::Match)
8326     return true;
8327 
8328   // Look through argument promotions for our error message's reported type.
8329   // This includes the integral and floating promotions, but excludes array
8330   // and function pointer decay (seeing that an argument intended to be a
8331   // string has type 'char [6]' is probably more confusing than 'char *') and
8332   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
8333   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8334     if (isArithmeticArgumentPromotion(S, ICE)) {
8335       E = ICE->getSubExpr();
8336       ExprTy = E->getType();
8337 
8338       // Check if we didn't match because of an implicit cast from a 'char'
8339       // or 'short' to an 'int'.  This is done because printf is a varargs
8340       // function.
8341       if (ICE->getType() == S.Context.IntTy ||
8342           ICE->getType() == S.Context.UnsignedIntTy) {
8343         // All further checking is done on the subexpression
8344         const analyze_printf::ArgType::MatchKind ImplicitMatch =
8345             AT.matchesType(S.Context, ExprTy);
8346         if (ImplicitMatch == analyze_printf::ArgType::Match)
8347           return true;
8348         if (ImplicitMatch == ArgType::NoMatchPedantic ||
8349             ImplicitMatch == ArgType::NoMatchTypeConfusion)
8350           Match = ImplicitMatch;
8351       }
8352     }
8353   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
8354     // Special case for 'a', which has type 'int' in C.
8355     // Note, however, that we do /not/ want to treat multibyte constants like
8356     // 'MooV' as characters! This form is deprecated but still exists.
8357     if (ExprTy == S.Context.IntTy)
8358       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
8359         ExprTy = S.Context.CharTy;
8360   }
8361 
8362   // Look through enums to their underlying type.
8363   bool IsEnum = false;
8364   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
8365     ExprTy = EnumTy->getDecl()->getIntegerType();
8366     IsEnum = true;
8367   }
8368 
8369   // %C in an Objective-C context prints a unichar, not a wchar_t.
8370   // If the argument is an integer of some kind, believe the %C and suggest
8371   // a cast instead of changing the conversion specifier.
8372   QualType IntendedTy = ExprTy;
8373   if (isObjCContext() &&
8374       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
8375     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
8376         !ExprTy->isCharType()) {
8377       // 'unichar' is defined as a typedef of unsigned short, but we should
8378       // prefer using the typedef if it is visible.
8379       IntendedTy = S.Context.UnsignedShortTy;
8380 
8381       // While we are here, check if the value is an IntegerLiteral that happens
8382       // to be within the valid range.
8383       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
8384         const llvm::APInt &V = IL->getValue();
8385         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
8386           return true;
8387       }
8388 
8389       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
8390                           Sema::LookupOrdinaryName);
8391       if (S.LookupName(Result, S.getCurScope())) {
8392         NamedDecl *ND = Result.getFoundDecl();
8393         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
8394           if (TD->getUnderlyingType() == IntendedTy)
8395             IntendedTy = S.Context.getTypedefType(TD);
8396       }
8397     }
8398   }
8399 
8400   // Special-case some of Darwin's platform-independence types by suggesting
8401   // casts to primitive types that are known to be large enough.
8402   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
8403   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
8404     QualType CastTy;
8405     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
8406     if (!CastTy.isNull()) {
8407       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
8408       // (long in ASTContext). Only complain to pedants.
8409       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
8410           (AT.isSizeT() || AT.isPtrdiffT()) &&
8411           AT.matchesType(S.Context, CastTy))
8412         Match = ArgType::NoMatchPedantic;
8413       IntendedTy = CastTy;
8414       ShouldNotPrintDirectly = true;
8415     }
8416   }
8417 
8418   // We may be able to offer a FixItHint if it is a supported type.
8419   PrintfSpecifier fixedFS = FS;
8420   bool Success =
8421       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
8422 
8423   if (Success) {
8424     // Get the fix string from the fixed format specifier
8425     SmallString<16> buf;
8426     llvm::raw_svector_ostream os(buf);
8427     fixedFS.toString(os);
8428 
8429     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
8430 
8431     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
8432       unsigned Diag;
8433       switch (Match) {
8434       case ArgType::Match: llvm_unreachable("expected non-matching");
8435       case ArgType::NoMatchPedantic:
8436         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8437         break;
8438       case ArgType::NoMatchTypeConfusion:
8439         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8440         break;
8441       case ArgType::NoMatch:
8442         Diag = diag::warn_format_conversion_argument_type_mismatch;
8443         break;
8444       }
8445 
8446       // In this case, the specifier is wrong and should be changed to match
8447       // the argument.
8448       EmitFormatDiagnostic(S.PDiag(Diag)
8449                                << AT.getRepresentativeTypeName(S.Context)
8450                                << IntendedTy << IsEnum << E->getSourceRange(),
8451                            E->getBeginLoc(),
8452                            /*IsStringLocation*/ false, SpecRange,
8453                            FixItHint::CreateReplacement(SpecRange, os.str()));
8454     } else {
8455       // The canonical type for formatting this value is different from the
8456       // actual type of the expression. (This occurs, for example, with Darwin's
8457       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
8458       // should be printed as 'long' for 64-bit compatibility.)
8459       // Rather than emitting a normal format/argument mismatch, we want to
8460       // add a cast to the recommended type (and correct the format string
8461       // if necessary).
8462       SmallString<16> CastBuf;
8463       llvm::raw_svector_ostream CastFix(CastBuf);
8464       CastFix << "(";
8465       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
8466       CastFix << ")";
8467 
8468       SmallVector<FixItHint,4> Hints;
8469       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
8470         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
8471 
8472       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
8473         // If there's already a cast present, just replace it.
8474         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
8475         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
8476 
8477       } else if (!requiresParensToAddCast(E)) {
8478         // If the expression has high enough precedence,
8479         // just write the C-style cast.
8480         Hints.push_back(
8481             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8482       } else {
8483         // Otherwise, add parens around the expression as well as the cast.
8484         CastFix << "(";
8485         Hints.push_back(
8486             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8487 
8488         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
8489         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
8490       }
8491 
8492       if (ShouldNotPrintDirectly) {
8493         // The expression has a type that should not be printed directly.
8494         // We extract the name from the typedef because we don't want to show
8495         // the underlying type in the diagnostic.
8496         StringRef Name;
8497         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
8498           Name = TypedefTy->getDecl()->getName();
8499         else
8500           Name = CastTyName;
8501         unsigned Diag = Match == ArgType::NoMatchPedantic
8502                             ? diag::warn_format_argument_needs_cast_pedantic
8503                             : diag::warn_format_argument_needs_cast;
8504         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
8505                                            << E->getSourceRange(),
8506                              E->getBeginLoc(), /*IsStringLocation=*/false,
8507                              SpecRange, Hints);
8508       } else {
8509         // In this case, the expression could be printed using a different
8510         // specifier, but we've decided that the specifier is probably correct
8511         // and we should cast instead. Just use the normal warning message.
8512         EmitFormatDiagnostic(
8513             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8514                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
8515                 << E->getSourceRange(),
8516             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
8517       }
8518     }
8519   } else {
8520     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
8521                                                    SpecifierLen);
8522     // Since the warning for passing non-POD types to variadic functions
8523     // was deferred until now, we emit a warning for non-POD
8524     // arguments here.
8525     switch (S.isValidVarArgType(ExprTy)) {
8526     case Sema::VAK_Valid:
8527     case Sema::VAK_ValidInCXX11: {
8528       unsigned Diag;
8529       switch (Match) {
8530       case ArgType::Match: llvm_unreachable("expected non-matching");
8531       case ArgType::NoMatchPedantic:
8532         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8533         break;
8534       case ArgType::NoMatchTypeConfusion:
8535         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8536         break;
8537       case ArgType::NoMatch:
8538         Diag = diag::warn_format_conversion_argument_type_mismatch;
8539         break;
8540       }
8541 
8542       EmitFormatDiagnostic(
8543           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
8544                         << IsEnum << CSR << E->getSourceRange(),
8545           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8546       break;
8547     }
8548     case Sema::VAK_Undefined:
8549     case Sema::VAK_MSVCUndefined:
8550       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
8551                                << S.getLangOpts().CPlusPlus11 << ExprTy
8552                                << CallType
8553                                << AT.getRepresentativeTypeName(S.Context) << CSR
8554                                << E->getSourceRange(),
8555                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8556       checkForCStrMembers(AT, E);
8557       break;
8558 
8559     case Sema::VAK_Invalid:
8560       if (ExprTy->isObjCObjectType())
8561         EmitFormatDiagnostic(
8562             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
8563                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
8564                 << AT.getRepresentativeTypeName(S.Context) << CSR
8565                 << E->getSourceRange(),
8566             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8567       else
8568         // FIXME: If this is an initializer list, suggest removing the braces
8569         // or inserting a cast to the target type.
8570         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
8571             << isa<InitListExpr>(E) << ExprTy << CallType
8572             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
8573       break;
8574     }
8575 
8576     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
8577            "format string specifier index out of range");
8578     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
8579   }
8580 
8581   return true;
8582 }
8583 
8584 //===--- CHECK: Scanf format string checking ------------------------------===//
8585 
8586 namespace {
8587 
8588 class CheckScanfHandler : public CheckFormatHandler {
8589 public:
8590   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
8591                     const Expr *origFormatExpr, Sema::FormatStringType type,
8592                     unsigned firstDataArg, unsigned numDataArgs,
8593                     const char *beg, bool hasVAListArg,
8594                     ArrayRef<const Expr *> Args, unsigned formatIdx,
8595                     bool inFunctionCall, Sema::VariadicCallType CallType,
8596                     llvm::SmallBitVector &CheckedVarArgs,
8597                     UncoveredArgHandler &UncoveredArg)
8598       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8599                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8600                            inFunctionCall, CallType, CheckedVarArgs,
8601                            UncoveredArg) {}
8602 
8603   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
8604                             const char *startSpecifier,
8605                             unsigned specifierLen) override;
8606 
8607   bool HandleInvalidScanfConversionSpecifier(
8608           const analyze_scanf::ScanfSpecifier &FS,
8609           const char *startSpecifier,
8610           unsigned specifierLen) override;
8611 
8612   void HandleIncompleteScanList(const char *start, const char *end) override;
8613 };
8614 
8615 } // namespace
8616 
8617 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
8618                                                  const char *end) {
8619   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
8620                        getLocationOfByte(end), /*IsStringLocation*/true,
8621                        getSpecifierRange(start, end - start));
8622 }
8623 
8624 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
8625                                         const analyze_scanf::ScanfSpecifier &FS,
8626                                         const char *startSpecifier,
8627                                         unsigned specifierLen) {
8628   const analyze_scanf::ScanfConversionSpecifier &CS =
8629     FS.getConversionSpecifier();
8630 
8631   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8632                                           getLocationOfByte(CS.getStart()),
8633                                           startSpecifier, specifierLen,
8634                                           CS.getStart(), CS.getLength());
8635 }
8636 
8637 bool CheckScanfHandler::HandleScanfSpecifier(
8638                                        const analyze_scanf::ScanfSpecifier &FS,
8639                                        const char *startSpecifier,
8640                                        unsigned specifierLen) {
8641   using namespace analyze_scanf;
8642   using namespace analyze_format_string;
8643 
8644   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
8645 
8646   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
8647   // be used to decide if we are using positional arguments consistently.
8648   if (FS.consumesDataArgument()) {
8649     if (atFirstArg) {
8650       atFirstArg = false;
8651       usesPositionalArgs = FS.usesPositionalArg();
8652     }
8653     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8654       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8655                                         startSpecifier, specifierLen);
8656       return false;
8657     }
8658   }
8659 
8660   // Check if the field with is non-zero.
8661   const OptionalAmount &Amt = FS.getFieldWidth();
8662   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
8663     if (Amt.getConstantAmount() == 0) {
8664       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
8665                                                    Amt.getConstantLength());
8666       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
8667                            getLocationOfByte(Amt.getStart()),
8668                            /*IsStringLocation*/true, R,
8669                            FixItHint::CreateRemoval(R));
8670     }
8671   }
8672 
8673   if (!FS.consumesDataArgument()) {
8674     // FIXME: Technically specifying a precision or field width here
8675     // makes no sense.  Worth issuing a warning at some point.
8676     return true;
8677   }
8678 
8679   // Consume the argument.
8680   unsigned argIndex = FS.getArgIndex();
8681   if (argIndex < NumDataArgs) {
8682       // The check to see if the argIndex is valid will come later.
8683       // We set the bit here because we may exit early from this
8684       // function if we encounter some other error.
8685     CoveredArgs.set(argIndex);
8686   }
8687 
8688   // Check the length modifier is valid with the given conversion specifier.
8689   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8690                                  S.getLangOpts()))
8691     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8692                                 diag::warn_format_nonsensical_length);
8693   else if (!FS.hasStandardLengthModifier())
8694     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8695   else if (!FS.hasStandardLengthConversionCombination())
8696     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8697                                 diag::warn_format_non_standard_conversion_spec);
8698 
8699   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8700     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8701 
8702   // The remaining checks depend on the data arguments.
8703   if (HasVAListArg)
8704     return true;
8705 
8706   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8707     return false;
8708 
8709   // Check that the argument type matches the format specifier.
8710   const Expr *Ex = getDataArg(argIndex);
8711   if (!Ex)
8712     return true;
8713 
8714   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
8715 
8716   if (!AT.isValid()) {
8717     return true;
8718   }
8719 
8720   analyze_format_string::ArgType::MatchKind Match =
8721       AT.matchesType(S.Context, Ex->getType());
8722   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
8723   if (Match == analyze_format_string::ArgType::Match)
8724     return true;
8725 
8726   ScanfSpecifier fixedFS = FS;
8727   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
8728                                  S.getLangOpts(), S.Context);
8729 
8730   unsigned Diag =
8731       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8732                : diag::warn_format_conversion_argument_type_mismatch;
8733 
8734   if (Success) {
8735     // Get the fix string from the fixed format specifier.
8736     SmallString<128> buf;
8737     llvm::raw_svector_ostream os(buf);
8738     fixedFS.toString(os);
8739 
8740     EmitFormatDiagnostic(
8741         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
8742                       << Ex->getType() << false << Ex->getSourceRange(),
8743         Ex->getBeginLoc(),
8744         /*IsStringLocation*/ false,
8745         getSpecifierRange(startSpecifier, specifierLen),
8746         FixItHint::CreateReplacement(
8747             getSpecifierRange(startSpecifier, specifierLen), os.str()));
8748   } else {
8749     EmitFormatDiagnostic(S.PDiag(Diag)
8750                              << AT.getRepresentativeTypeName(S.Context)
8751                              << Ex->getType() << false << Ex->getSourceRange(),
8752                          Ex->getBeginLoc(),
8753                          /*IsStringLocation*/ false,
8754                          getSpecifierRange(startSpecifier, specifierLen));
8755   }
8756 
8757   return true;
8758 }
8759 
8760 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
8761                               const Expr *OrigFormatExpr,
8762                               ArrayRef<const Expr *> Args,
8763                               bool HasVAListArg, unsigned format_idx,
8764                               unsigned firstDataArg,
8765                               Sema::FormatStringType Type,
8766                               bool inFunctionCall,
8767                               Sema::VariadicCallType CallType,
8768                               llvm::SmallBitVector &CheckedVarArgs,
8769                               UncoveredArgHandler &UncoveredArg,
8770                               bool IgnoreStringsWithoutSpecifiers) {
8771   // CHECK: is the format string a wide literal?
8772   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
8773     CheckFormatHandler::EmitFormatDiagnostic(
8774         S, inFunctionCall, Args[format_idx],
8775         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
8776         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8777     return;
8778   }
8779 
8780   // Str - The format string.  NOTE: this is NOT null-terminated!
8781   StringRef StrRef = FExpr->getString();
8782   const char *Str = StrRef.data();
8783   // Account for cases where the string literal is truncated in a declaration.
8784   const ConstantArrayType *T =
8785     S.Context.getAsConstantArrayType(FExpr->getType());
8786   assert(T && "String literal not of constant array type!");
8787   size_t TypeSize = T->getSize().getZExtValue();
8788   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8789   const unsigned numDataArgs = Args.size() - firstDataArg;
8790 
8791   if (IgnoreStringsWithoutSpecifiers &&
8792       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
8793           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
8794     return;
8795 
8796   // Emit a warning if the string literal is truncated and does not contain an
8797   // embedded null character.
8798   if (TypeSize <= StrRef.size() &&
8799       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
8800     CheckFormatHandler::EmitFormatDiagnostic(
8801         S, inFunctionCall, Args[format_idx],
8802         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
8803         FExpr->getBeginLoc(),
8804         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
8805     return;
8806   }
8807 
8808   // CHECK: empty format string?
8809   if (StrLen == 0 && numDataArgs > 0) {
8810     CheckFormatHandler::EmitFormatDiagnostic(
8811         S, inFunctionCall, Args[format_idx],
8812         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
8813         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8814     return;
8815   }
8816 
8817   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
8818       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
8819       Type == Sema::FST_OSTrace) {
8820     CheckPrintfHandler H(
8821         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
8822         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
8823         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
8824         CheckedVarArgs, UncoveredArg);
8825 
8826     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
8827                                                   S.getLangOpts(),
8828                                                   S.Context.getTargetInfo(),
8829                                             Type == Sema::FST_FreeBSDKPrintf))
8830       H.DoneProcessing();
8831   } else if (Type == Sema::FST_Scanf) {
8832     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
8833                         numDataArgs, Str, HasVAListArg, Args, format_idx,
8834                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
8835 
8836     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
8837                                                  S.getLangOpts(),
8838                                                  S.Context.getTargetInfo()))
8839       H.DoneProcessing();
8840   } // TODO: handle other formats
8841 }
8842 
8843 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
8844   // Str - The format string.  NOTE: this is NOT null-terminated!
8845   StringRef StrRef = FExpr->getString();
8846   const char *Str = StrRef.data();
8847   // Account for cases where the string literal is truncated in a declaration.
8848   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
8849   assert(T && "String literal not of constant array type!");
8850   size_t TypeSize = T->getSize().getZExtValue();
8851   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8852   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
8853                                                          getLangOpts(),
8854                                                          Context.getTargetInfo());
8855 }
8856 
8857 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
8858 
8859 // Returns the related absolute value function that is larger, of 0 if one
8860 // does not exist.
8861 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
8862   switch (AbsFunction) {
8863   default:
8864     return 0;
8865 
8866   case Builtin::BI__builtin_abs:
8867     return Builtin::BI__builtin_labs;
8868   case Builtin::BI__builtin_labs:
8869     return Builtin::BI__builtin_llabs;
8870   case Builtin::BI__builtin_llabs:
8871     return 0;
8872 
8873   case Builtin::BI__builtin_fabsf:
8874     return Builtin::BI__builtin_fabs;
8875   case Builtin::BI__builtin_fabs:
8876     return Builtin::BI__builtin_fabsl;
8877   case Builtin::BI__builtin_fabsl:
8878     return 0;
8879 
8880   case Builtin::BI__builtin_cabsf:
8881     return Builtin::BI__builtin_cabs;
8882   case Builtin::BI__builtin_cabs:
8883     return Builtin::BI__builtin_cabsl;
8884   case Builtin::BI__builtin_cabsl:
8885     return 0;
8886 
8887   case Builtin::BIabs:
8888     return Builtin::BIlabs;
8889   case Builtin::BIlabs:
8890     return Builtin::BIllabs;
8891   case Builtin::BIllabs:
8892     return 0;
8893 
8894   case Builtin::BIfabsf:
8895     return Builtin::BIfabs;
8896   case Builtin::BIfabs:
8897     return Builtin::BIfabsl;
8898   case Builtin::BIfabsl:
8899     return 0;
8900 
8901   case Builtin::BIcabsf:
8902    return Builtin::BIcabs;
8903   case Builtin::BIcabs:
8904     return Builtin::BIcabsl;
8905   case Builtin::BIcabsl:
8906     return 0;
8907   }
8908 }
8909 
8910 // Returns the argument type of the absolute value function.
8911 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
8912                                              unsigned AbsType) {
8913   if (AbsType == 0)
8914     return QualType();
8915 
8916   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
8917   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
8918   if (Error != ASTContext::GE_None)
8919     return QualType();
8920 
8921   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
8922   if (!FT)
8923     return QualType();
8924 
8925   if (FT->getNumParams() != 1)
8926     return QualType();
8927 
8928   return FT->getParamType(0);
8929 }
8930 
8931 // Returns the best absolute value function, or zero, based on type and
8932 // current absolute value function.
8933 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
8934                                    unsigned AbsFunctionKind) {
8935   unsigned BestKind = 0;
8936   uint64_t ArgSize = Context.getTypeSize(ArgType);
8937   for (unsigned Kind = AbsFunctionKind; Kind != 0;
8938        Kind = getLargerAbsoluteValueFunction(Kind)) {
8939     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
8940     if (Context.getTypeSize(ParamType) >= ArgSize) {
8941       if (BestKind == 0)
8942         BestKind = Kind;
8943       else if (Context.hasSameType(ParamType, ArgType)) {
8944         BestKind = Kind;
8945         break;
8946       }
8947     }
8948   }
8949   return BestKind;
8950 }
8951 
8952 enum AbsoluteValueKind {
8953   AVK_Integer,
8954   AVK_Floating,
8955   AVK_Complex
8956 };
8957 
8958 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
8959   if (T->isIntegralOrEnumerationType())
8960     return AVK_Integer;
8961   if (T->isRealFloatingType())
8962     return AVK_Floating;
8963   if (T->isAnyComplexType())
8964     return AVK_Complex;
8965 
8966   llvm_unreachable("Type not integer, floating, or complex");
8967 }
8968 
8969 // Changes the absolute value function to a different type.  Preserves whether
8970 // the function is a builtin.
8971 static unsigned changeAbsFunction(unsigned AbsKind,
8972                                   AbsoluteValueKind ValueKind) {
8973   switch (ValueKind) {
8974   case AVK_Integer:
8975     switch (AbsKind) {
8976     default:
8977       return 0;
8978     case Builtin::BI__builtin_fabsf:
8979     case Builtin::BI__builtin_fabs:
8980     case Builtin::BI__builtin_fabsl:
8981     case Builtin::BI__builtin_cabsf:
8982     case Builtin::BI__builtin_cabs:
8983     case Builtin::BI__builtin_cabsl:
8984       return Builtin::BI__builtin_abs;
8985     case Builtin::BIfabsf:
8986     case Builtin::BIfabs:
8987     case Builtin::BIfabsl:
8988     case Builtin::BIcabsf:
8989     case Builtin::BIcabs:
8990     case Builtin::BIcabsl:
8991       return Builtin::BIabs;
8992     }
8993   case AVK_Floating:
8994     switch (AbsKind) {
8995     default:
8996       return 0;
8997     case Builtin::BI__builtin_abs:
8998     case Builtin::BI__builtin_labs:
8999     case Builtin::BI__builtin_llabs:
9000     case Builtin::BI__builtin_cabsf:
9001     case Builtin::BI__builtin_cabs:
9002     case Builtin::BI__builtin_cabsl:
9003       return Builtin::BI__builtin_fabsf;
9004     case Builtin::BIabs:
9005     case Builtin::BIlabs:
9006     case Builtin::BIllabs:
9007     case Builtin::BIcabsf:
9008     case Builtin::BIcabs:
9009     case Builtin::BIcabsl:
9010       return Builtin::BIfabsf;
9011     }
9012   case AVK_Complex:
9013     switch (AbsKind) {
9014     default:
9015       return 0;
9016     case Builtin::BI__builtin_abs:
9017     case Builtin::BI__builtin_labs:
9018     case Builtin::BI__builtin_llabs:
9019     case Builtin::BI__builtin_fabsf:
9020     case Builtin::BI__builtin_fabs:
9021     case Builtin::BI__builtin_fabsl:
9022       return Builtin::BI__builtin_cabsf;
9023     case Builtin::BIabs:
9024     case Builtin::BIlabs:
9025     case Builtin::BIllabs:
9026     case Builtin::BIfabsf:
9027     case Builtin::BIfabs:
9028     case Builtin::BIfabsl:
9029       return Builtin::BIcabsf;
9030     }
9031   }
9032   llvm_unreachable("Unable to convert function");
9033 }
9034 
9035 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
9036   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
9037   if (!FnInfo)
9038     return 0;
9039 
9040   switch (FDecl->getBuiltinID()) {
9041   default:
9042     return 0;
9043   case Builtin::BI__builtin_abs:
9044   case Builtin::BI__builtin_fabs:
9045   case Builtin::BI__builtin_fabsf:
9046   case Builtin::BI__builtin_fabsl:
9047   case Builtin::BI__builtin_labs:
9048   case Builtin::BI__builtin_llabs:
9049   case Builtin::BI__builtin_cabs:
9050   case Builtin::BI__builtin_cabsf:
9051   case Builtin::BI__builtin_cabsl:
9052   case Builtin::BIabs:
9053   case Builtin::BIlabs:
9054   case Builtin::BIllabs:
9055   case Builtin::BIfabs:
9056   case Builtin::BIfabsf:
9057   case Builtin::BIfabsl:
9058   case Builtin::BIcabs:
9059   case Builtin::BIcabsf:
9060   case Builtin::BIcabsl:
9061     return FDecl->getBuiltinID();
9062   }
9063   llvm_unreachable("Unknown Builtin type");
9064 }
9065 
9066 // If the replacement is valid, emit a note with replacement function.
9067 // Additionally, suggest including the proper header if not already included.
9068 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
9069                             unsigned AbsKind, QualType ArgType) {
9070   bool EmitHeaderHint = true;
9071   const char *HeaderName = nullptr;
9072   const char *FunctionName = nullptr;
9073   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
9074     FunctionName = "std::abs";
9075     if (ArgType->isIntegralOrEnumerationType()) {
9076       HeaderName = "cstdlib";
9077     } else if (ArgType->isRealFloatingType()) {
9078       HeaderName = "cmath";
9079     } else {
9080       llvm_unreachable("Invalid Type");
9081     }
9082 
9083     // Lookup all std::abs
9084     if (NamespaceDecl *Std = S.getStdNamespace()) {
9085       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
9086       R.suppressDiagnostics();
9087       S.LookupQualifiedName(R, Std);
9088 
9089       for (const auto *I : R) {
9090         const FunctionDecl *FDecl = nullptr;
9091         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
9092           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
9093         } else {
9094           FDecl = dyn_cast<FunctionDecl>(I);
9095         }
9096         if (!FDecl)
9097           continue;
9098 
9099         // Found std::abs(), check that they are the right ones.
9100         if (FDecl->getNumParams() != 1)
9101           continue;
9102 
9103         // Check that the parameter type can handle the argument.
9104         QualType ParamType = FDecl->getParamDecl(0)->getType();
9105         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
9106             S.Context.getTypeSize(ArgType) <=
9107                 S.Context.getTypeSize(ParamType)) {
9108           // Found a function, don't need the header hint.
9109           EmitHeaderHint = false;
9110           break;
9111         }
9112       }
9113     }
9114   } else {
9115     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
9116     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
9117 
9118     if (HeaderName) {
9119       DeclarationName DN(&S.Context.Idents.get(FunctionName));
9120       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
9121       R.suppressDiagnostics();
9122       S.LookupName(R, S.getCurScope());
9123 
9124       if (R.isSingleResult()) {
9125         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
9126         if (FD && FD->getBuiltinID() == AbsKind) {
9127           EmitHeaderHint = false;
9128         } else {
9129           return;
9130         }
9131       } else if (!R.empty()) {
9132         return;
9133       }
9134     }
9135   }
9136 
9137   S.Diag(Loc, diag::note_replace_abs_function)
9138       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
9139 
9140   if (!HeaderName)
9141     return;
9142 
9143   if (!EmitHeaderHint)
9144     return;
9145 
9146   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
9147                                                     << FunctionName;
9148 }
9149 
9150 template <std::size_t StrLen>
9151 static bool IsStdFunction(const FunctionDecl *FDecl,
9152                           const char (&Str)[StrLen]) {
9153   if (!FDecl)
9154     return false;
9155   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
9156     return false;
9157   if (!FDecl->isInStdNamespace())
9158     return false;
9159 
9160   return true;
9161 }
9162 
9163 // Warn when using the wrong abs() function.
9164 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
9165                                       const FunctionDecl *FDecl) {
9166   if (Call->getNumArgs() != 1)
9167     return;
9168 
9169   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
9170   bool IsStdAbs = IsStdFunction(FDecl, "abs");
9171   if (AbsKind == 0 && !IsStdAbs)
9172     return;
9173 
9174   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9175   QualType ParamType = Call->getArg(0)->getType();
9176 
9177   // Unsigned types cannot be negative.  Suggest removing the absolute value
9178   // function call.
9179   if (ArgType->isUnsignedIntegerType()) {
9180     const char *FunctionName =
9181         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
9182     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
9183     Diag(Call->getExprLoc(), diag::note_remove_abs)
9184         << FunctionName
9185         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
9186     return;
9187   }
9188 
9189   // Taking the absolute value of a pointer is very suspicious, they probably
9190   // wanted to index into an array, dereference a pointer, call a function, etc.
9191   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
9192     unsigned DiagType = 0;
9193     if (ArgType->isFunctionType())
9194       DiagType = 1;
9195     else if (ArgType->isArrayType())
9196       DiagType = 2;
9197 
9198     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
9199     return;
9200   }
9201 
9202   // std::abs has overloads which prevent most of the absolute value problems
9203   // from occurring.
9204   if (IsStdAbs)
9205     return;
9206 
9207   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
9208   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
9209 
9210   // The argument and parameter are the same kind.  Check if they are the right
9211   // size.
9212   if (ArgValueKind == ParamValueKind) {
9213     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
9214       return;
9215 
9216     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
9217     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
9218         << FDecl << ArgType << ParamType;
9219 
9220     if (NewAbsKind == 0)
9221       return;
9222 
9223     emitReplacement(*this, Call->getExprLoc(),
9224                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9225     return;
9226   }
9227 
9228   // ArgValueKind != ParamValueKind
9229   // The wrong type of absolute value function was used.  Attempt to find the
9230   // proper one.
9231   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
9232   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
9233   if (NewAbsKind == 0)
9234     return;
9235 
9236   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
9237       << FDecl << ParamValueKind << ArgValueKind;
9238 
9239   emitReplacement(*this, Call->getExprLoc(),
9240                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9241 }
9242 
9243 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
9244 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
9245                                 const FunctionDecl *FDecl) {
9246   if (!Call || !FDecl) return;
9247 
9248   // Ignore template specializations and macros.
9249   if (inTemplateInstantiation()) return;
9250   if (Call->getExprLoc().isMacroID()) return;
9251 
9252   // Only care about the one template argument, two function parameter std::max
9253   if (Call->getNumArgs() != 2) return;
9254   if (!IsStdFunction(FDecl, "max")) return;
9255   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
9256   if (!ArgList) return;
9257   if (ArgList->size() != 1) return;
9258 
9259   // Check that template type argument is unsigned integer.
9260   const auto& TA = ArgList->get(0);
9261   if (TA.getKind() != TemplateArgument::Type) return;
9262   QualType ArgType = TA.getAsType();
9263   if (!ArgType->isUnsignedIntegerType()) return;
9264 
9265   // See if either argument is a literal zero.
9266   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
9267     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
9268     if (!MTE) return false;
9269     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
9270     if (!Num) return false;
9271     if (Num->getValue() != 0) return false;
9272     return true;
9273   };
9274 
9275   const Expr *FirstArg = Call->getArg(0);
9276   const Expr *SecondArg = Call->getArg(1);
9277   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
9278   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
9279 
9280   // Only warn when exactly one argument is zero.
9281   if (IsFirstArgZero == IsSecondArgZero) return;
9282 
9283   SourceRange FirstRange = FirstArg->getSourceRange();
9284   SourceRange SecondRange = SecondArg->getSourceRange();
9285 
9286   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
9287 
9288   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
9289       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
9290 
9291   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
9292   SourceRange RemovalRange;
9293   if (IsFirstArgZero) {
9294     RemovalRange = SourceRange(FirstRange.getBegin(),
9295                                SecondRange.getBegin().getLocWithOffset(-1));
9296   } else {
9297     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
9298                                SecondRange.getEnd());
9299   }
9300 
9301   Diag(Call->getExprLoc(), diag::note_remove_max_call)
9302         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
9303         << FixItHint::CreateRemoval(RemovalRange);
9304 }
9305 
9306 //===--- CHECK: Standard memory functions ---------------------------------===//
9307 
9308 /// Takes the expression passed to the size_t parameter of functions
9309 /// such as memcmp, strncat, etc and warns if it's a comparison.
9310 ///
9311 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
9312 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
9313                                            IdentifierInfo *FnName,
9314                                            SourceLocation FnLoc,
9315                                            SourceLocation RParenLoc) {
9316   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
9317   if (!Size)
9318     return false;
9319 
9320   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
9321   if (!Size->isComparisonOp() && !Size->isLogicalOp())
9322     return false;
9323 
9324   SourceRange SizeRange = Size->getSourceRange();
9325   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
9326       << SizeRange << FnName;
9327   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
9328       << FnName
9329       << FixItHint::CreateInsertion(
9330              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
9331       << FixItHint::CreateRemoval(RParenLoc);
9332   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
9333       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
9334       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
9335                                     ")");
9336 
9337   return true;
9338 }
9339 
9340 /// Determine whether the given type is or contains a dynamic class type
9341 /// (e.g., whether it has a vtable).
9342 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
9343                                                      bool &IsContained) {
9344   // Look through array types while ignoring qualifiers.
9345   const Type *Ty = T->getBaseElementTypeUnsafe();
9346   IsContained = false;
9347 
9348   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
9349   RD = RD ? RD->getDefinition() : nullptr;
9350   if (!RD || RD->isInvalidDecl())
9351     return nullptr;
9352 
9353   if (RD->isDynamicClass())
9354     return RD;
9355 
9356   // Check all the fields.  If any bases were dynamic, the class is dynamic.
9357   // It's impossible for a class to transitively contain itself by value, so
9358   // infinite recursion is impossible.
9359   for (auto *FD : RD->fields()) {
9360     bool SubContained;
9361     if (const CXXRecordDecl *ContainedRD =
9362             getContainedDynamicClass(FD->getType(), SubContained)) {
9363       IsContained = true;
9364       return ContainedRD;
9365     }
9366   }
9367 
9368   return nullptr;
9369 }
9370 
9371 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
9372   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
9373     if (Unary->getKind() == UETT_SizeOf)
9374       return Unary;
9375   return nullptr;
9376 }
9377 
9378 /// If E is a sizeof expression, returns its argument expression,
9379 /// otherwise returns NULL.
9380 static const Expr *getSizeOfExprArg(const Expr *E) {
9381   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9382     if (!SizeOf->isArgumentType())
9383       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
9384   return nullptr;
9385 }
9386 
9387 /// If E is a sizeof expression, returns its argument type.
9388 static QualType getSizeOfArgType(const Expr *E) {
9389   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9390     return SizeOf->getTypeOfArgument();
9391   return QualType();
9392 }
9393 
9394 namespace {
9395 
9396 struct SearchNonTrivialToInitializeField
9397     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
9398   using Super =
9399       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
9400 
9401   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
9402 
9403   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
9404                      SourceLocation SL) {
9405     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9406       asDerived().visitArray(PDIK, AT, SL);
9407       return;
9408     }
9409 
9410     Super::visitWithKind(PDIK, FT, SL);
9411   }
9412 
9413   void visitARCStrong(QualType FT, SourceLocation SL) {
9414     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9415   }
9416   void visitARCWeak(QualType FT, SourceLocation SL) {
9417     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9418   }
9419   void visitStruct(QualType FT, SourceLocation SL) {
9420     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9421       visit(FD->getType(), FD->getLocation());
9422   }
9423   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
9424                   const ArrayType *AT, SourceLocation SL) {
9425     visit(getContext().getBaseElementType(AT), SL);
9426   }
9427   void visitTrivial(QualType FT, SourceLocation SL) {}
9428 
9429   static void diag(QualType RT, const Expr *E, Sema &S) {
9430     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
9431   }
9432 
9433   ASTContext &getContext() { return S.getASTContext(); }
9434 
9435   const Expr *E;
9436   Sema &S;
9437 };
9438 
9439 struct SearchNonTrivialToCopyField
9440     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
9441   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
9442 
9443   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
9444 
9445   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
9446                      SourceLocation SL) {
9447     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9448       asDerived().visitArray(PCK, AT, SL);
9449       return;
9450     }
9451 
9452     Super::visitWithKind(PCK, FT, SL);
9453   }
9454 
9455   void visitARCStrong(QualType FT, SourceLocation SL) {
9456     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9457   }
9458   void visitARCWeak(QualType FT, SourceLocation SL) {
9459     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9460   }
9461   void visitStruct(QualType FT, SourceLocation SL) {
9462     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9463       visit(FD->getType(), FD->getLocation());
9464   }
9465   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
9466                   SourceLocation SL) {
9467     visit(getContext().getBaseElementType(AT), SL);
9468   }
9469   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
9470                 SourceLocation SL) {}
9471   void visitTrivial(QualType FT, SourceLocation SL) {}
9472   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
9473 
9474   static void diag(QualType RT, const Expr *E, Sema &S) {
9475     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
9476   }
9477 
9478   ASTContext &getContext() { return S.getASTContext(); }
9479 
9480   const Expr *E;
9481   Sema &S;
9482 };
9483 
9484 }
9485 
9486 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
9487 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
9488   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
9489 
9490   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
9491     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
9492       return false;
9493 
9494     return doesExprLikelyComputeSize(BO->getLHS()) ||
9495            doesExprLikelyComputeSize(BO->getRHS());
9496   }
9497 
9498   return getAsSizeOfExpr(SizeofExpr) != nullptr;
9499 }
9500 
9501 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
9502 ///
9503 /// \code
9504 ///   #define MACRO 0
9505 ///   foo(MACRO);
9506 ///   foo(0);
9507 /// \endcode
9508 ///
9509 /// This should return true for the first call to foo, but not for the second
9510 /// (regardless of whether foo is a macro or function).
9511 static bool isArgumentExpandedFromMacro(SourceManager &SM,
9512                                         SourceLocation CallLoc,
9513                                         SourceLocation ArgLoc) {
9514   if (!CallLoc.isMacroID())
9515     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
9516 
9517   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
9518          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
9519 }
9520 
9521 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
9522 /// last two arguments transposed.
9523 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
9524   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
9525     return;
9526 
9527   const Expr *SizeArg =
9528     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
9529 
9530   auto isLiteralZero = [](const Expr *E) {
9531     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
9532   };
9533 
9534   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
9535   SourceLocation CallLoc = Call->getRParenLoc();
9536   SourceManager &SM = S.getSourceManager();
9537   if (isLiteralZero(SizeArg) &&
9538       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
9539 
9540     SourceLocation DiagLoc = SizeArg->getExprLoc();
9541 
9542     // Some platforms #define bzero to __builtin_memset. See if this is the
9543     // case, and if so, emit a better diagnostic.
9544     if (BId == Builtin::BIbzero ||
9545         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
9546                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
9547       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
9548       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
9549     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
9550       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
9551       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
9552     }
9553     return;
9554   }
9555 
9556   // If the second argument to a memset is a sizeof expression and the third
9557   // isn't, this is also likely an error. This should catch
9558   // 'memset(buf, sizeof(buf), 0xff)'.
9559   if (BId == Builtin::BImemset &&
9560       doesExprLikelyComputeSize(Call->getArg(1)) &&
9561       !doesExprLikelyComputeSize(Call->getArg(2))) {
9562     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
9563     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
9564     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
9565     return;
9566   }
9567 }
9568 
9569 /// Check for dangerous or invalid arguments to memset().
9570 ///
9571 /// This issues warnings on known problematic, dangerous or unspecified
9572 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
9573 /// function calls.
9574 ///
9575 /// \param Call The call expression to diagnose.
9576 void Sema::CheckMemaccessArguments(const CallExpr *Call,
9577                                    unsigned BId,
9578                                    IdentifierInfo *FnName) {
9579   assert(BId != 0);
9580 
9581   // It is possible to have a non-standard definition of memset.  Validate
9582   // we have enough arguments, and if not, abort further checking.
9583   unsigned ExpectedNumArgs =
9584       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
9585   if (Call->getNumArgs() < ExpectedNumArgs)
9586     return;
9587 
9588   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
9589                       BId == Builtin::BIstrndup ? 1 : 2);
9590   unsigned LenArg =
9591       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
9592   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
9593 
9594   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
9595                                      Call->getBeginLoc(), Call->getRParenLoc()))
9596     return;
9597 
9598   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
9599   CheckMemaccessSize(*this, BId, Call);
9600 
9601   // We have special checking when the length is a sizeof expression.
9602   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
9603   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
9604   llvm::FoldingSetNodeID SizeOfArgID;
9605 
9606   // Although widely used, 'bzero' is not a standard function. Be more strict
9607   // with the argument types before allowing diagnostics and only allow the
9608   // form bzero(ptr, sizeof(...)).
9609   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9610   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
9611     return;
9612 
9613   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
9614     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
9615     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
9616 
9617     QualType DestTy = Dest->getType();
9618     QualType PointeeTy;
9619     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
9620       PointeeTy = DestPtrTy->getPointeeType();
9621 
9622       // Never warn about void type pointers. This can be used to suppress
9623       // false positives.
9624       if (PointeeTy->isVoidType())
9625         continue;
9626 
9627       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
9628       // actually comparing the expressions for equality. Because computing the
9629       // expression IDs can be expensive, we only do this if the diagnostic is
9630       // enabled.
9631       if (SizeOfArg &&
9632           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
9633                            SizeOfArg->getExprLoc())) {
9634         // We only compute IDs for expressions if the warning is enabled, and
9635         // cache the sizeof arg's ID.
9636         if (SizeOfArgID == llvm::FoldingSetNodeID())
9637           SizeOfArg->Profile(SizeOfArgID, Context, true);
9638         llvm::FoldingSetNodeID DestID;
9639         Dest->Profile(DestID, Context, true);
9640         if (DestID == SizeOfArgID) {
9641           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
9642           //       over sizeof(src) as well.
9643           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
9644           StringRef ReadableName = FnName->getName();
9645 
9646           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
9647             if (UnaryOp->getOpcode() == UO_AddrOf)
9648               ActionIdx = 1; // If its an address-of operator, just remove it.
9649           if (!PointeeTy->isIncompleteType() &&
9650               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
9651             ActionIdx = 2; // If the pointee's size is sizeof(char),
9652                            // suggest an explicit length.
9653 
9654           // If the function is defined as a builtin macro, do not show macro
9655           // expansion.
9656           SourceLocation SL = SizeOfArg->getExprLoc();
9657           SourceRange DSR = Dest->getSourceRange();
9658           SourceRange SSR = SizeOfArg->getSourceRange();
9659           SourceManager &SM = getSourceManager();
9660 
9661           if (SM.isMacroArgExpansion(SL)) {
9662             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
9663             SL = SM.getSpellingLoc(SL);
9664             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
9665                              SM.getSpellingLoc(DSR.getEnd()));
9666             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
9667                              SM.getSpellingLoc(SSR.getEnd()));
9668           }
9669 
9670           DiagRuntimeBehavior(SL, SizeOfArg,
9671                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
9672                                 << ReadableName
9673                                 << PointeeTy
9674                                 << DestTy
9675                                 << DSR
9676                                 << SSR);
9677           DiagRuntimeBehavior(SL, SizeOfArg,
9678                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
9679                                 << ActionIdx
9680                                 << SSR);
9681 
9682           break;
9683         }
9684       }
9685 
9686       // Also check for cases where the sizeof argument is the exact same
9687       // type as the memory argument, and where it points to a user-defined
9688       // record type.
9689       if (SizeOfArgTy != QualType()) {
9690         if (PointeeTy->isRecordType() &&
9691             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
9692           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
9693                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
9694                                 << FnName << SizeOfArgTy << ArgIdx
9695                                 << PointeeTy << Dest->getSourceRange()
9696                                 << LenExpr->getSourceRange());
9697           break;
9698         }
9699       }
9700     } else if (DestTy->isArrayType()) {
9701       PointeeTy = DestTy;
9702     }
9703 
9704     if (PointeeTy == QualType())
9705       continue;
9706 
9707     // Always complain about dynamic classes.
9708     bool IsContained;
9709     if (const CXXRecordDecl *ContainedRD =
9710             getContainedDynamicClass(PointeeTy, IsContained)) {
9711 
9712       unsigned OperationType = 0;
9713       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
9714       // "overwritten" if we're warning about the destination for any call
9715       // but memcmp; otherwise a verb appropriate to the call.
9716       if (ArgIdx != 0 || IsCmp) {
9717         if (BId == Builtin::BImemcpy)
9718           OperationType = 1;
9719         else if(BId == Builtin::BImemmove)
9720           OperationType = 2;
9721         else if (IsCmp)
9722           OperationType = 3;
9723       }
9724 
9725       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9726                           PDiag(diag::warn_dyn_class_memaccess)
9727                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
9728                               << IsContained << ContainedRD << OperationType
9729                               << Call->getCallee()->getSourceRange());
9730     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
9731              BId != Builtin::BImemset)
9732       DiagRuntimeBehavior(
9733         Dest->getExprLoc(), Dest,
9734         PDiag(diag::warn_arc_object_memaccess)
9735           << ArgIdx << FnName << PointeeTy
9736           << Call->getCallee()->getSourceRange());
9737     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
9738       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
9739           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
9740         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9741                             PDiag(diag::warn_cstruct_memaccess)
9742                                 << ArgIdx << FnName << PointeeTy << 0);
9743         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
9744       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
9745                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
9746         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9747                             PDiag(diag::warn_cstruct_memaccess)
9748                                 << ArgIdx << FnName << PointeeTy << 1);
9749         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
9750       } else {
9751         continue;
9752       }
9753     } else
9754       continue;
9755 
9756     DiagRuntimeBehavior(
9757       Dest->getExprLoc(), Dest,
9758       PDiag(diag::note_bad_memaccess_silence)
9759         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
9760     break;
9761   }
9762 }
9763 
9764 // A little helper routine: ignore addition and subtraction of integer literals.
9765 // This intentionally does not ignore all integer constant expressions because
9766 // we don't want to remove sizeof().
9767 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
9768   Ex = Ex->IgnoreParenCasts();
9769 
9770   while (true) {
9771     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
9772     if (!BO || !BO->isAdditiveOp())
9773       break;
9774 
9775     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
9776     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
9777 
9778     if (isa<IntegerLiteral>(RHS))
9779       Ex = LHS;
9780     else if (isa<IntegerLiteral>(LHS))
9781       Ex = RHS;
9782     else
9783       break;
9784   }
9785 
9786   return Ex;
9787 }
9788 
9789 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
9790                                                       ASTContext &Context) {
9791   // Only handle constant-sized or VLAs, but not flexible members.
9792   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
9793     // Only issue the FIXIT for arrays of size > 1.
9794     if (CAT->getSize().getSExtValue() <= 1)
9795       return false;
9796   } else if (!Ty->isVariableArrayType()) {
9797     return false;
9798   }
9799   return true;
9800 }
9801 
9802 // Warn if the user has made the 'size' argument to strlcpy or strlcat
9803 // be the size of the source, instead of the destination.
9804 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
9805                                     IdentifierInfo *FnName) {
9806 
9807   // Don't crash if the user has the wrong number of arguments
9808   unsigned NumArgs = Call->getNumArgs();
9809   if ((NumArgs != 3) && (NumArgs != 4))
9810     return;
9811 
9812   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
9813   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
9814   const Expr *CompareWithSrc = nullptr;
9815 
9816   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
9817                                      Call->getBeginLoc(), Call->getRParenLoc()))
9818     return;
9819 
9820   // Look for 'strlcpy(dst, x, sizeof(x))'
9821   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
9822     CompareWithSrc = Ex;
9823   else {
9824     // Look for 'strlcpy(dst, x, strlen(x))'
9825     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
9826       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
9827           SizeCall->getNumArgs() == 1)
9828         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
9829     }
9830   }
9831 
9832   if (!CompareWithSrc)
9833     return;
9834 
9835   // Determine if the argument to sizeof/strlen is equal to the source
9836   // argument.  In principle there's all kinds of things you could do
9837   // here, for instance creating an == expression and evaluating it with
9838   // EvaluateAsBooleanCondition, but this uses a more direct technique:
9839   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
9840   if (!SrcArgDRE)
9841     return;
9842 
9843   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
9844   if (!CompareWithSrcDRE ||
9845       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
9846     return;
9847 
9848   const Expr *OriginalSizeArg = Call->getArg(2);
9849   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
9850       << OriginalSizeArg->getSourceRange() << FnName;
9851 
9852   // Output a FIXIT hint if the destination is an array (rather than a
9853   // pointer to an array).  This could be enhanced to handle some
9854   // pointers if we know the actual size, like if DstArg is 'array+2'
9855   // we could say 'sizeof(array)-2'.
9856   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
9857   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
9858     return;
9859 
9860   SmallString<128> sizeString;
9861   llvm::raw_svector_ostream OS(sizeString);
9862   OS << "sizeof(";
9863   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9864   OS << ")";
9865 
9866   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
9867       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
9868                                       OS.str());
9869 }
9870 
9871 /// Check if two expressions refer to the same declaration.
9872 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
9873   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
9874     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
9875       return D1->getDecl() == D2->getDecl();
9876   return false;
9877 }
9878 
9879 static const Expr *getStrlenExprArg(const Expr *E) {
9880   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9881     const FunctionDecl *FD = CE->getDirectCallee();
9882     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
9883       return nullptr;
9884     return CE->getArg(0)->IgnoreParenCasts();
9885   }
9886   return nullptr;
9887 }
9888 
9889 // Warn on anti-patterns as the 'size' argument to strncat.
9890 // The correct size argument should look like following:
9891 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
9892 void Sema::CheckStrncatArguments(const CallExpr *CE,
9893                                  IdentifierInfo *FnName) {
9894   // Don't crash if the user has the wrong number of arguments.
9895   if (CE->getNumArgs() < 3)
9896     return;
9897   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
9898   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
9899   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
9900 
9901   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
9902                                      CE->getRParenLoc()))
9903     return;
9904 
9905   // Identify common expressions, which are wrongly used as the size argument
9906   // to strncat and may lead to buffer overflows.
9907   unsigned PatternType = 0;
9908   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
9909     // - sizeof(dst)
9910     if (referToTheSameDecl(SizeOfArg, DstArg))
9911       PatternType = 1;
9912     // - sizeof(src)
9913     else if (referToTheSameDecl(SizeOfArg, SrcArg))
9914       PatternType = 2;
9915   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
9916     if (BE->getOpcode() == BO_Sub) {
9917       const Expr *L = BE->getLHS()->IgnoreParenCasts();
9918       const Expr *R = BE->getRHS()->IgnoreParenCasts();
9919       // - sizeof(dst) - strlen(dst)
9920       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
9921           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
9922         PatternType = 1;
9923       // - sizeof(src) - (anything)
9924       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
9925         PatternType = 2;
9926     }
9927   }
9928 
9929   if (PatternType == 0)
9930     return;
9931 
9932   // Generate the diagnostic.
9933   SourceLocation SL = LenArg->getBeginLoc();
9934   SourceRange SR = LenArg->getSourceRange();
9935   SourceManager &SM = getSourceManager();
9936 
9937   // If the function is defined as a builtin macro, do not show macro expansion.
9938   if (SM.isMacroArgExpansion(SL)) {
9939     SL = SM.getSpellingLoc(SL);
9940     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
9941                      SM.getSpellingLoc(SR.getEnd()));
9942   }
9943 
9944   // Check if the destination is an array (rather than a pointer to an array).
9945   QualType DstTy = DstArg->getType();
9946   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
9947                                                                     Context);
9948   if (!isKnownSizeArray) {
9949     if (PatternType == 1)
9950       Diag(SL, diag::warn_strncat_wrong_size) << SR;
9951     else
9952       Diag(SL, diag::warn_strncat_src_size) << SR;
9953     return;
9954   }
9955 
9956   if (PatternType == 1)
9957     Diag(SL, diag::warn_strncat_large_size) << SR;
9958   else
9959     Diag(SL, diag::warn_strncat_src_size) << SR;
9960 
9961   SmallString<128> sizeString;
9962   llvm::raw_svector_ostream OS(sizeString);
9963   OS << "sizeof(";
9964   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9965   OS << ") - ";
9966   OS << "strlen(";
9967   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9968   OS << ") - 1";
9969 
9970   Diag(SL, diag::note_strncat_wrong_size)
9971     << FixItHint::CreateReplacement(SR, OS.str());
9972 }
9973 
9974 void
9975 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
9976                          SourceLocation ReturnLoc,
9977                          bool isObjCMethod,
9978                          const AttrVec *Attrs,
9979                          const FunctionDecl *FD) {
9980   // Check if the return value is null but should not be.
9981   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
9982        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
9983       CheckNonNullExpr(*this, RetValExp))
9984     Diag(ReturnLoc, diag::warn_null_ret)
9985       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
9986 
9987   // C++11 [basic.stc.dynamic.allocation]p4:
9988   //   If an allocation function declared with a non-throwing
9989   //   exception-specification fails to allocate storage, it shall return
9990   //   a null pointer. Any other allocation function that fails to allocate
9991   //   storage shall indicate failure only by throwing an exception [...]
9992   if (FD) {
9993     OverloadedOperatorKind Op = FD->getOverloadedOperator();
9994     if (Op == OO_New || Op == OO_Array_New) {
9995       const FunctionProtoType *Proto
9996         = FD->getType()->castAs<FunctionProtoType>();
9997       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
9998           CheckNonNullExpr(*this, RetValExp))
9999         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
10000           << FD << getLangOpts().CPlusPlus11;
10001     }
10002   }
10003 }
10004 
10005 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
10006 
10007 /// Check for comparisons of floating point operands using != and ==.
10008 /// Issue a warning if these are no self-comparisons, as they are not likely
10009 /// to do what the programmer intended.
10010 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
10011   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
10012   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
10013 
10014   // Special case: check for x == x (which is OK).
10015   // Do not emit warnings for such cases.
10016   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
10017     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
10018       if (DRL->getDecl() == DRR->getDecl())
10019         return;
10020 
10021   // Special case: check for comparisons against literals that can be exactly
10022   //  represented by APFloat.  In such cases, do not emit a warning.  This
10023   //  is a heuristic: often comparison against such literals are used to
10024   //  detect if a value in a variable has not changed.  This clearly can
10025   //  lead to false negatives.
10026   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
10027     if (FLL->isExact())
10028       return;
10029   } else
10030     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
10031       if (FLR->isExact())
10032         return;
10033 
10034   // Check for comparisons with builtin types.
10035   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
10036     if (CL->getBuiltinCallee())
10037       return;
10038 
10039   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
10040     if (CR->getBuiltinCallee())
10041       return;
10042 
10043   // Emit the diagnostic.
10044   Diag(Loc, diag::warn_floatingpoint_eq)
10045     << LHS->getSourceRange() << RHS->getSourceRange();
10046 }
10047 
10048 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
10049 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
10050 
10051 namespace {
10052 
10053 /// Structure recording the 'active' range of an integer-valued
10054 /// expression.
10055 struct IntRange {
10056   /// The number of bits active in the int.
10057   unsigned Width;
10058 
10059   /// True if the int is known not to have negative values.
10060   bool NonNegative;
10061 
10062   IntRange(unsigned Width, bool NonNegative)
10063       : Width(Width), NonNegative(NonNegative) {}
10064 
10065   /// Returns the range of the bool type.
10066   static IntRange forBoolType() {
10067     return IntRange(1, true);
10068   }
10069 
10070   /// Returns the range of an opaque value of the given integral type.
10071   static IntRange forValueOfType(ASTContext &C, QualType T) {
10072     return forValueOfCanonicalType(C,
10073                           T->getCanonicalTypeInternal().getTypePtr());
10074   }
10075 
10076   /// Returns the range of an opaque value of a canonical integral type.
10077   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
10078     assert(T->isCanonicalUnqualified());
10079 
10080     if (const VectorType *VT = dyn_cast<VectorType>(T))
10081       T = VT->getElementType().getTypePtr();
10082     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10083       T = CT->getElementType().getTypePtr();
10084     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10085       T = AT->getValueType().getTypePtr();
10086 
10087     if (!C.getLangOpts().CPlusPlus) {
10088       // For enum types in C code, use the underlying datatype.
10089       if (const EnumType *ET = dyn_cast<EnumType>(T))
10090         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
10091     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
10092       // For enum types in C++, use the known bit width of the enumerators.
10093       EnumDecl *Enum = ET->getDecl();
10094       // In C++11, enums can have a fixed underlying type. Use this type to
10095       // compute the range.
10096       if (Enum->isFixed()) {
10097         return IntRange(C.getIntWidth(QualType(T, 0)),
10098                         !ET->isSignedIntegerOrEnumerationType());
10099       }
10100 
10101       unsigned NumPositive = Enum->getNumPositiveBits();
10102       unsigned NumNegative = Enum->getNumNegativeBits();
10103 
10104       if (NumNegative == 0)
10105         return IntRange(NumPositive, true/*NonNegative*/);
10106       else
10107         return IntRange(std::max(NumPositive + 1, NumNegative),
10108                         false/*NonNegative*/);
10109     }
10110 
10111     if (const auto *EIT = dyn_cast<ExtIntType>(T))
10112       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10113 
10114     const BuiltinType *BT = cast<BuiltinType>(T);
10115     assert(BT->isInteger());
10116 
10117     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10118   }
10119 
10120   /// Returns the "target" range of a canonical integral type, i.e.
10121   /// the range of values expressible in the type.
10122   ///
10123   /// This matches forValueOfCanonicalType except that enums have the
10124   /// full range of their type, not the range of their enumerators.
10125   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
10126     assert(T->isCanonicalUnqualified());
10127 
10128     if (const VectorType *VT = dyn_cast<VectorType>(T))
10129       T = VT->getElementType().getTypePtr();
10130     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10131       T = CT->getElementType().getTypePtr();
10132     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10133       T = AT->getValueType().getTypePtr();
10134     if (const EnumType *ET = dyn_cast<EnumType>(T))
10135       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
10136 
10137     if (const auto *EIT = dyn_cast<ExtIntType>(T))
10138       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10139 
10140     const BuiltinType *BT = cast<BuiltinType>(T);
10141     assert(BT->isInteger());
10142 
10143     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10144   }
10145 
10146   /// Returns the supremum of two ranges: i.e. their conservative merge.
10147   static IntRange join(IntRange L, IntRange R) {
10148     return IntRange(std::max(L.Width, R.Width),
10149                     L.NonNegative && R.NonNegative);
10150   }
10151 
10152   /// Returns the infinum of two ranges: i.e. their aggressive merge.
10153   static IntRange meet(IntRange L, IntRange R) {
10154     return IntRange(std::min(L.Width, R.Width),
10155                     L.NonNegative || R.NonNegative);
10156   }
10157 };
10158 
10159 } // namespace
10160 
10161 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
10162                               unsigned MaxWidth) {
10163   if (value.isSigned() && value.isNegative())
10164     return IntRange(value.getMinSignedBits(), false);
10165 
10166   if (value.getBitWidth() > MaxWidth)
10167     value = value.trunc(MaxWidth);
10168 
10169   // isNonNegative() just checks the sign bit without considering
10170   // signedness.
10171   return IntRange(value.getActiveBits(), true);
10172 }
10173 
10174 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
10175                               unsigned MaxWidth) {
10176   if (result.isInt())
10177     return GetValueRange(C, result.getInt(), MaxWidth);
10178 
10179   if (result.isVector()) {
10180     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
10181     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
10182       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
10183       R = IntRange::join(R, El);
10184     }
10185     return R;
10186   }
10187 
10188   if (result.isComplexInt()) {
10189     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
10190     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
10191     return IntRange::join(R, I);
10192   }
10193 
10194   // This can happen with lossless casts to intptr_t of "based" lvalues.
10195   // Assume it might use arbitrary bits.
10196   // FIXME: The only reason we need to pass the type in here is to get
10197   // the sign right on this one case.  It would be nice if APValue
10198   // preserved this.
10199   assert(result.isLValue() || result.isAddrLabelDiff());
10200   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
10201 }
10202 
10203 static QualType GetExprType(const Expr *E) {
10204   QualType Ty = E->getType();
10205   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
10206     Ty = AtomicRHS->getValueType();
10207   return Ty;
10208 }
10209 
10210 /// Pseudo-evaluate the given integer expression, estimating the
10211 /// range of values it might take.
10212 ///
10213 /// \param MaxWidth - the width to which the value will be truncated
10214 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
10215                              bool InConstantContext) {
10216   E = E->IgnoreParens();
10217 
10218   // Try a full evaluation first.
10219   Expr::EvalResult result;
10220   if (E->EvaluateAsRValue(result, C, InConstantContext))
10221     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
10222 
10223   // I think we only want to look through implicit casts here; if the
10224   // user has an explicit widening cast, we should treat the value as
10225   // being of the new, wider type.
10226   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
10227     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
10228       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext);
10229 
10230     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
10231 
10232     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
10233                          CE->getCastKind() == CK_BooleanToSignedIntegral;
10234 
10235     // Assume that non-integer casts can span the full range of the type.
10236     if (!isIntegerCast)
10237       return OutputTypeRange;
10238 
10239     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
10240                                      std::min(MaxWidth, OutputTypeRange.Width),
10241                                      InConstantContext);
10242 
10243     // Bail out if the subexpr's range is as wide as the cast type.
10244     if (SubRange.Width >= OutputTypeRange.Width)
10245       return OutputTypeRange;
10246 
10247     // Otherwise, we take the smaller width, and we're non-negative if
10248     // either the output type or the subexpr is.
10249     return IntRange(SubRange.Width,
10250                     SubRange.NonNegative || OutputTypeRange.NonNegative);
10251   }
10252 
10253   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
10254     // If we can fold the condition, just take that operand.
10255     bool CondResult;
10256     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
10257       return GetExprRange(C,
10258                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
10259                           MaxWidth, InConstantContext);
10260 
10261     // Otherwise, conservatively merge.
10262     IntRange L =
10263         GetExprRange(C, CO->getTrueExpr(), MaxWidth, InConstantContext);
10264     IntRange R =
10265         GetExprRange(C, CO->getFalseExpr(), MaxWidth, InConstantContext);
10266     return IntRange::join(L, R);
10267   }
10268 
10269   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
10270     switch (BO->getOpcode()) {
10271     case BO_Cmp:
10272       llvm_unreachable("builtin <=> should have class type");
10273 
10274     // Boolean-valued operations are single-bit and positive.
10275     case BO_LAnd:
10276     case BO_LOr:
10277     case BO_LT:
10278     case BO_GT:
10279     case BO_LE:
10280     case BO_GE:
10281     case BO_EQ:
10282     case BO_NE:
10283       return IntRange::forBoolType();
10284 
10285     // The type of the assignments is the type of the LHS, so the RHS
10286     // is not necessarily the same type.
10287     case BO_MulAssign:
10288     case BO_DivAssign:
10289     case BO_RemAssign:
10290     case BO_AddAssign:
10291     case BO_SubAssign:
10292     case BO_XorAssign:
10293     case BO_OrAssign:
10294       // TODO: bitfields?
10295       return IntRange::forValueOfType(C, GetExprType(E));
10296 
10297     // Simple assignments just pass through the RHS, which will have
10298     // been coerced to the LHS type.
10299     case BO_Assign:
10300       // TODO: bitfields?
10301       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10302 
10303     // Operations with opaque sources are black-listed.
10304     case BO_PtrMemD:
10305     case BO_PtrMemI:
10306       return IntRange::forValueOfType(C, GetExprType(E));
10307 
10308     // Bitwise-and uses the *infinum* of the two source ranges.
10309     case BO_And:
10310     case BO_AndAssign:
10311       return IntRange::meet(
10312           GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext),
10313           GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext));
10314 
10315     // Left shift gets black-listed based on a judgement call.
10316     case BO_Shl:
10317       // ...except that we want to treat '1 << (blah)' as logically
10318       // positive.  It's an important idiom.
10319       if (IntegerLiteral *I
10320             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
10321         if (I->getValue() == 1) {
10322           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
10323           return IntRange(R.Width, /*NonNegative*/ true);
10324         }
10325       }
10326       LLVM_FALLTHROUGH;
10327 
10328     case BO_ShlAssign:
10329       return IntRange::forValueOfType(C, GetExprType(E));
10330 
10331     // Right shift by a constant can narrow its left argument.
10332     case BO_Shr:
10333     case BO_ShrAssign: {
10334       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
10335 
10336       // If the shift amount is a positive constant, drop the width by
10337       // that much.
10338       llvm::APSInt shift;
10339       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
10340           shift.isNonNegative()) {
10341         unsigned zext = shift.getZExtValue();
10342         if (zext >= L.Width)
10343           L.Width = (L.NonNegative ? 0 : 1);
10344         else
10345           L.Width -= zext;
10346       }
10347 
10348       return L;
10349     }
10350 
10351     // Comma acts as its right operand.
10352     case BO_Comma:
10353       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10354 
10355     // Black-list pointer subtractions.
10356     case BO_Sub:
10357       if (BO->getLHS()->getType()->isPointerType())
10358         return IntRange::forValueOfType(C, GetExprType(E));
10359       break;
10360 
10361     // The width of a division result is mostly determined by the size
10362     // of the LHS.
10363     case BO_Div: {
10364       // Don't 'pre-truncate' the operands.
10365       unsigned opWidth = C.getIntWidth(GetExprType(E));
10366       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
10367 
10368       // If the divisor is constant, use that.
10369       llvm::APSInt divisor;
10370       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
10371         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
10372         if (log2 >= L.Width)
10373           L.Width = (L.NonNegative ? 0 : 1);
10374         else
10375           L.Width = std::min(L.Width - log2, MaxWidth);
10376         return L;
10377       }
10378 
10379       // Otherwise, just use the LHS's width.
10380       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
10381       return IntRange(L.Width, L.NonNegative && R.NonNegative);
10382     }
10383 
10384     // The result of a remainder can't be larger than the result of
10385     // either side.
10386     case BO_Rem: {
10387       // Don't 'pre-truncate' the operands.
10388       unsigned opWidth = C.getIntWidth(GetExprType(E));
10389       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
10390       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
10391 
10392       IntRange meet = IntRange::meet(L, R);
10393       meet.Width = std::min(meet.Width, MaxWidth);
10394       return meet;
10395     }
10396 
10397     // The default behavior is okay for these.
10398     case BO_Mul:
10399     case BO_Add:
10400     case BO_Xor:
10401     case BO_Or:
10402       break;
10403     }
10404 
10405     // The default case is to treat the operation as if it were closed
10406     // on the narrowest type that encompasses both operands.
10407     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
10408     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10409     return IntRange::join(L, R);
10410   }
10411 
10412   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
10413     switch (UO->getOpcode()) {
10414     // Boolean-valued operations are white-listed.
10415     case UO_LNot:
10416       return IntRange::forBoolType();
10417 
10418     // Operations with opaque sources are black-listed.
10419     case UO_Deref:
10420     case UO_AddrOf: // should be impossible
10421       return IntRange::forValueOfType(C, GetExprType(E));
10422 
10423     default:
10424       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext);
10425     }
10426   }
10427 
10428   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
10429     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext);
10430 
10431   if (const auto *BitField = E->getSourceBitField())
10432     return IntRange(BitField->getBitWidthValue(C),
10433                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
10434 
10435   return IntRange::forValueOfType(C, GetExprType(E));
10436 }
10437 
10438 static IntRange GetExprRange(ASTContext &C, const Expr *E,
10439                              bool InConstantContext) {
10440   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext);
10441 }
10442 
10443 /// Checks whether the given value, which currently has the given
10444 /// source semantics, has the same value when coerced through the
10445 /// target semantics.
10446 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
10447                                  const llvm::fltSemantics &Src,
10448                                  const llvm::fltSemantics &Tgt) {
10449   llvm::APFloat truncated = value;
10450 
10451   bool ignored;
10452   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
10453   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
10454 
10455   return truncated.bitwiseIsEqual(value);
10456 }
10457 
10458 /// Checks whether the given value, which currently has the given
10459 /// source semantics, has the same value when coerced through the
10460 /// target semantics.
10461 ///
10462 /// The value might be a vector of floats (or a complex number).
10463 static bool IsSameFloatAfterCast(const APValue &value,
10464                                  const llvm::fltSemantics &Src,
10465                                  const llvm::fltSemantics &Tgt) {
10466   if (value.isFloat())
10467     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
10468 
10469   if (value.isVector()) {
10470     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
10471       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
10472         return false;
10473     return true;
10474   }
10475 
10476   assert(value.isComplexFloat());
10477   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
10478           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
10479 }
10480 
10481 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
10482                                        bool IsListInit = false);
10483 
10484 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
10485   // Suppress cases where we are comparing against an enum constant.
10486   if (const DeclRefExpr *DR =
10487       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
10488     if (isa<EnumConstantDecl>(DR->getDecl()))
10489       return true;
10490 
10491   // Suppress cases where the value is expanded from a macro, unless that macro
10492   // is how a language represents a boolean literal. This is the case in both C
10493   // and Objective-C.
10494   SourceLocation BeginLoc = E->getBeginLoc();
10495   if (BeginLoc.isMacroID()) {
10496     StringRef MacroName = Lexer::getImmediateMacroName(
10497         BeginLoc, S.getSourceManager(), S.getLangOpts());
10498     return MacroName != "YES" && MacroName != "NO" &&
10499            MacroName != "true" && MacroName != "false";
10500   }
10501 
10502   return false;
10503 }
10504 
10505 static bool isKnownToHaveUnsignedValue(Expr *E) {
10506   return E->getType()->isIntegerType() &&
10507          (!E->getType()->isSignedIntegerType() ||
10508           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
10509 }
10510 
10511 namespace {
10512 /// The promoted range of values of a type. In general this has the
10513 /// following structure:
10514 ///
10515 ///     |-----------| . . . |-----------|
10516 ///     ^           ^       ^           ^
10517 ///    Min       HoleMin  HoleMax      Max
10518 ///
10519 /// ... where there is only a hole if a signed type is promoted to unsigned
10520 /// (in which case Min and Max are the smallest and largest representable
10521 /// values).
10522 struct PromotedRange {
10523   // Min, or HoleMax if there is a hole.
10524   llvm::APSInt PromotedMin;
10525   // Max, or HoleMin if there is a hole.
10526   llvm::APSInt PromotedMax;
10527 
10528   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
10529     if (R.Width == 0)
10530       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
10531     else if (R.Width >= BitWidth && !Unsigned) {
10532       // Promotion made the type *narrower*. This happens when promoting
10533       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
10534       // Treat all values of 'signed int' as being in range for now.
10535       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
10536       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
10537     } else {
10538       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
10539                         .extOrTrunc(BitWidth);
10540       PromotedMin.setIsUnsigned(Unsigned);
10541 
10542       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
10543                         .extOrTrunc(BitWidth);
10544       PromotedMax.setIsUnsigned(Unsigned);
10545     }
10546   }
10547 
10548   // Determine whether this range is contiguous (has no hole).
10549   bool isContiguous() const { return PromotedMin <= PromotedMax; }
10550 
10551   // Where a constant value is within the range.
10552   enum ComparisonResult {
10553     LT = 0x1,
10554     LE = 0x2,
10555     GT = 0x4,
10556     GE = 0x8,
10557     EQ = 0x10,
10558     NE = 0x20,
10559     InRangeFlag = 0x40,
10560 
10561     Less = LE | LT | NE,
10562     Min = LE | InRangeFlag,
10563     InRange = InRangeFlag,
10564     Max = GE | InRangeFlag,
10565     Greater = GE | GT | NE,
10566 
10567     OnlyValue = LE | GE | EQ | InRangeFlag,
10568     InHole = NE
10569   };
10570 
10571   ComparisonResult compare(const llvm::APSInt &Value) const {
10572     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
10573            Value.isUnsigned() == PromotedMin.isUnsigned());
10574     if (!isContiguous()) {
10575       assert(Value.isUnsigned() && "discontiguous range for signed compare");
10576       if (Value.isMinValue()) return Min;
10577       if (Value.isMaxValue()) return Max;
10578       if (Value >= PromotedMin) return InRange;
10579       if (Value <= PromotedMax) return InRange;
10580       return InHole;
10581     }
10582 
10583     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
10584     case -1: return Less;
10585     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
10586     case 1:
10587       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
10588       case -1: return InRange;
10589       case 0: return Max;
10590       case 1: return Greater;
10591       }
10592     }
10593 
10594     llvm_unreachable("impossible compare result");
10595   }
10596 
10597   static llvm::Optional<StringRef>
10598   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
10599     if (Op == BO_Cmp) {
10600       ComparisonResult LTFlag = LT, GTFlag = GT;
10601       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
10602 
10603       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
10604       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
10605       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
10606       return llvm::None;
10607     }
10608 
10609     ComparisonResult TrueFlag, FalseFlag;
10610     if (Op == BO_EQ) {
10611       TrueFlag = EQ;
10612       FalseFlag = NE;
10613     } else if (Op == BO_NE) {
10614       TrueFlag = NE;
10615       FalseFlag = EQ;
10616     } else {
10617       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
10618         TrueFlag = LT;
10619         FalseFlag = GE;
10620       } else {
10621         TrueFlag = GT;
10622         FalseFlag = LE;
10623       }
10624       if (Op == BO_GE || Op == BO_LE)
10625         std::swap(TrueFlag, FalseFlag);
10626     }
10627     if (R & TrueFlag)
10628       return StringRef("true");
10629     if (R & FalseFlag)
10630       return StringRef("false");
10631     return llvm::None;
10632   }
10633 };
10634 }
10635 
10636 static bool HasEnumType(Expr *E) {
10637   // Strip off implicit integral promotions.
10638   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
10639     if (ICE->getCastKind() != CK_IntegralCast &&
10640         ICE->getCastKind() != CK_NoOp)
10641       break;
10642     E = ICE->getSubExpr();
10643   }
10644 
10645   return E->getType()->isEnumeralType();
10646 }
10647 
10648 static int classifyConstantValue(Expr *Constant) {
10649   // The values of this enumeration are used in the diagnostics
10650   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
10651   enum ConstantValueKind {
10652     Miscellaneous = 0,
10653     LiteralTrue,
10654     LiteralFalse
10655   };
10656   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
10657     return BL->getValue() ? ConstantValueKind::LiteralTrue
10658                           : ConstantValueKind::LiteralFalse;
10659   return ConstantValueKind::Miscellaneous;
10660 }
10661 
10662 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
10663                                         Expr *Constant, Expr *Other,
10664                                         const llvm::APSInt &Value,
10665                                         bool RhsConstant) {
10666   if (S.inTemplateInstantiation())
10667     return false;
10668 
10669   Expr *OriginalOther = Other;
10670 
10671   Constant = Constant->IgnoreParenImpCasts();
10672   Other = Other->IgnoreParenImpCasts();
10673 
10674   // Suppress warnings on tautological comparisons between values of the same
10675   // enumeration type. There are only two ways we could warn on this:
10676   //  - If the constant is outside the range of representable values of
10677   //    the enumeration. In such a case, we should warn about the cast
10678   //    to enumeration type, not about the comparison.
10679   //  - If the constant is the maximum / minimum in-range value. For an
10680   //    enumeratin type, such comparisons can be meaningful and useful.
10681   if (Constant->getType()->isEnumeralType() &&
10682       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
10683     return false;
10684 
10685   // TODO: Investigate using GetExprRange() to get tighter bounds
10686   // on the bit ranges.
10687   QualType OtherT = Other->getType();
10688   if (const auto *AT = OtherT->getAs<AtomicType>())
10689     OtherT = AT->getValueType();
10690   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
10691 
10692   // Special case for ObjC BOOL on targets where its a typedef for a signed char
10693   // (Namely, macOS).
10694   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
10695                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
10696                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
10697 
10698   // Whether we're treating Other as being a bool because of the form of
10699   // expression despite it having another type (typically 'int' in C).
10700   bool OtherIsBooleanDespiteType =
10701       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
10702   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
10703     OtherRange = IntRange::forBoolType();
10704 
10705   // Determine the promoted range of the other type and see if a comparison of
10706   // the constant against that range is tautological.
10707   PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
10708                                    Value.isUnsigned());
10709   auto Cmp = OtherPromotedRange.compare(Value);
10710   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
10711   if (!Result)
10712     return false;
10713 
10714   // Suppress the diagnostic for an in-range comparison if the constant comes
10715   // from a macro or enumerator. We don't want to diagnose
10716   //
10717   //   some_long_value <= INT_MAX
10718   //
10719   // when sizeof(int) == sizeof(long).
10720   bool InRange = Cmp & PromotedRange::InRangeFlag;
10721   if (InRange && IsEnumConstOrFromMacro(S, Constant))
10722     return false;
10723 
10724   // If this is a comparison to an enum constant, include that
10725   // constant in the diagnostic.
10726   const EnumConstantDecl *ED = nullptr;
10727   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
10728     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
10729 
10730   // Should be enough for uint128 (39 decimal digits)
10731   SmallString<64> PrettySourceValue;
10732   llvm::raw_svector_ostream OS(PrettySourceValue);
10733   if (ED) {
10734     OS << '\'' << *ED << "' (" << Value << ")";
10735   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
10736                Constant->IgnoreParenImpCasts())) {
10737     OS << (BL->getValue() ? "YES" : "NO");
10738   } else {
10739     OS << Value;
10740   }
10741 
10742   if (IsObjCSignedCharBool) {
10743     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10744                           S.PDiag(diag::warn_tautological_compare_objc_bool)
10745                               << OS.str() << *Result);
10746     return true;
10747   }
10748 
10749   // FIXME: We use a somewhat different formatting for the in-range cases and
10750   // cases involving boolean values for historical reasons. We should pick a
10751   // consistent way of presenting these diagnostics.
10752   if (!InRange || Other->isKnownToHaveBooleanValue()) {
10753 
10754     S.DiagRuntimeBehavior(
10755         E->getOperatorLoc(), E,
10756         S.PDiag(!InRange ? diag::warn_out_of_range_compare
10757                          : diag::warn_tautological_bool_compare)
10758             << OS.str() << classifyConstantValue(Constant) << OtherT
10759             << OtherIsBooleanDespiteType << *Result
10760             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
10761   } else {
10762     unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
10763                         ? (HasEnumType(OriginalOther)
10764                                ? diag::warn_unsigned_enum_always_true_comparison
10765                                : diag::warn_unsigned_always_true_comparison)
10766                         : diag::warn_tautological_constant_compare;
10767 
10768     S.Diag(E->getOperatorLoc(), Diag)
10769         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
10770         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
10771   }
10772 
10773   return true;
10774 }
10775 
10776 /// Analyze the operands of the given comparison.  Implements the
10777 /// fallback case from AnalyzeComparison.
10778 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
10779   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10780   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10781 }
10782 
10783 /// Implements -Wsign-compare.
10784 ///
10785 /// \param E the binary operator to check for warnings
10786 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
10787   // The type the comparison is being performed in.
10788   QualType T = E->getLHS()->getType();
10789 
10790   // Only analyze comparison operators where both sides have been converted to
10791   // the same type.
10792   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
10793     return AnalyzeImpConvsInComparison(S, E);
10794 
10795   // Don't analyze value-dependent comparisons directly.
10796   if (E->isValueDependent())
10797     return AnalyzeImpConvsInComparison(S, E);
10798 
10799   Expr *LHS = E->getLHS();
10800   Expr *RHS = E->getRHS();
10801 
10802   if (T->isIntegralType(S.Context)) {
10803     llvm::APSInt RHSValue;
10804     llvm::APSInt LHSValue;
10805 
10806     bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
10807     bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
10808 
10809     // We don't care about expressions whose result is a constant.
10810     if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
10811       return AnalyzeImpConvsInComparison(S, E);
10812 
10813     // We only care about expressions where just one side is literal
10814     if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
10815       // Is the constant on the RHS or LHS?
10816       const bool RhsConstant = IsRHSIntegralLiteral;
10817       Expr *Const = RhsConstant ? RHS : LHS;
10818       Expr *Other = RhsConstant ? LHS : RHS;
10819       const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
10820 
10821       // Check whether an integer constant comparison results in a value
10822       // of 'true' or 'false'.
10823       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
10824         return AnalyzeImpConvsInComparison(S, E);
10825     }
10826   }
10827 
10828   if (!T->hasUnsignedIntegerRepresentation()) {
10829     // We don't do anything special if this isn't an unsigned integral
10830     // comparison:  we're only interested in integral comparisons, and
10831     // signed comparisons only happen in cases we don't care to warn about.
10832     return AnalyzeImpConvsInComparison(S, E);
10833   }
10834 
10835   LHS = LHS->IgnoreParenImpCasts();
10836   RHS = RHS->IgnoreParenImpCasts();
10837 
10838   if (!S.getLangOpts().CPlusPlus) {
10839     // Avoid warning about comparison of integers with different signs when
10840     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
10841     // the type of `E`.
10842     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
10843       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10844     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
10845       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10846   }
10847 
10848   // Check to see if one of the (unmodified) operands is of different
10849   // signedness.
10850   Expr *signedOperand, *unsignedOperand;
10851   if (LHS->getType()->hasSignedIntegerRepresentation()) {
10852     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
10853            "unsigned comparison between two signed integer expressions?");
10854     signedOperand = LHS;
10855     unsignedOperand = RHS;
10856   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
10857     signedOperand = RHS;
10858     unsignedOperand = LHS;
10859   } else {
10860     return AnalyzeImpConvsInComparison(S, E);
10861   }
10862 
10863   // Otherwise, calculate the effective range of the signed operand.
10864   IntRange signedRange =
10865       GetExprRange(S.Context, signedOperand, S.isConstantEvaluated());
10866 
10867   // Go ahead and analyze implicit conversions in the operands.  Note
10868   // that we skip the implicit conversions on both sides.
10869   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
10870   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
10871 
10872   // If the signed range is non-negative, -Wsign-compare won't fire.
10873   if (signedRange.NonNegative)
10874     return;
10875 
10876   // For (in)equality comparisons, if the unsigned operand is a
10877   // constant which cannot collide with a overflowed signed operand,
10878   // then reinterpreting the signed operand as unsigned will not
10879   // change the result of the comparison.
10880   if (E->isEqualityOp()) {
10881     unsigned comparisonWidth = S.Context.getIntWidth(T);
10882     IntRange unsignedRange =
10883         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated());
10884 
10885     // We should never be unable to prove that the unsigned operand is
10886     // non-negative.
10887     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
10888 
10889     if (unsignedRange.Width < comparisonWidth)
10890       return;
10891   }
10892 
10893   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10894                         S.PDiag(diag::warn_mixed_sign_comparison)
10895                             << LHS->getType() << RHS->getType()
10896                             << LHS->getSourceRange() << RHS->getSourceRange());
10897 }
10898 
10899 /// Analyzes an attempt to assign the given value to a bitfield.
10900 ///
10901 /// Returns true if there was something fishy about the attempt.
10902 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
10903                                       SourceLocation InitLoc) {
10904   assert(Bitfield->isBitField());
10905   if (Bitfield->isInvalidDecl())
10906     return false;
10907 
10908   // White-list bool bitfields.
10909   QualType BitfieldType = Bitfield->getType();
10910   if (BitfieldType->isBooleanType())
10911      return false;
10912 
10913   if (BitfieldType->isEnumeralType()) {
10914     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
10915     // If the underlying enum type was not explicitly specified as an unsigned
10916     // type and the enum contain only positive values, MSVC++ will cause an
10917     // inconsistency by storing this as a signed type.
10918     if (S.getLangOpts().CPlusPlus11 &&
10919         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
10920         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
10921         BitfieldEnumDecl->getNumNegativeBits() == 0) {
10922       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
10923         << BitfieldEnumDecl->getNameAsString();
10924     }
10925   }
10926 
10927   if (Bitfield->getType()->isBooleanType())
10928     return false;
10929 
10930   // Ignore value- or type-dependent expressions.
10931   if (Bitfield->getBitWidth()->isValueDependent() ||
10932       Bitfield->getBitWidth()->isTypeDependent() ||
10933       Init->isValueDependent() ||
10934       Init->isTypeDependent())
10935     return false;
10936 
10937   Expr *OriginalInit = Init->IgnoreParenImpCasts();
10938   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
10939 
10940   Expr::EvalResult Result;
10941   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
10942                                    Expr::SE_AllowSideEffects)) {
10943     // The RHS is not constant.  If the RHS has an enum type, make sure the
10944     // bitfield is wide enough to hold all the values of the enum without
10945     // truncation.
10946     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
10947       EnumDecl *ED = EnumTy->getDecl();
10948       bool SignedBitfield = BitfieldType->isSignedIntegerType();
10949 
10950       // Enum types are implicitly signed on Windows, so check if there are any
10951       // negative enumerators to see if the enum was intended to be signed or
10952       // not.
10953       bool SignedEnum = ED->getNumNegativeBits() > 0;
10954 
10955       // Check for surprising sign changes when assigning enum values to a
10956       // bitfield of different signedness.  If the bitfield is signed and we
10957       // have exactly the right number of bits to store this unsigned enum,
10958       // suggest changing the enum to an unsigned type. This typically happens
10959       // on Windows where unfixed enums always use an underlying type of 'int'.
10960       unsigned DiagID = 0;
10961       if (SignedEnum && !SignedBitfield) {
10962         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
10963       } else if (SignedBitfield && !SignedEnum &&
10964                  ED->getNumPositiveBits() == FieldWidth) {
10965         DiagID = diag::warn_signed_bitfield_enum_conversion;
10966       }
10967 
10968       if (DiagID) {
10969         S.Diag(InitLoc, DiagID) << Bitfield << ED;
10970         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
10971         SourceRange TypeRange =
10972             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
10973         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
10974             << SignedEnum << TypeRange;
10975       }
10976 
10977       // Compute the required bitwidth. If the enum has negative values, we need
10978       // one more bit than the normal number of positive bits to represent the
10979       // sign bit.
10980       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
10981                                                   ED->getNumNegativeBits())
10982                                        : ED->getNumPositiveBits();
10983 
10984       // Check the bitwidth.
10985       if (BitsNeeded > FieldWidth) {
10986         Expr *WidthExpr = Bitfield->getBitWidth();
10987         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
10988             << Bitfield << ED;
10989         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
10990             << BitsNeeded << ED << WidthExpr->getSourceRange();
10991       }
10992     }
10993 
10994     return false;
10995   }
10996 
10997   llvm::APSInt Value = Result.Val.getInt();
10998 
10999   unsigned OriginalWidth = Value.getBitWidth();
11000 
11001   if (!Value.isSigned() || Value.isNegative())
11002     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
11003       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
11004         OriginalWidth = Value.getMinSignedBits();
11005 
11006   if (OriginalWidth <= FieldWidth)
11007     return false;
11008 
11009   // Compute the value which the bitfield will contain.
11010   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
11011   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
11012 
11013   // Check whether the stored value is equal to the original value.
11014   TruncatedValue = TruncatedValue.extend(OriginalWidth);
11015   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
11016     return false;
11017 
11018   // Special-case bitfields of width 1: booleans are naturally 0/1, and
11019   // therefore don't strictly fit into a signed bitfield of width 1.
11020   if (FieldWidth == 1 && Value == 1)
11021     return false;
11022 
11023   std::string PrettyValue = Value.toString(10);
11024   std::string PrettyTrunc = TruncatedValue.toString(10);
11025 
11026   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
11027     << PrettyValue << PrettyTrunc << OriginalInit->getType()
11028     << Init->getSourceRange();
11029 
11030   return true;
11031 }
11032 
11033 /// Analyze the given simple or compound assignment for warning-worthy
11034 /// operations.
11035 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
11036   // Just recurse on the LHS.
11037   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11038 
11039   // We want to recurse on the RHS as normal unless we're assigning to
11040   // a bitfield.
11041   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
11042     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
11043                                   E->getOperatorLoc())) {
11044       // Recurse, ignoring any implicit conversions on the RHS.
11045       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
11046                                         E->getOperatorLoc());
11047     }
11048   }
11049 
11050   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11051 
11052   // Diagnose implicitly sequentially-consistent atomic assignment.
11053   if (E->getLHS()->getType()->isAtomicType())
11054     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
11055 }
11056 
11057 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
11058 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
11059                             SourceLocation CContext, unsigned diag,
11060                             bool pruneControlFlow = false) {
11061   if (pruneControlFlow) {
11062     S.DiagRuntimeBehavior(E->getExprLoc(), E,
11063                           S.PDiag(diag)
11064                               << SourceType << T << E->getSourceRange()
11065                               << SourceRange(CContext));
11066     return;
11067   }
11068   S.Diag(E->getExprLoc(), diag)
11069     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
11070 }
11071 
11072 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
11073 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
11074                             SourceLocation CContext,
11075                             unsigned diag, bool pruneControlFlow = false) {
11076   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
11077 }
11078 
11079 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
11080   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
11081       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
11082 }
11083 
11084 static void adornObjCBoolConversionDiagWithTernaryFixit(
11085     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
11086   Expr *Ignored = SourceExpr->IgnoreImplicit();
11087   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
11088     Ignored = OVE->getSourceExpr();
11089   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
11090                      isa<BinaryOperator>(Ignored) ||
11091                      isa<CXXOperatorCallExpr>(Ignored);
11092   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
11093   if (NeedsParens)
11094     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
11095             << FixItHint::CreateInsertion(EndLoc, ")");
11096   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
11097 }
11098 
11099 /// Diagnose an implicit cast from a floating point value to an integer value.
11100 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
11101                                     SourceLocation CContext) {
11102   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
11103   const bool PruneWarnings = S.inTemplateInstantiation();
11104 
11105   Expr *InnerE = E->IgnoreParenImpCasts();
11106   // We also want to warn on, e.g., "int i = -1.234"
11107   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
11108     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
11109       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
11110 
11111   const bool IsLiteral =
11112       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
11113 
11114   llvm::APFloat Value(0.0);
11115   bool IsConstant =
11116     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
11117   if (!IsConstant) {
11118     if (isObjCSignedCharBool(S, T)) {
11119       return adornObjCBoolConversionDiagWithTernaryFixit(
11120           S, E,
11121           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
11122               << E->getType());
11123     }
11124 
11125     return DiagnoseImpCast(S, E, T, CContext,
11126                            diag::warn_impcast_float_integer, PruneWarnings);
11127   }
11128 
11129   bool isExact = false;
11130 
11131   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
11132                             T->hasUnsignedIntegerRepresentation());
11133   llvm::APFloat::opStatus Result = Value.convertToInteger(
11134       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
11135 
11136   // FIXME: Force the precision of the source value down so we don't print
11137   // digits which are usually useless (we don't really care here if we
11138   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
11139   // would automatically print the shortest representation, but it's a bit
11140   // tricky to implement.
11141   SmallString<16> PrettySourceValue;
11142   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
11143   precision = (precision * 59 + 195) / 196;
11144   Value.toString(PrettySourceValue, precision);
11145 
11146   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
11147     return adornObjCBoolConversionDiagWithTernaryFixit(
11148         S, E,
11149         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
11150             << PrettySourceValue);
11151   }
11152 
11153   if (Result == llvm::APFloat::opOK && isExact) {
11154     if (IsLiteral) return;
11155     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
11156                            PruneWarnings);
11157   }
11158 
11159   // Conversion of a floating-point value to a non-bool integer where the
11160   // integral part cannot be represented by the integer type is undefined.
11161   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
11162     return DiagnoseImpCast(
11163         S, E, T, CContext,
11164         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
11165                   : diag::warn_impcast_float_to_integer_out_of_range,
11166         PruneWarnings);
11167 
11168   unsigned DiagID = 0;
11169   if (IsLiteral) {
11170     // Warn on floating point literal to integer.
11171     DiagID = diag::warn_impcast_literal_float_to_integer;
11172   } else if (IntegerValue == 0) {
11173     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
11174       return DiagnoseImpCast(S, E, T, CContext,
11175                              diag::warn_impcast_float_integer, PruneWarnings);
11176     }
11177     // Warn on non-zero to zero conversion.
11178     DiagID = diag::warn_impcast_float_to_integer_zero;
11179   } else {
11180     if (IntegerValue.isUnsigned()) {
11181       if (!IntegerValue.isMaxValue()) {
11182         return DiagnoseImpCast(S, E, T, CContext,
11183                                diag::warn_impcast_float_integer, PruneWarnings);
11184       }
11185     } else {  // IntegerValue.isSigned()
11186       if (!IntegerValue.isMaxSignedValue() &&
11187           !IntegerValue.isMinSignedValue()) {
11188         return DiagnoseImpCast(S, E, T, CContext,
11189                                diag::warn_impcast_float_integer, PruneWarnings);
11190       }
11191     }
11192     // Warn on evaluatable floating point expression to integer conversion.
11193     DiagID = diag::warn_impcast_float_to_integer;
11194   }
11195 
11196   SmallString<16> PrettyTargetValue;
11197   if (IsBool)
11198     PrettyTargetValue = Value.isZero() ? "false" : "true";
11199   else
11200     IntegerValue.toString(PrettyTargetValue);
11201 
11202   if (PruneWarnings) {
11203     S.DiagRuntimeBehavior(E->getExprLoc(), E,
11204                           S.PDiag(DiagID)
11205                               << E->getType() << T.getUnqualifiedType()
11206                               << PrettySourceValue << PrettyTargetValue
11207                               << E->getSourceRange() << SourceRange(CContext));
11208   } else {
11209     S.Diag(E->getExprLoc(), DiagID)
11210         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
11211         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
11212   }
11213 }
11214 
11215 /// Analyze the given compound assignment for the possible losing of
11216 /// floating-point precision.
11217 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
11218   assert(isa<CompoundAssignOperator>(E) &&
11219          "Must be compound assignment operation");
11220   // Recurse on the LHS and RHS in here
11221   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11222   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11223 
11224   if (E->getLHS()->getType()->isAtomicType())
11225     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
11226 
11227   // Now check the outermost expression
11228   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
11229   const auto *RBT = cast<CompoundAssignOperator>(E)
11230                         ->getComputationResultType()
11231                         ->getAs<BuiltinType>();
11232 
11233   // The below checks assume source is floating point.
11234   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
11235 
11236   // If source is floating point but target is an integer.
11237   if (ResultBT->isInteger())
11238     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
11239                            E->getExprLoc(), diag::warn_impcast_float_integer);
11240 
11241   if (!ResultBT->isFloatingPoint())
11242     return;
11243 
11244   // If both source and target are floating points, warn about losing precision.
11245   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11246       QualType(ResultBT, 0), QualType(RBT, 0));
11247   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
11248     // warn about dropping FP rank.
11249     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
11250                     diag::warn_impcast_float_result_precision);
11251 }
11252 
11253 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
11254                                       IntRange Range) {
11255   if (!Range.Width) return "0";
11256 
11257   llvm::APSInt ValueInRange = Value;
11258   ValueInRange.setIsSigned(!Range.NonNegative);
11259   ValueInRange = ValueInRange.trunc(Range.Width);
11260   return ValueInRange.toString(10);
11261 }
11262 
11263 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
11264   if (!isa<ImplicitCastExpr>(Ex))
11265     return false;
11266 
11267   Expr *InnerE = Ex->IgnoreParenImpCasts();
11268   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
11269   const Type *Source =
11270     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
11271   if (Target->isDependentType())
11272     return false;
11273 
11274   const BuiltinType *FloatCandidateBT =
11275     dyn_cast<BuiltinType>(ToBool ? Source : Target);
11276   const Type *BoolCandidateType = ToBool ? Target : Source;
11277 
11278   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
11279           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
11280 }
11281 
11282 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
11283                                              SourceLocation CC) {
11284   unsigned NumArgs = TheCall->getNumArgs();
11285   for (unsigned i = 0; i < NumArgs; ++i) {
11286     Expr *CurrA = TheCall->getArg(i);
11287     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
11288       continue;
11289 
11290     bool IsSwapped = ((i > 0) &&
11291         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
11292     IsSwapped |= ((i < (NumArgs - 1)) &&
11293         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
11294     if (IsSwapped) {
11295       // Warn on this floating-point to bool conversion.
11296       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
11297                       CurrA->getType(), CC,
11298                       diag::warn_impcast_floating_point_to_bool);
11299     }
11300   }
11301 }
11302 
11303 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
11304                                    SourceLocation CC) {
11305   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
11306                         E->getExprLoc()))
11307     return;
11308 
11309   // Don't warn on functions which have return type nullptr_t.
11310   if (isa<CallExpr>(E))
11311     return;
11312 
11313   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
11314   const Expr::NullPointerConstantKind NullKind =
11315       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
11316   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
11317     return;
11318 
11319   // Return if target type is a safe conversion.
11320   if (T->isAnyPointerType() || T->isBlockPointerType() ||
11321       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
11322     return;
11323 
11324   SourceLocation Loc = E->getSourceRange().getBegin();
11325 
11326   // Venture through the macro stacks to get to the source of macro arguments.
11327   // The new location is a better location than the complete location that was
11328   // passed in.
11329   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
11330   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
11331 
11332   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
11333   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
11334     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
11335         Loc, S.SourceMgr, S.getLangOpts());
11336     if (MacroName == "NULL")
11337       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
11338   }
11339 
11340   // Only warn if the null and context location are in the same macro expansion.
11341   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
11342     return;
11343 
11344   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
11345       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
11346       << FixItHint::CreateReplacement(Loc,
11347                                       S.getFixItZeroLiteralForType(T, Loc));
11348 }
11349 
11350 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11351                                   ObjCArrayLiteral *ArrayLiteral);
11352 
11353 static void
11354 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11355                            ObjCDictionaryLiteral *DictionaryLiteral);
11356 
11357 /// Check a single element within a collection literal against the
11358 /// target element type.
11359 static void checkObjCCollectionLiteralElement(Sema &S,
11360                                               QualType TargetElementType,
11361                                               Expr *Element,
11362                                               unsigned ElementKind) {
11363   // Skip a bitcast to 'id' or qualified 'id'.
11364   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
11365     if (ICE->getCastKind() == CK_BitCast &&
11366         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
11367       Element = ICE->getSubExpr();
11368   }
11369 
11370   QualType ElementType = Element->getType();
11371   ExprResult ElementResult(Element);
11372   if (ElementType->getAs<ObjCObjectPointerType>() &&
11373       S.CheckSingleAssignmentConstraints(TargetElementType,
11374                                          ElementResult,
11375                                          false, false)
11376         != Sema::Compatible) {
11377     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
11378         << ElementType << ElementKind << TargetElementType
11379         << Element->getSourceRange();
11380   }
11381 
11382   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
11383     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
11384   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
11385     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
11386 }
11387 
11388 /// Check an Objective-C array literal being converted to the given
11389 /// target type.
11390 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11391                                   ObjCArrayLiteral *ArrayLiteral) {
11392   if (!S.NSArrayDecl)
11393     return;
11394 
11395   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11396   if (!TargetObjCPtr)
11397     return;
11398 
11399   if (TargetObjCPtr->isUnspecialized() ||
11400       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11401         != S.NSArrayDecl->getCanonicalDecl())
11402     return;
11403 
11404   auto TypeArgs = TargetObjCPtr->getTypeArgs();
11405   if (TypeArgs.size() != 1)
11406     return;
11407 
11408   QualType TargetElementType = TypeArgs[0];
11409   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
11410     checkObjCCollectionLiteralElement(S, TargetElementType,
11411                                       ArrayLiteral->getElement(I),
11412                                       0);
11413   }
11414 }
11415 
11416 /// Check an Objective-C dictionary literal being converted to the given
11417 /// target type.
11418 static void
11419 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11420                            ObjCDictionaryLiteral *DictionaryLiteral) {
11421   if (!S.NSDictionaryDecl)
11422     return;
11423 
11424   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11425   if (!TargetObjCPtr)
11426     return;
11427 
11428   if (TargetObjCPtr->isUnspecialized() ||
11429       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11430         != S.NSDictionaryDecl->getCanonicalDecl())
11431     return;
11432 
11433   auto TypeArgs = TargetObjCPtr->getTypeArgs();
11434   if (TypeArgs.size() != 2)
11435     return;
11436 
11437   QualType TargetKeyType = TypeArgs[0];
11438   QualType TargetObjectType = TypeArgs[1];
11439   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
11440     auto Element = DictionaryLiteral->getKeyValueElement(I);
11441     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
11442     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
11443   }
11444 }
11445 
11446 // Helper function to filter out cases for constant width constant conversion.
11447 // Don't warn on char array initialization or for non-decimal values.
11448 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
11449                                           SourceLocation CC) {
11450   // If initializing from a constant, and the constant starts with '0',
11451   // then it is a binary, octal, or hexadecimal.  Allow these constants
11452   // to fill all the bits, even if there is a sign change.
11453   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
11454     const char FirstLiteralCharacter =
11455         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
11456     if (FirstLiteralCharacter == '0')
11457       return false;
11458   }
11459 
11460   // If the CC location points to a '{', and the type is char, then assume
11461   // assume it is an array initialization.
11462   if (CC.isValid() && T->isCharType()) {
11463     const char FirstContextCharacter =
11464         S.getSourceManager().getCharacterData(CC)[0];
11465     if (FirstContextCharacter == '{')
11466       return false;
11467   }
11468 
11469   return true;
11470 }
11471 
11472 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
11473   const auto *IL = dyn_cast<IntegerLiteral>(E);
11474   if (!IL) {
11475     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
11476       if (UO->getOpcode() == UO_Minus)
11477         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
11478     }
11479   }
11480 
11481   return IL;
11482 }
11483 
11484 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
11485   E = E->IgnoreParenImpCasts();
11486   SourceLocation ExprLoc = E->getExprLoc();
11487 
11488   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11489     BinaryOperator::Opcode Opc = BO->getOpcode();
11490     Expr::EvalResult Result;
11491     // Do not diagnose unsigned shifts.
11492     if (Opc == BO_Shl) {
11493       const auto *LHS = getIntegerLiteral(BO->getLHS());
11494       const auto *RHS = getIntegerLiteral(BO->getRHS());
11495       if (LHS && LHS->getValue() == 0)
11496         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
11497       else if (!E->isValueDependent() && LHS && RHS &&
11498                RHS->getValue().isNonNegative() &&
11499                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
11500         S.Diag(ExprLoc, diag::warn_left_shift_always)
11501             << (Result.Val.getInt() != 0);
11502       else if (E->getType()->isSignedIntegerType())
11503         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
11504     }
11505   }
11506 
11507   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11508     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
11509     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
11510     if (!LHS || !RHS)
11511       return;
11512     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
11513         (RHS->getValue() == 0 || RHS->getValue() == 1))
11514       // Do not diagnose common idioms.
11515       return;
11516     if (LHS->getValue() != 0 && RHS->getValue() != 0)
11517       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
11518   }
11519 }
11520 
11521 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
11522                                     SourceLocation CC,
11523                                     bool *ICContext = nullptr,
11524                                     bool IsListInit = false) {
11525   if (E->isTypeDependent() || E->isValueDependent()) return;
11526 
11527   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
11528   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
11529   if (Source == Target) return;
11530   if (Target->isDependentType()) return;
11531 
11532   // If the conversion context location is invalid don't complain. We also
11533   // don't want to emit a warning if the issue occurs from the expansion of
11534   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
11535   // delay this check as long as possible. Once we detect we are in that
11536   // scenario, we just return.
11537   if (CC.isInvalid())
11538     return;
11539 
11540   if (Source->isAtomicType())
11541     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
11542 
11543   // Diagnose implicit casts to bool.
11544   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
11545     if (isa<StringLiteral>(E))
11546       // Warn on string literal to bool.  Checks for string literals in logical
11547       // and expressions, for instance, assert(0 && "error here"), are
11548       // prevented by a check in AnalyzeImplicitConversions().
11549       return DiagnoseImpCast(S, E, T, CC,
11550                              diag::warn_impcast_string_literal_to_bool);
11551     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
11552         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
11553       // This covers the literal expressions that evaluate to Objective-C
11554       // objects.
11555       return DiagnoseImpCast(S, E, T, CC,
11556                              diag::warn_impcast_objective_c_literal_to_bool);
11557     }
11558     if (Source->isPointerType() || Source->canDecayToPointerType()) {
11559       // Warn on pointer to bool conversion that is always true.
11560       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
11561                                      SourceRange(CC));
11562     }
11563   }
11564 
11565   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
11566   // is a typedef for signed char (macOS), then that constant value has to be 1
11567   // or 0.
11568   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
11569     Expr::EvalResult Result;
11570     if (E->EvaluateAsInt(Result, S.getASTContext(),
11571                          Expr::SE_AllowSideEffects)) {
11572       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
11573         adornObjCBoolConversionDiagWithTernaryFixit(
11574             S, E,
11575             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
11576                 << Result.Val.getInt().toString(10));
11577       }
11578       return;
11579     }
11580   }
11581 
11582   // Check implicit casts from Objective-C collection literals to specialized
11583   // collection types, e.g., NSArray<NSString *> *.
11584   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
11585     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
11586   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
11587     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
11588 
11589   // Strip vector types.
11590   if (isa<VectorType>(Source)) {
11591     if (!isa<VectorType>(Target)) {
11592       if (S.SourceMgr.isInSystemMacro(CC))
11593         return;
11594       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
11595     }
11596 
11597     // If the vector cast is cast between two vectors of the same size, it is
11598     // a bitcast, not a conversion.
11599     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
11600       return;
11601 
11602     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
11603     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
11604   }
11605   if (auto VecTy = dyn_cast<VectorType>(Target))
11606     Target = VecTy->getElementType().getTypePtr();
11607 
11608   // Strip complex types.
11609   if (isa<ComplexType>(Source)) {
11610     if (!isa<ComplexType>(Target)) {
11611       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
11612         return;
11613 
11614       return DiagnoseImpCast(S, E, T, CC,
11615                              S.getLangOpts().CPlusPlus
11616                                  ? diag::err_impcast_complex_scalar
11617                                  : diag::warn_impcast_complex_scalar);
11618     }
11619 
11620     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
11621     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
11622   }
11623 
11624   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
11625   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
11626 
11627   // If the source is floating point...
11628   if (SourceBT && SourceBT->isFloatingPoint()) {
11629     // ...and the target is floating point...
11630     if (TargetBT && TargetBT->isFloatingPoint()) {
11631       // ...then warn if we're dropping FP rank.
11632 
11633       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11634           QualType(SourceBT, 0), QualType(TargetBT, 0));
11635       if (Order > 0) {
11636         // Don't warn about float constants that are precisely
11637         // representable in the target type.
11638         Expr::EvalResult result;
11639         if (E->EvaluateAsRValue(result, S.Context)) {
11640           // Value might be a float, a float vector, or a float complex.
11641           if (IsSameFloatAfterCast(result.Val,
11642                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
11643                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
11644             return;
11645         }
11646 
11647         if (S.SourceMgr.isInSystemMacro(CC))
11648           return;
11649 
11650         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
11651       }
11652       // ... or possibly if we're increasing rank, too
11653       else if (Order < 0) {
11654         if (S.SourceMgr.isInSystemMacro(CC))
11655           return;
11656 
11657         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
11658       }
11659       return;
11660     }
11661 
11662     // If the target is integral, always warn.
11663     if (TargetBT && TargetBT->isInteger()) {
11664       if (S.SourceMgr.isInSystemMacro(CC))
11665         return;
11666 
11667       DiagnoseFloatingImpCast(S, E, T, CC);
11668     }
11669 
11670     // Detect the case where a call result is converted from floating-point to
11671     // to bool, and the final argument to the call is converted from bool, to
11672     // discover this typo:
11673     //
11674     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
11675     //
11676     // FIXME: This is an incredibly special case; is there some more general
11677     // way to detect this class of misplaced-parentheses bug?
11678     if (Target->isBooleanType() && isa<CallExpr>(E)) {
11679       // Check last argument of function call to see if it is an
11680       // implicit cast from a type matching the type the result
11681       // is being cast to.
11682       CallExpr *CEx = cast<CallExpr>(E);
11683       if (unsigned NumArgs = CEx->getNumArgs()) {
11684         Expr *LastA = CEx->getArg(NumArgs - 1);
11685         Expr *InnerE = LastA->IgnoreParenImpCasts();
11686         if (isa<ImplicitCastExpr>(LastA) &&
11687             InnerE->getType()->isBooleanType()) {
11688           // Warn on this floating-point to bool conversion
11689           DiagnoseImpCast(S, E, T, CC,
11690                           diag::warn_impcast_floating_point_to_bool);
11691         }
11692       }
11693     }
11694     return;
11695   }
11696 
11697   // Valid casts involving fixed point types should be accounted for here.
11698   if (Source->isFixedPointType()) {
11699     if (Target->isUnsaturatedFixedPointType()) {
11700       Expr::EvalResult Result;
11701       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
11702                                   S.isConstantEvaluated())) {
11703         APFixedPoint Value = Result.Val.getFixedPoint();
11704         APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
11705         APFixedPoint MinVal = S.Context.getFixedPointMin(T);
11706         if (Value > MaxVal || Value < MinVal) {
11707           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11708                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11709                                     << Value.toString() << T
11710                                     << E->getSourceRange()
11711                                     << clang::SourceRange(CC));
11712           return;
11713         }
11714       }
11715     } else if (Target->isIntegerType()) {
11716       Expr::EvalResult Result;
11717       if (!S.isConstantEvaluated() &&
11718           E->EvaluateAsFixedPoint(Result, S.Context,
11719                                   Expr::SE_AllowSideEffects)) {
11720         APFixedPoint FXResult = Result.Val.getFixedPoint();
11721 
11722         bool Overflowed;
11723         llvm::APSInt IntResult = FXResult.convertToInt(
11724             S.Context.getIntWidth(T),
11725             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
11726 
11727         if (Overflowed) {
11728           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11729                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11730                                     << FXResult.toString() << T
11731                                     << E->getSourceRange()
11732                                     << clang::SourceRange(CC));
11733           return;
11734         }
11735       }
11736     }
11737   } else if (Target->isUnsaturatedFixedPointType()) {
11738     if (Source->isIntegerType()) {
11739       Expr::EvalResult Result;
11740       if (!S.isConstantEvaluated() &&
11741           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
11742         llvm::APSInt Value = Result.Val.getInt();
11743 
11744         bool Overflowed;
11745         APFixedPoint IntResult = APFixedPoint::getFromIntValue(
11746             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
11747 
11748         if (Overflowed) {
11749           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11750                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11751                                     << Value.toString(/*Radix=*/10) << T
11752                                     << E->getSourceRange()
11753                                     << clang::SourceRange(CC));
11754           return;
11755         }
11756       }
11757     }
11758   }
11759 
11760   // If we are casting an integer type to a floating point type without
11761   // initialization-list syntax, we might lose accuracy if the floating
11762   // point type has a narrower significand than the integer type.
11763   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
11764       TargetBT->isFloatingType() && !IsListInit) {
11765     // Determine the number of precision bits in the source integer type.
11766     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated());
11767     unsigned int SourcePrecision = SourceRange.Width;
11768 
11769     // Determine the number of precision bits in the
11770     // target floating point type.
11771     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
11772         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
11773 
11774     if (SourcePrecision > 0 && TargetPrecision > 0 &&
11775         SourcePrecision > TargetPrecision) {
11776 
11777       llvm::APSInt SourceInt;
11778       if (E->isIntegerConstantExpr(SourceInt, S.Context)) {
11779         // If the source integer is a constant, convert it to the target
11780         // floating point type. Issue a warning if the value changes
11781         // during the whole conversion.
11782         llvm::APFloat TargetFloatValue(
11783             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
11784         llvm::APFloat::opStatus ConversionStatus =
11785             TargetFloatValue.convertFromAPInt(
11786                 SourceInt, SourceBT->isSignedInteger(),
11787                 llvm::APFloat::rmNearestTiesToEven);
11788 
11789         if (ConversionStatus != llvm::APFloat::opOK) {
11790           std::string PrettySourceValue = SourceInt.toString(10);
11791           SmallString<32> PrettyTargetValue;
11792           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
11793 
11794           S.DiagRuntimeBehavior(
11795               E->getExprLoc(), E,
11796               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
11797                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
11798                   << E->getSourceRange() << clang::SourceRange(CC));
11799         }
11800       } else {
11801         // Otherwise, the implicit conversion may lose precision.
11802         DiagnoseImpCast(S, E, T, CC,
11803                         diag::warn_impcast_integer_float_precision);
11804       }
11805     }
11806   }
11807 
11808   DiagnoseNullConversion(S, E, T, CC);
11809 
11810   S.DiscardMisalignedMemberAddress(Target, E);
11811 
11812   if (Target->isBooleanType())
11813     DiagnoseIntInBoolContext(S, E);
11814 
11815   if (!Source->isIntegerType() || !Target->isIntegerType())
11816     return;
11817 
11818   // TODO: remove this early return once the false positives for constant->bool
11819   // in templates, macros, etc, are reduced or removed.
11820   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
11821     return;
11822 
11823   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
11824       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
11825     return adornObjCBoolConversionDiagWithTernaryFixit(
11826         S, E,
11827         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
11828             << E->getType());
11829   }
11830 
11831   IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated());
11832   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
11833 
11834   if (SourceRange.Width > TargetRange.Width) {
11835     // If the source is a constant, use a default-on diagnostic.
11836     // TODO: this should happen for bitfield stores, too.
11837     Expr::EvalResult Result;
11838     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
11839                          S.isConstantEvaluated())) {
11840       llvm::APSInt Value(32);
11841       Value = Result.Val.getInt();
11842 
11843       if (S.SourceMgr.isInSystemMacro(CC))
11844         return;
11845 
11846       std::string PrettySourceValue = Value.toString(10);
11847       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11848 
11849       S.DiagRuntimeBehavior(
11850           E->getExprLoc(), E,
11851           S.PDiag(diag::warn_impcast_integer_precision_constant)
11852               << PrettySourceValue << PrettyTargetValue << E->getType() << T
11853               << E->getSourceRange() << clang::SourceRange(CC));
11854       return;
11855     }
11856 
11857     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
11858     if (S.SourceMgr.isInSystemMacro(CC))
11859       return;
11860 
11861     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
11862       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
11863                              /* pruneControlFlow */ true);
11864     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
11865   }
11866 
11867   if (TargetRange.Width > SourceRange.Width) {
11868     if (auto *UO = dyn_cast<UnaryOperator>(E))
11869       if (UO->getOpcode() == UO_Minus)
11870         if (Source->isUnsignedIntegerType()) {
11871           if (Target->isUnsignedIntegerType())
11872             return DiagnoseImpCast(S, E, T, CC,
11873                                    diag::warn_impcast_high_order_zero_bits);
11874           if (Target->isSignedIntegerType())
11875             return DiagnoseImpCast(S, E, T, CC,
11876                                    diag::warn_impcast_nonnegative_result);
11877         }
11878   }
11879 
11880   if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
11881       SourceRange.NonNegative && Source->isSignedIntegerType()) {
11882     // Warn when doing a signed to signed conversion, warn if the positive
11883     // source value is exactly the width of the target type, which will
11884     // cause a negative value to be stored.
11885 
11886     Expr::EvalResult Result;
11887     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
11888         !S.SourceMgr.isInSystemMacro(CC)) {
11889       llvm::APSInt Value = Result.Val.getInt();
11890       if (isSameWidthConstantConversion(S, E, T, CC)) {
11891         std::string PrettySourceValue = Value.toString(10);
11892         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11893 
11894         S.DiagRuntimeBehavior(
11895             E->getExprLoc(), E,
11896             S.PDiag(diag::warn_impcast_integer_precision_constant)
11897                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
11898                 << E->getSourceRange() << clang::SourceRange(CC));
11899         return;
11900       }
11901     }
11902 
11903     // Fall through for non-constants to give a sign conversion warning.
11904   }
11905 
11906   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
11907       (!TargetRange.NonNegative && SourceRange.NonNegative &&
11908        SourceRange.Width == TargetRange.Width)) {
11909     if (S.SourceMgr.isInSystemMacro(CC))
11910       return;
11911 
11912     unsigned DiagID = diag::warn_impcast_integer_sign;
11913 
11914     // Traditionally, gcc has warned about this under -Wsign-compare.
11915     // We also want to warn about it in -Wconversion.
11916     // So if -Wconversion is off, use a completely identical diagnostic
11917     // in the sign-compare group.
11918     // The conditional-checking code will
11919     if (ICContext) {
11920       DiagID = diag::warn_impcast_integer_sign_conditional;
11921       *ICContext = true;
11922     }
11923 
11924     return DiagnoseImpCast(S, E, T, CC, DiagID);
11925   }
11926 
11927   // Diagnose conversions between different enumeration types.
11928   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
11929   // type, to give us better diagnostics.
11930   QualType SourceType = E->getType();
11931   if (!S.getLangOpts().CPlusPlus) {
11932     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11933       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
11934         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
11935         SourceType = S.Context.getTypeDeclType(Enum);
11936         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
11937       }
11938   }
11939 
11940   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
11941     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
11942       if (SourceEnum->getDecl()->hasNameForLinkage() &&
11943           TargetEnum->getDecl()->hasNameForLinkage() &&
11944           SourceEnum != TargetEnum) {
11945         if (S.SourceMgr.isInSystemMacro(CC))
11946           return;
11947 
11948         return DiagnoseImpCast(S, E, SourceType, T, CC,
11949                                diag::warn_impcast_different_enum_types);
11950       }
11951 }
11952 
11953 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
11954                                      SourceLocation CC, QualType T);
11955 
11956 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
11957                                     SourceLocation CC, bool &ICContext) {
11958   E = E->IgnoreParenImpCasts();
11959 
11960   if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
11961     return CheckConditionalOperator(S, CO, CC, T);
11962 
11963   AnalyzeImplicitConversions(S, E, CC);
11964   if (E->getType() != T)
11965     return CheckImplicitConversion(S, E, T, CC, &ICContext);
11966 }
11967 
11968 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
11969                                      SourceLocation CC, QualType T) {
11970   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
11971 
11972   Expr *TrueExpr = E->getTrueExpr();
11973   if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
11974     TrueExpr = BCO->getCommon();
11975 
11976   bool Suspicious = false;
11977   CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
11978   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
11979 
11980   if (T->isBooleanType())
11981     DiagnoseIntInBoolContext(S, E);
11982 
11983   // If -Wconversion would have warned about either of the candidates
11984   // for a signedness conversion to the context type...
11985   if (!Suspicious) return;
11986 
11987   // ...but it's currently ignored...
11988   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
11989     return;
11990 
11991   // ...then check whether it would have warned about either of the
11992   // candidates for a signedness conversion to the condition type.
11993   if (E->getType() == T) return;
11994 
11995   Suspicious = false;
11996   CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(),
11997                           E->getType(), CC, &Suspicious);
11998   if (!Suspicious)
11999     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
12000                             E->getType(), CC, &Suspicious);
12001 }
12002 
12003 /// Check conversion of given expression to boolean.
12004 /// Input argument E is a logical expression.
12005 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
12006   if (S.getLangOpts().Bool)
12007     return;
12008   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
12009     return;
12010   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
12011 }
12012 
12013 namespace {
12014 struct AnalyzeImplicitConversionsWorkItem {
12015   Expr *E;
12016   SourceLocation CC;
12017   bool IsListInit;
12018 };
12019 }
12020 
12021 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
12022 /// that should be visited are added to WorkList.
12023 static void AnalyzeImplicitConversions(
12024     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
12025     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
12026   Expr *OrigE = Item.E;
12027   SourceLocation CC = Item.CC;
12028 
12029   QualType T = OrigE->getType();
12030   Expr *E = OrigE->IgnoreParenImpCasts();
12031 
12032   // Propagate whether we are in a C++ list initialization expression.
12033   // If so, we do not issue warnings for implicit int-float conversion
12034   // precision loss, because C++11 narrowing already handles it.
12035   bool IsListInit = Item.IsListInit ||
12036                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
12037 
12038   if (E->isTypeDependent() || E->isValueDependent())
12039     return;
12040 
12041   Expr *SourceExpr = E;
12042   // Examine, but don't traverse into the source expression of an
12043   // OpaqueValueExpr, since it may have multiple parents and we don't want to
12044   // emit duplicate diagnostics. Its fine to examine the form or attempt to
12045   // evaluate it in the context of checking the specific conversion to T though.
12046   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
12047     if (auto *Src = OVE->getSourceExpr())
12048       SourceExpr = Src;
12049 
12050   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
12051     if (UO->getOpcode() == UO_Not &&
12052         UO->getSubExpr()->isKnownToHaveBooleanValue())
12053       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
12054           << OrigE->getSourceRange() << T->isBooleanType()
12055           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
12056 
12057   // For conditional operators, we analyze the arguments as if they
12058   // were being fed directly into the output.
12059   if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
12060     CheckConditionalOperator(S, CO, CC, T);
12061     return;
12062   }
12063 
12064   // Check implicit argument conversions for function calls.
12065   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
12066     CheckImplicitArgumentConversions(S, Call, CC);
12067 
12068   // Go ahead and check any implicit conversions we might have skipped.
12069   // The non-canonical typecheck is just an optimization;
12070   // CheckImplicitConversion will filter out dead implicit conversions.
12071   if (SourceExpr->getType() != T)
12072     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
12073 
12074   // Now continue drilling into this expression.
12075 
12076   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
12077     // The bound subexpressions in a PseudoObjectExpr are not reachable
12078     // as transitive children.
12079     // FIXME: Use a more uniform representation for this.
12080     for (auto *SE : POE->semantics())
12081       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
12082         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
12083   }
12084 
12085   // Skip past explicit casts.
12086   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
12087     E = CE->getSubExpr()->IgnoreParenImpCasts();
12088     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
12089       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12090     WorkList.push_back({E, CC, IsListInit});
12091     return;
12092   }
12093 
12094   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12095     // Do a somewhat different check with comparison operators.
12096     if (BO->isComparisonOp())
12097       return AnalyzeComparison(S, BO);
12098 
12099     // And with simple assignments.
12100     if (BO->getOpcode() == BO_Assign)
12101       return AnalyzeAssignment(S, BO);
12102     // And with compound assignments.
12103     if (BO->isAssignmentOp())
12104       return AnalyzeCompoundAssignment(S, BO);
12105   }
12106 
12107   // These break the otherwise-useful invariant below.  Fortunately,
12108   // we don't really need to recurse into them, because any internal
12109   // expressions should have been analyzed already when they were
12110   // built into statements.
12111   if (isa<StmtExpr>(E)) return;
12112 
12113   // Don't descend into unevaluated contexts.
12114   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
12115 
12116   // Now just recurse over the expression's children.
12117   CC = E->getExprLoc();
12118   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
12119   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
12120   for (Stmt *SubStmt : E->children()) {
12121     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
12122     if (!ChildExpr)
12123       continue;
12124 
12125     if (IsLogicalAndOperator &&
12126         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
12127       // Ignore checking string literals that are in logical and operators.
12128       // This is a common pattern for asserts.
12129       continue;
12130     WorkList.push_back({ChildExpr, CC, IsListInit});
12131   }
12132 
12133   if (BO && BO->isLogicalOp()) {
12134     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
12135     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
12136       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
12137 
12138     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
12139     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
12140       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
12141   }
12142 
12143   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
12144     if (U->getOpcode() == UO_LNot) {
12145       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
12146     } else if (U->getOpcode() != UO_AddrOf) {
12147       if (U->getSubExpr()->getType()->isAtomicType())
12148         S.Diag(U->getSubExpr()->getBeginLoc(),
12149                diag::warn_atomic_implicit_seq_cst);
12150     }
12151   }
12152 }
12153 
12154 /// AnalyzeImplicitConversions - Find and report any interesting
12155 /// implicit conversions in the given expression.  There are a couple
12156 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
12157 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
12158                                        bool IsListInit/*= false*/) {
12159   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
12160   WorkList.push_back({OrigE, CC, IsListInit});
12161   while (!WorkList.empty())
12162     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
12163 }
12164 
12165 /// Diagnose integer type and any valid implicit conversion to it.
12166 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
12167   // Taking into account implicit conversions,
12168   // allow any integer.
12169   if (!E->getType()->isIntegerType()) {
12170     S.Diag(E->getBeginLoc(),
12171            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
12172     return true;
12173   }
12174   // Potentially emit standard warnings for implicit conversions if enabled
12175   // using -Wconversion.
12176   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
12177   return false;
12178 }
12179 
12180 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
12181 // Returns true when emitting a warning about taking the address of a reference.
12182 static bool CheckForReference(Sema &SemaRef, const Expr *E,
12183                               const PartialDiagnostic &PD) {
12184   E = E->IgnoreParenImpCasts();
12185 
12186   const FunctionDecl *FD = nullptr;
12187 
12188   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12189     if (!DRE->getDecl()->getType()->isReferenceType())
12190       return false;
12191   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12192     if (!M->getMemberDecl()->getType()->isReferenceType())
12193       return false;
12194   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
12195     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
12196       return false;
12197     FD = Call->getDirectCallee();
12198   } else {
12199     return false;
12200   }
12201 
12202   SemaRef.Diag(E->getExprLoc(), PD);
12203 
12204   // If possible, point to location of function.
12205   if (FD) {
12206     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
12207   }
12208 
12209   return true;
12210 }
12211 
12212 // Returns true if the SourceLocation is expanded from any macro body.
12213 // Returns false if the SourceLocation is invalid, is from not in a macro
12214 // expansion, or is from expanded from a top-level macro argument.
12215 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
12216   if (Loc.isInvalid())
12217     return false;
12218 
12219   while (Loc.isMacroID()) {
12220     if (SM.isMacroBodyExpansion(Loc))
12221       return true;
12222     Loc = SM.getImmediateMacroCallerLoc(Loc);
12223   }
12224 
12225   return false;
12226 }
12227 
12228 /// Diagnose pointers that are always non-null.
12229 /// \param E the expression containing the pointer
12230 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
12231 /// compared to a null pointer
12232 /// \param IsEqual True when the comparison is equal to a null pointer
12233 /// \param Range Extra SourceRange to highlight in the diagnostic
12234 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
12235                                         Expr::NullPointerConstantKind NullKind,
12236                                         bool IsEqual, SourceRange Range) {
12237   if (!E)
12238     return;
12239 
12240   // Don't warn inside macros.
12241   if (E->getExprLoc().isMacroID()) {
12242     const SourceManager &SM = getSourceManager();
12243     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
12244         IsInAnyMacroBody(SM, Range.getBegin()))
12245       return;
12246   }
12247   E = E->IgnoreImpCasts();
12248 
12249   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
12250 
12251   if (isa<CXXThisExpr>(E)) {
12252     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
12253                                 : diag::warn_this_bool_conversion;
12254     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
12255     return;
12256   }
12257 
12258   bool IsAddressOf = false;
12259 
12260   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12261     if (UO->getOpcode() != UO_AddrOf)
12262       return;
12263     IsAddressOf = true;
12264     E = UO->getSubExpr();
12265   }
12266 
12267   if (IsAddressOf) {
12268     unsigned DiagID = IsCompare
12269                           ? diag::warn_address_of_reference_null_compare
12270                           : diag::warn_address_of_reference_bool_conversion;
12271     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
12272                                          << IsEqual;
12273     if (CheckForReference(*this, E, PD)) {
12274       return;
12275     }
12276   }
12277 
12278   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
12279     bool IsParam = isa<NonNullAttr>(NonnullAttr);
12280     std::string Str;
12281     llvm::raw_string_ostream S(Str);
12282     E->printPretty(S, nullptr, getPrintingPolicy());
12283     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
12284                                 : diag::warn_cast_nonnull_to_bool;
12285     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
12286       << E->getSourceRange() << Range << IsEqual;
12287     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
12288   };
12289 
12290   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
12291   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
12292     if (auto *Callee = Call->getDirectCallee()) {
12293       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
12294         ComplainAboutNonnullParamOrCall(A);
12295         return;
12296       }
12297     }
12298   }
12299 
12300   // Expect to find a single Decl.  Skip anything more complicated.
12301   ValueDecl *D = nullptr;
12302   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
12303     D = R->getDecl();
12304   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12305     D = M->getMemberDecl();
12306   }
12307 
12308   // Weak Decls can be null.
12309   if (!D || D->isWeak())
12310     return;
12311 
12312   // Check for parameter decl with nonnull attribute
12313   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
12314     if (getCurFunction() &&
12315         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
12316       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
12317         ComplainAboutNonnullParamOrCall(A);
12318         return;
12319       }
12320 
12321       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
12322         // Skip function template not specialized yet.
12323         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
12324           return;
12325         auto ParamIter = llvm::find(FD->parameters(), PV);
12326         assert(ParamIter != FD->param_end());
12327         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
12328 
12329         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
12330           if (!NonNull->args_size()) {
12331               ComplainAboutNonnullParamOrCall(NonNull);
12332               return;
12333           }
12334 
12335           for (const ParamIdx &ArgNo : NonNull->args()) {
12336             if (ArgNo.getASTIndex() == ParamNo) {
12337               ComplainAboutNonnullParamOrCall(NonNull);
12338               return;
12339             }
12340           }
12341         }
12342       }
12343     }
12344   }
12345 
12346   QualType T = D->getType();
12347   const bool IsArray = T->isArrayType();
12348   const bool IsFunction = T->isFunctionType();
12349 
12350   // Address of function is used to silence the function warning.
12351   if (IsAddressOf && IsFunction) {
12352     return;
12353   }
12354 
12355   // Found nothing.
12356   if (!IsAddressOf && !IsFunction && !IsArray)
12357     return;
12358 
12359   // Pretty print the expression for the diagnostic.
12360   std::string Str;
12361   llvm::raw_string_ostream S(Str);
12362   E->printPretty(S, nullptr, getPrintingPolicy());
12363 
12364   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
12365                               : diag::warn_impcast_pointer_to_bool;
12366   enum {
12367     AddressOf,
12368     FunctionPointer,
12369     ArrayPointer
12370   } DiagType;
12371   if (IsAddressOf)
12372     DiagType = AddressOf;
12373   else if (IsFunction)
12374     DiagType = FunctionPointer;
12375   else if (IsArray)
12376     DiagType = ArrayPointer;
12377   else
12378     llvm_unreachable("Could not determine diagnostic.");
12379   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
12380                                 << Range << IsEqual;
12381 
12382   if (!IsFunction)
12383     return;
12384 
12385   // Suggest '&' to silence the function warning.
12386   Diag(E->getExprLoc(), diag::note_function_warning_silence)
12387       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
12388 
12389   // Check to see if '()' fixit should be emitted.
12390   QualType ReturnType;
12391   UnresolvedSet<4> NonTemplateOverloads;
12392   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
12393   if (ReturnType.isNull())
12394     return;
12395 
12396   if (IsCompare) {
12397     // There are two cases here.  If there is null constant, the only suggest
12398     // for a pointer return type.  If the null is 0, then suggest if the return
12399     // type is a pointer or an integer type.
12400     if (!ReturnType->isPointerType()) {
12401       if (NullKind == Expr::NPCK_ZeroExpression ||
12402           NullKind == Expr::NPCK_ZeroLiteral) {
12403         if (!ReturnType->isIntegerType())
12404           return;
12405       } else {
12406         return;
12407       }
12408     }
12409   } else { // !IsCompare
12410     // For function to bool, only suggest if the function pointer has bool
12411     // return type.
12412     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
12413       return;
12414   }
12415   Diag(E->getExprLoc(), diag::note_function_to_function_call)
12416       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
12417 }
12418 
12419 /// Diagnoses "dangerous" implicit conversions within the given
12420 /// expression (which is a full expression).  Implements -Wconversion
12421 /// and -Wsign-compare.
12422 ///
12423 /// \param CC the "context" location of the implicit conversion, i.e.
12424 ///   the most location of the syntactic entity requiring the implicit
12425 ///   conversion
12426 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
12427   // Don't diagnose in unevaluated contexts.
12428   if (isUnevaluatedContext())
12429     return;
12430 
12431   // Don't diagnose for value- or type-dependent expressions.
12432   if (E->isTypeDependent() || E->isValueDependent())
12433     return;
12434 
12435   // Check for array bounds violations in cases where the check isn't triggered
12436   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
12437   // ArraySubscriptExpr is on the RHS of a variable initialization.
12438   CheckArrayAccess(E);
12439 
12440   // This is not the right CC for (e.g.) a variable initialization.
12441   AnalyzeImplicitConversions(*this, E, CC);
12442 }
12443 
12444 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
12445 /// Input argument E is a logical expression.
12446 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
12447   ::CheckBoolLikeConversion(*this, E, CC);
12448 }
12449 
12450 /// Diagnose when expression is an integer constant expression and its evaluation
12451 /// results in integer overflow
12452 void Sema::CheckForIntOverflow (Expr *E) {
12453   // Use a work list to deal with nested struct initializers.
12454   SmallVector<Expr *, 2> Exprs(1, E);
12455 
12456   do {
12457     Expr *OriginalE = Exprs.pop_back_val();
12458     Expr *E = OriginalE->IgnoreParenCasts();
12459 
12460     if (isa<BinaryOperator>(E)) {
12461       E->EvaluateForOverflow(Context);
12462       continue;
12463     }
12464 
12465     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
12466       Exprs.append(InitList->inits().begin(), InitList->inits().end());
12467     else if (isa<ObjCBoxedExpr>(OriginalE))
12468       E->EvaluateForOverflow(Context);
12469     else if (auto Call = dyn_cast<CallExpr>(E))
12470       Exprs.append(Call->arg_begin(), Call->arg_end());
12471     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
12472       Exprs.append(Message->arg_begin(), Message->arg_end());
12473   } while (!Exprs.empty());
12474 }
12475 
12476 namespace {
12477 
12478 /// Visitor for expressions which looks for unsequenced operations on the
12479 /// same object.
12480 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
12481   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
12482 
12483   /// A tree of sequenced regions within an expression. Two regions are
12484   /// unsequenced if one is an ancestor or a descendent of the other. When we
12485   /// finish processing an expression with sequencing, such as a comma
12486   /// expression, we fold its tree nodes into its parent, since they are
12487   /// unsequenced with respect to nodes we will visit later.
12488   class SequenceTree {
12489     struct Value {
12490       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
12491       unsigned Parent : 31;
12492       unsigned Merged : 1;
12493     };
12494     SmallVector<Value, 8> Values;
12495 
12496   public:
12497     /// A region within an expression which may be sequenced with respect
12498     /// to some other region.
12499     class Seq {
12500       friend class SequenceTree;
12501 
12502       unsigned Index;
12503 
12504       explicit Seq(unsigned N) : Index(N) {}
12505 
12506     public:
12507       Seq() : Index(0) {}
12508     };
12509 
12510     SequenceTree() { Values.push_back(Value(0)); }
12511     Seq root() const { return Seq(0); }
12512 
12513     /// Create a new sequence of operations, which is an unsequenced
12514     /// subset of \p Parent. This sequence of operations is sequenced with
12515     /// respect to other children of \p Parent.
12516     Seq allocate(Seq Parent) {
12517       Values.push_back(Value(Parent.Index));
12518       return Seq(Values.size() - 1);
12519     }
12520 
12521     /// Merge a sequence of operations into its parent.
12522     void merge(Seq S) {
12523       Values[S.Index].Merged = true;
12524     }
12525 
12526     /// Determine whether two operations are unsequenced. This operation
12527     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
12528     /// should have been merged into its parent as appropriate.
12529     bool isUnsequenced(Seq Cur, Seq Old) {
12530       unsigned C = representative(Cur.Index);
12531       unsigned Target = representative(Old.Index);
12532       while (C >= Target) {
12533         if (C == Target)
12534           return true;
12535         C = Values[C].Parent;
12536       }
12537       return false;
12538     }
12539 
12540   private:
12541     /// Pick a representative for a sequence.
12542     unsigned representative(unsigned K) {
12543       if (Values[K].Merged)
12544         // Perform path compression as we go.
12545         return Values[K].Parent = representative(Values[K].Parent);
12546       return K;
12547     }
12548   };
12549 
12550   /// An object for which we can track unsequenced uses.
12551   using Object = const NamedDecl *;
12552 
12553   /// Different flavors of object usage which we track. We only track the
12554   /// least-sequenced usage of each kind.
12555   enum UsageKind {
12556     /// A read of an object. Multiple unsequenced reads are OK.
12557     UK_Use,
12558 
12559     /// A modification of an object which is sequenced before the value
12560     /// computation of the expression, such as ++n in C++.
12561     UK_ModAsValue,
12562 
12563     /// A modification of an object which is not sequenced before the value
12564     /// computation of the expression, such as n++.
12565     UK_ModAsSideEffect,
12566 
12567     UK_Count = UK_ModAsSideEffect + 1
12568   };
12569 
12570   /// Bundle together a sequencing region and the expression corresponding
12571   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
12572   struct Usage {
12573     const Expr *UsageExpr;
12574     SequenceTree::Seq Seq;
12575 
12576     Usage() : UsageExpr(nullptr), Seq() {}
12577   };
12578 
12579   struct UsageInfo {
12580     Usage Uses[UK_Count];
12581 
12582     /// Have we issued a diagnostic for this object already?
12583     bool Diagnosed;
12584 
12585     UsageInfo() : Uses(), Diagnosed(false) {}
12586   };
12587   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
12588 
12589   Sema &SemaRef;
12590 
12591   /// Sequenced regions within the expression.
12592   SequenceTree Tree;
12593 
12594   /// Declaration modifications and references which we have seen.
12595   UsageInfoMap UsageMap;
12596 
12597   /// The region we are currently within.
12598   SequenceTree::Seq Region;
12599 
12600   /// Filled in with declarations which were modified as a side-effect
12601   /// (that is, post-increment operations).
12602   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
12603 
12604   /// Expressions to check later. We defer checking these to reduce
12605   /// stack usage.
12606   SmallVectorImpl<const Expr *> &WorkList;
12607 
12608   /// RAII object wrapping the visitation of a sequenced subexpression of an
12609   /// expression. At the end of this process, the side-effects of the evaluation
12610   /// become sequenced with respect to the value computation of the result, so
12611   /// we downgrade any UK_ModAsSideEffect within the evaluation to
12612   /// UK_ModAsValue.
12613   struct SequencedSubexpression {
12614     SequencedSubexpression(SequenceChecker &Self)
12615       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
12616       Self.ModAsSideEffect = &ModAsSideEffect;
12617     }
12618 
12619     ~SequencedSubexpression() {
12620       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
12621         // Add a new usage with usage kind UK_ModAsValue, and then restore
12622         // the previous usage with UK_ModAsSideEffect (thus clearing it if
12623         // the previous one was empty).
12624         UsageInfo &UI = Self.UsageMap[M.first];
12625         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
12626         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
12627         SideEffectUsage = M.second;
12628       }
12629       Self.ModAsSideEffect = OldModAsSideEffect;
12630     }
12631 
12632     SequenceChecker &Self;
12633     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
12634     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
12635   };
12636 
12637   /// RAII object wrapping the visitation of a subexpression which we might
12638   /// choose to evaluate as a constant. If any subexpression is evaluated and
12639   /// found to be non-constant, this allows us to suppress the evaluation of
12640   /// the outer expression.
12641   class EvaluationTracker {
12642   public:
12643     EvaluationTracker(SequenceChecker &Self)
12644         : Self(Self), Prev(Self.EvalTracker) {
12645       Self.EvalTracker = this;
12646     }
12647 
12648     ~EvaluationTracker() {
12649       Self.EvalTracker = Prev;
12650       if (Prev)
12651         Prev->EvalOK &= EvalOK;
12652     }
12653 
12654     bool evaluate(const Expr *E, bool &Result) {
12655       if (!EvalOK || E->isValueDependent())
12656         return false;
12657       EvalOK = E->EvaluateAsBooleanCondition(
12658           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
12659       return EvalOK;
12660     }
12661 
12662   private:
12663     SequenceChecker &Self;
12664     EvaluationTracker *Prev;
12665     bool EvalOK = true;
12666   } *EvalTracker = nullptr;
12667 
12668   /// Find the object which is produced by the specified expression,
12669   /// if any.
12670   Object getObject(const Expr *E, bool Mod) const {
12671     E = E->IgnoreParenCasts();
12672     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12673       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
12674         return getObject(UO->getSubExpr(), Mod);
12675     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12676       if (BO->getOpcode() == BO_Comma)
12677         return getObject(BO->getRHS(), Mod);
12678       if (Mod && BO->isAssignmentOp())
12679         return getObject(BO->getLHS(), Mod);
12680     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12681       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
12682       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
12683         return ME->getMemberDecl();
12684     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12685       // FIXME: If this is a reference, map through to its value.
12686       return DRE->getDecl();
12687     return nullptr;
12688   }
12689 
12690   /// Note that an object \p O was modified or used by an expression
12691   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
12692   /// the object \p O as obtained via the \p UsageMap.
12693   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
12694     // Get the old usage for the given object and usage kind.
12695     Usage &U = UI.Uses[UK];
12696     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
12697       // If we have a modification as side effect and are in a sequenced
12698       // subexpression, save the old Usage so that we can restore it later
12699       // in SequencedSubexpression::~SequencedSubexpression.
12700       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
12701         ModAsSideEffect->push_back(std::make_pair(O, U));
12702       // Then record the new usage with the current sequencing region.
12703       U.UsageExpr = UsageExpr;
12704       U.Seq = Region;
12705     }
12706   }
12707 
12708   /// Check whether a modification or use of an object \p O in an expression
12709   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
12710   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
12711   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
12712   /// usage and false we are checking for a mod-use unsequenced usage.
12713   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
12714                   UsageKind OtherKind, bool IsModMod) {
12715     if (UI.Diagnosed)
12716       return;
12717 
12718     const Usage &U = UI.Uses[OtherKind];
12719     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
12720       return;
12721 
12722     const Expr *Mod = U.UsageExpr;
12723     const Expr *ModOrUse = UsageExpr;
12724     if (OtherKind == UK_Use)
12725       std::swap(Mod, ModOrUse);
12726 
12727     SemaRef.DiagRuntimeBehavior(
12728         Mod->getExprLoc(), {Mod, ModOrUse},
12729         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
12730                                : diag::warn_unsequenced_mod_use)
12731             << O << SourceRange(ModOrUse->getExprLoc()));
12732     UI.Diagnosed = true;
12733   }
12734 
12735   // A note on note{Pre, Post}{Use, Mod}:
12736   //
12737   // (It helps to follow the algorithm with an expression such as
12738   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
12739   //  operations before C++17 and both are well-defined in C++17).
12740   //
12741   // When visiting a node which uses/modify an object we first call notePreUse
12742   // or notePreMod before visiting its sub-expression(s). At this point the
12743   // children of the current node have not yet been visited and so the eventual
12744   // uses/modifications resulting from the children of the current node have not
12745   // been recorded yet.
12746   //
12747   // We then visit the children of the current node. After that notePostUse or
12748   // notePostMod is called. These will 1) detect an unsequenced modification
12749   // as side effect (as in "k++ + k") and 2) add a new usage with the
12750   // appropriate usage kind.
12751   //
12752   // We also have to be careful that some operation sequences modification as
12753   // side effect as well (for example: || or ,). To account for this we wrap
12754   // the visitation of such a sub-expression (for example: the LHS of || or ,)
12755   // with SequencedSubexpression. SequencedSubexpression is an RAII object
12756   // which record usages which are modifications as side effect, and then
12757   // downgrade them (or more accurately restore the previous usage which was a
12758   // modification as side effect) when exiting the scope of the sequenced
12759   // subexpression.
12760 
12761   void notePreUse(Object O, const Expr *UseExpr) {
12762     UsageInfo &UI = UsageMap[O];
12763     // Uses conflict with other modifications.
12764     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
12765   }
12766 
12767   void notePostUse(Object O, const Expr *UseExpr) {
12768     UsageInfo &UI = UsageMap[O];
12769     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
12770                /*IsModMod=*/false);
12771     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
12772   }
12773 
12774   void notePreMod(Object O, const Expr *ModExpr) {
12775     UsageInfo &UI = UsageMap[O];
12776     // Modifications conflict with other modifications and with uses.
12777     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
12778     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
12779   }
12780 
12781   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
12782     UsageInfo &UI = UsageMap[O];
12783     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
12784                /*IsModMod=*/true);
12785     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
12786   }
12787 
12788 public:
12789   SequenceChecker(Sema &S, const Expr *E,
12790                   SmallVectorImpl<const Expr *> &WorkList)
12791       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
12792     Visit(E);
12793     // Silence a -Wunused-private-field since WorkList is now unused.
12794     // TODO: Evaluate if it can be used, and if not remove it.
12795     (void)this->WorkList;
12796   }
12797 
12798   void VisitStmt(const Stmt *S) {
12799     // Skip all statements which aren't expressions for now.
12800   }
12801 
12802   void VisitExpr(const Expr *E) {
12803     // By default, just recurse to evaluated subexpressions.
12804     Base::VisitStmt(E);
12805   }
12806 
12807   void VisitCastExpr(const CastExpr *E) {
12808     Object O = Object();
12809     if (E->getCastKind() == CK_LValueToRValue)
12810       O = getObject(E->getSubExpr(), false);
12811 
12812     if (O)
12813       notePreUse(O, E);
12814     VisitExpr(E);
12815     if (O)
12816       notePostUse(O, E);
12817   }
12818 
12819   void VisitSequencedExpressions(const Expr *SequencedBefore,
12820                                  const Expr *SequencedAfter) {
12821     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
12822     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
12823     SequenceTree::Seq OldRegion = Region;
12824 
12825     {
12826       SequencedSubexpression SeqBefore(*this);
12827       Region = BeforeRegion;
12828       Visit(SequencedBefore);
12829     }
12830 
12831     Region = AfterRegion;
12832     Visit(SequencedAfter);
12833 
12834     Region = OldRegion;
12835 
12836     Tree.merge(BeforeRegion);
12837     Tree.merge(AfterRegion);
12838   }
12839 
12840   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
12841     // C++17 [expr.sub]p1:
12842     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
12843     //   expression E1 is sequenced before the expression E2.
12844     if (SemaRef.getLangOpts().CPlusPlus17)
12845       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
12846     else {
12847       Visit(ASE->getLHS());
12848       Visit(ASE->getRHS());
12849     }
12850   }
12851 
12852   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
12853   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
12854   void VisitBinPtrMem(const BinaryOperator *BO) {
12855     // C++17 [expr.mptr.oper]p4:
12856     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
12857     //  the expression E1 is sequenced before the expression E2.
12858     if (SemaRef.getLangOpts().CPlusPlus17)
12859       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12860     else {
12861       Visit(BO->getLHS());
12862       Visit(BO->getRHS());
12863     }
12864   }
12865 
12866   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
12867   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
12868   void VisitBinShlShr(const BinaryOperator *BO) {
12869     // C++17 [expr.shift]p4:
12870     //  The expression E1 is sequenced before the expression E2.
12871     if (SemaRef.getLangOpts().CPlusPlus17)
12872       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12873     else {
12874       Visit(BO->getLHS());
12875       Visit(BO->getRHS());
12876     }
12877   }
12878 
12879   void VisitBinComma(const BinaryOperator *BO) {
12880     // C++11 [expr.comma]p1:
12881     //   Every value computation and side effect associated with the left
12882     //   expression is sequenced before every value computation and side
12883     //   effect associated with the right expression.
12884     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12885   }
12886 
12887   void VisitBinAssign(const BinaryOperator *BO) {
12888     SequenceTree::Seq RHSRegion;
12889     SequenceTree::Seq LHSRegion;
12890     if (SemaRef.getLangOpts().CPlusPlus17) {
12891       RHSRegion = Tree.allocate(Region);
12892       LHSRegion = Tree.allocate(Region);
12893     } else {
12894       RHSRegion = Region;
12895       LHSRegion = Region;
12896     }
12897     SequenceTree::Seq OldRegion = Region;
12898 
12899     // C++11 [expr.ass]p1:
12900     //  [...] the assignment is sequenced after the value computation
12901     //  of the right and left operands, [...]
12902     //
12903     // so check it before inspecting the operands and update the
12904     // map afterwards.
12905     Object O = getObject(BO->getLHS(), /*Mod=*/true);
12906     if (O)
12907       notePreMod(O, BO);
12908 
12909     if (SemaRef.getLangOpts().CPlusPlus17) {
12910       // C++17 [expr.ass]p1:
12911       //  [...] The right operand is sequenced before the left operand. [...]
12912       {
12913         SequencedSubexpression SeqBefore(*this);
12914         Region = RHSRegion;
12915         Visit(BO->getRHS());
12916       }
12917 
12918       Region = LHSRegion;
12919       Visit(BO->getLHS());
12920 
12921       if (O && isa<CompoundAssignOperator>(BO))
12922         notePostUse(O, BO);
12923 
12924     } else {
12925       // C++11 does not specify any sequencing between the LHS and RHS.
12926       Region = LHSRegion;
12927       Visit(BO->getLHS());
12928 
12929       if (O && isa<CompoundAssignOperator>(BO))
12930         notePostUse(O, BO);
12931 
12932       Region = RHSRegion;
12933       Visit(BO->getRHS());
12934     }
12935 
12936     // C++11 [expr.ass]p1:
12937     //  the assignment is sequenced [...] before the value computation of the
12938     //  assignment expression.
12939     // C11 6.5.16/3 has no such rule.
12940     Region = OldRegion;
12941     if (O)
12942       notePostMod(O, BO,
12943                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12944                                                   : UK_ModAsSideEffect);
12945     if (SemaRef.getLangOpts().CPlusPlus17) {
12946       Tree.merge(RHSRegion);
12947       Tree.merge(LHSRegion);
12948     }
12949   }
12950 
12951   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
12952     VisitBinAssign(CAO);
12953   }
12954 
12955   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12956   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12957   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
12958     Object O = getObject(UO->getSubExpr(), true);
12959     if (!O)
12960       return VisitExpr(UO);
12961 
12962     notePreMod(O, UO);
12963     Visit(UO->getSubExpr());
12964     // C++11 [expr.pre.incr]p1:
12965     //   the expression ++x is equivalent to x+=1
12966     notePostMod(O, UO,
12967                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12968                                                 : UK_ModAsSideEffect);
12969   }
12970 
12971   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12972   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12973   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
12974     Object O = getObject(UO->getSubExpr(), true);
12975     if (!O)
12976       return VisitExpr(UO);
12977 
12978     notePreMod(O, UO);
12979     Visit(UO->getSubExpr());
12980     notePostMod(O, UO, UK_ModAsSideEffect);
12981   }
12982 
12983   void VisitBinLOr(const BinaryOperator *BO) {
12984     // C++11 [expr.log.or]p2:
12985     //  If the second expression is evaluated, every value computation and
12986     //  side effect associated with the first expression is sequenced before
12987     //  every value computation and side effect associated with the
12988     //  second expression.
12989     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
12990     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
12991     SequenceTree::Seq OldRegion = Region;
12992 
12993     EvaluationTracker Eval(*this);
12994     {
12995       SequencedSubexpression Sequenced(*this);
12996       Region = LHSRegion;
12997       Visit(BO->getLHS());
12998     }
12999 
13000     // C++11 [expr.log.or]p1:
13001     //  [...] the second operand is not evaluated if the first operand
13002     //  evaluates to true.
13003     bool EvalResult = false;
13004     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
13005     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
13006     if (ShouldVisitRHS) {
13007       Region = RHSRegion;
13008       Visit(BO->getRHS());
13009     }
13010 
13011     Region = OldRegion;
13012     Tree.merge(LHSRegion);
13013     Tree.merge(RHSRegion);
13014   }
13015 
13016   void VisitBinLAnd(const BinaryOperator *BO) {
13017     // C++11 [expr.log.and]p2:
13018     //  If the second expression is evaluated, every value computation and
13019     //  side effect associated with the first expression is sequenced before
13020     //  every value computation and side effect associated with the
13021     //  second expression.
13022     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
13023     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
13024     SequenceTree::Seq OldRegion = Region;
13025 
13026     EvaluationTracker Eval(*this);
13027     {
13028       SequencedSubexpression Sequenced(*this);
13029       Region = LHSRegion;
13030       Visit(BO->getLHS());
13031     }
13032 
13033     // C++11 [expr.log.and]p1:
13034     //  [...] the second operand is not evaluated if the first operand is false.
13035     bool EvalResult = false;
13036     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
13037     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
13038     if (ShouldVisitRHS) {
13039       Region = RHSRegion;
13040       Visit(BO->getRHS());
13041     }
13042 
13043     Region = OldRegion;
13044     Tree.merge(LHSRegion);
13045     Tree.merge(RHSRegion);
13046   }
13047 
13048   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
13049     // C++11 [expr.cond]p1:
13050     //  [...] Every value computation and side effect associated with the first
13051     //  expression is sequenced before every value computation and side effect
13052     //  associated with the second or third expression.
13053     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
13054 
13055     // No sequencing is specified between the true and false expression.
13056     // However since exactly one of both is going to be evaluated we can
13057     // consider them to be sequenced. This is needed to avoid warning on
13058     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
13059     // both the true and false expressions because we can't evaluate x.
13060     // This will still allow us to detect an expression like (pre C++17)
13061     // "(x ? y += 1 : y += 2) = y".
13062     //
13063     // We don't wrap the visitation of the true and false expression with
13064     // SequencedSubexpression because we don't want to downgrade modifications
13065     // as side effect in the true and false expressions after the visition
13066     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
13067     // not warn between the two "y++", but we should warn between the "y++"
13068     // and the "y".
13069     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
13070     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
13071     SequenceTree::Seq OldRegion = Region;
13072 
13073     EvaluationTracker Eval(*this);
13074     {
13075       SequencedSubexpression Sequenced(*this);
13076       Region = ConditionRegion;
13077       Visit(CO->getCond());
13078     }
13079 
13080     // C++11 [expr.cond]p1:
13081     // [...] The first expression is contextually converted to bool (Clause 4).
13082     // It is evaluated and if it is true, the result of the conditional
13083     // expression is the value of the second expression, otherwise that of the
13084     // third expression. Only one of the second and third expressions is
13085     // evaluated. [...]
13086     bool EvalResult = false;
13087     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
13088     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
13089     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
13090     if (ShouldVisitTrueExpr) {
13091       Region = TrueRegion;
13092       Visit(CO->getTrueExpr());
13093     }
13094     if (ShouldVisitFalseExpr) {
13095       Region = FalseRegion;
13096       Visit(CO->getFalseExpr());
13097     }
13098 
13099     Region = OldRegion;
13100     Tree.merge(ConditionRegion);
13101     Tree.merge(TrueRegion);
13102     Tree.merge(FalseRegion);
13103   }
13104 
13105   void VisitCallExpr(const CallExpr *CE) {
13106     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
13107 
13108     if (CE->isUnevaluatedBuiltinCall(Context))
13109       return;
13110 
13111     // C++11 [intro.execution]p15:
13112     //   When calling a function [...], every value computation and side effect
13113     //   associated with any argument expression, or with the postfix expression
13114     //   designating the called function, is sequenced before execution of every
13115     //   expression or statement in the body of the function [and thus before
13116     //   the value computation of its result].
13117     SequencedSubexpression Sequenced(*this);
13118     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
13119       // C++17 [expr.call]p5
13120       //   The postfix-expression is sequenced before each expression in the
13121       //   expression-list and any default argument. [...]
13122       SequenceTree::Seq CalleeRegion;
13123       SequenceTree::Seq OtherRegion;
13124       if (SemaRef.getLangOpts().CPlusPlus17) {
13125         CalleeRegion = Tree.allocate(Region);
13126         OtherRegion = Tree.allocate(Region);
13127       } else {
13128         CalleeRegion = Region;
13129         OtherRegion = Region;
13130       }
13131       SequenceTree::Seq OldRegion = Region;
13132 
13133       // Visit the callee expression first.
13134       Region = CalleeRegion;
13135       if (SemaRef.getLangOpts().CPlusPlus17) {
13136         SequencedSubexpression Sequenced(*this);
13137         Visit(CE->getCallee());
13138       } else {
13139         Visit(CE->getCallee());
13140       }
13141 
13142       // Then visit the argument expressions.
13143       Region = OtherRegion;
13144       for (const Expr *Argument : CE->arguments())
13145         Visit(Argument);
13146 
13147       Region = OldRegion;
13148       if (SemaRef.getLangOpts().CPlusPlus17) {
13149         Tree.merge(CalleeRegion);
13150         Tree.merge(OtherRegion);
13151       }
13152     });
13153   }
13154 
13155   void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
13156     // C++17 [over.match.oper]p2:
13157     //   [...] the operator notation is first transformed to the equivalent
13158     //   function-call notation as summarized in Table 12 (where @ denotes one
13159     //   of the operators covered in the specified subclause). However, the
13160     //   operands are sequenced in the order prescribed for the built-in
13161     //   operator (Clause 8).
13162     //
13163     // From the above only overloaded binary operators and overloaded call
13164     // operators have sequencing rules in C++17 that we need to handle
13165     // separately.
13166     if (!SemaRef.getLangOpts().CPlusPlus17 ||
13167         (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
13168       return VisitCallExpr(CXXOCE);
13169 
13170     enum {
13171       NoSequencing,
13172       LHSBeforeRHS,
13173       RHSBeforeLHS,
13174       LHSBeforeRest
13175     } SequencingKind;
13176     switch (CXXOCE->getOperator()) {
13177     case OO_Equal:
13178     case OO_PlusEqual:
13179     case OO_MinusEqual:
13180     case OO_StarEqual:
13181     case OO_SlashEqual:
13182     case OO_PercentEqual:
13183     case OO_CaretEqual:
13184     case OO_AmpEqual:
13185     case OO_PipeEqual:
13186     case OO_LessLessEqual:
13187     case OO_GreaterGreaterEqual:
13188       SequencingKind = RHSBeforeLHS;
13189       break;
13190 
13191     case OO_LessLess:
13192     case OO_GreaterGreater:
13193     case OO_AmpAmp:
13194     case OO_PipePipe:
13195     case OO_Comma:
13196     case OO_ArrowStar:
13197     case OO_Subscript:
13198       SequencingKind = LHSBeforeRHS;
13199       break;
13200 
13201     case OO_Call:
13202       SequencingKind = LHSBeforeRest;
13203       break;
13204 
13205     default:
13206       SequencingKind = NoSequencing;
13207       break;
13208     }
13209 
13210     if (SequencingKind == NoSequencing)
13211       return VisitCallExpr(CXXOCE);
13212 
13213     // This is a call, so all subexpressions are sequenced before the result.
13214     SequencedSubexpression Sequenced(*this);
13215 
13216     SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
13217       assert(SemaRef.getLangOpts().CPlusPlus17 &&
13218              "Should only get there with C++17 and above!");
13219       assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
13220              "Should only get there with an overloaded binary operator"
13221              " or an overloaded call operator!");
13222 
13223       if (SequencingKind == LHSBeforeRest) {
13224         assert(CXXOCE->getOperator() == OO_Call &&
13225                "We should only have an overloaded call operator here!");
13226 
13227         // This is very similar to VisitCallExpr, except that we only have the
13228         // C++17 case. The postfix-expression is the first argument of the
13229         // CXXOperatorCallExpr. The expressions in the expression-list, if any,
13230         // are in the following arguments.
13231         //
13232         // Note that we intentionally do not visit the callee expression since
13233         // it is just a decayed reference to a function.
13234         SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
13235         SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
13236         SequenceTree::Seq OldRegion = Region;
13237 
13238         assert(CXXOCE->getNumArgs() >= 1 &&
13239                "An overloaded call operator must have at least one argument"
13240                " for the postfix-expression!");
13241         const Expr *PostfixExpr = CXXOCE->getArgs()[0];
13242         llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
13243                                           CXXOCE->getNumArgs() - 1);
13244 
13245         // Visit the postfix-expression first.
13246         {
13247           Region = PostfixExprRegion;
13248           SequencedSubexpression Sequenced(*this);
13249           Visit(PostfixExpr);
13250         }
13251 
13252         // Then visit the argument expressions.
13253         Region = ArgsRegion;
13254         for (const Expr *Arg : Args)
13255           Visit(Arg);
13256 
13257         Region = OldRegion;
13258         Tree.merge(PostfixExprRegion);
13259         Tree.merge(ArgsRegion);
13260       } else {
13261         assert(CXXOCE->getNumArgs() == 2 &&
13262                "Should only have two arguments here!");
13263         assert((SequencingKind == LHSBeforeRHS ||
13264                 SequencingKind == RHSBeforeLHS) &&
13265                "Unexpected sequencing kind!");
13266 
13267         // We do not visit the callee expression since it is just a decayed
13268         // reference to a function.
13269         const Expr *E1 = CXXOCE->getArg(0);
13270         const Expr *E2 = CXXOCE->getArg(1);
13271         if (SequencingKind == RHSBeforeLHS)
13272           std::swap(E1, E2);
13273 
13274         return VisitSequencedExpressions(E1, E2);
13275       }
13276     });
13277   }
13278 
13279   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
13280     // This is a call, so all subexpressions are sequenced before the result.
13281     SequencedSubexpression Sequenced(*this);
13282 
13283     if (!CCE->isListInitialization())
13284       return VisitExpr(CCE);
13285 
13286     // In C++11, list initializations are sequenced.
13287     SmallVector<SequenceTree::Seq, 32> Elts;
13288     SequenceTree::Seq Parent = Region;
13289     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
13290                                               E = CCE->arg_end();
13291          I != E; ++I) {
13292       Region = Tree.allocate(Parent);
13293       Elts.push_back(Region);
13294       Visit(*I);
13295     }
13296 
13297     // Forget that the initializers are sequenced.
13298     Region = Parent;
13299     for (unsigned I = 0; I < Elts.size(); ++I)
13300       Tree.merge(Elts[I]);
13301   }
13302 
13303   void VisitInitListExpr(const InitListExpr *ILE) {
13304     if (!SemaRef.getLangOpts().CPlusPlus11)
13305       return VisitExpr(ILE);
13306 
13307     // In C++11, list initializations are sequenced.
13308     SmallVector<SequenceTree::Seq, 32> Elts;
13309     SequenceTree::Seq Parent = Region;
13310     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
13311       const Expr *E = ILE->getInit(I);
13312       if (!E)
13313         continue;
13314       Region = Tree.allocate(Parent);
13315       Elts.push_back(Region);
13316       Visit(E);
13317     }
13318 
13319     // Forget that the initializers are sequenced.
13320     Region = Parent;
13321     for (unsigned I = 0; I < Elts.size(); ++I)
13322       Tree.merge(Elts[I]);
13323   }
13324 };
13325 
13326 } // namespace
13327 
13328 void Sema::CheckUnsequencedOperations(const Expr *E) {
13329   SmallVector<const Expr *, 8> WorkList;
13330   WorkList.push_back(E);
13331   while (!WorkList.empty()) {
13332     const Expr *Item = WorkList.pop_back_val();
13333     SequenceChecker(*this, Item, WorkList);
13334   }
13335 }
13336 
13337 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
13338                               bool IsConstexpr) {
13339   llvm::SaveAndRestore<bool> ConstantContext(
13340       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
13341   CheckImplicitConversions(E, CheckLoc);
13342   if (!E->isInstantiationDependent())
13343     CheckUnsequencedOperations(E);
13344   if (!IsConstexpr && !E->isValueDependent())
13345     CheckForIntOverflow(E);
13346   DiagnoseMisalignedMembers();
13347 }
13348 
13349 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
13350                                        FieldDecl *BitField,
13351                                        Expr *Init) {
13352   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
13353 }
13354 
13355 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
13356                                          SourceLocation Loc) {
13357   if (!PType->isVariablyModifiedType())
13358     return;
13359   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
13360     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
13361     return;
13362   }
13363   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
13364     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
13365     return;
13366   }
13367   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
13368     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
13369     return;
13370   }
13371 
13372   const ArrayType *AT = S.Context.getAsArrayType(PType);
13373   if (!AT)
13374     return;
13375 
13376   if (AT->getSizeModifier() != ArrayType::Star) {
13377     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
13378     return;
13379   }
13380 
13381   S.Diag(Loc, diag::err_array_star_in_function_definition);
13382 }
13383 
13384 /// CheckParmsForFunctionDef - Check that the parameters of the given
13385 /// function are appropriate for the definition of a function. This
13386 /// takes care of any checks that cannot be performed on the
13387 /// declaration itself, e.g., that the types of each of the function
13388 /// parameters are complete.
13389 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
13390                                     bool CheckParameterNames) {
13391   bool HasInvalidParm = false;
13392   for (ParmVarDecl *Param : Parameters) {
13393     // C99 6.7.5.3p4: the parameters in a parameter type list in a
13394     // function declarator that is part of a function definition of
13395     // that function shall not have incomplete type.
13396     //
13397     // This is also C++ [dcl.fct]p6.
13398     if (!Param->isInvalidDecl() &&
13399         RequireCompleteType(Param->getLocation(), Param->getType(),
13400                             diag::err_typecheck_decl_incomplete_type)) {
13401       Param->setInvalidDecl();
13402       HasInvalidParm = true;
13403     }
13404 
13405     // C99 6.9.1p5: If the declarator includes a parameter type list, the
13406     // declaration of each parameter shall include an identifier.
13407     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
13408         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
13409       // Diagnose this as an extension in C17 and earlier.
13410       if (!getLangOpts().C2x)
13411         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
13412     }
13413 
13414     // C99 6.7.5.3p12:
13415     //   If the function declarator is not part of a definition of that
13416     //   function, parameters may have incomplete type and may use the [*]
13417     //   notation in their sequences of declarator specifiers to specify
13418     //   variable length array types.
13419     QualType PType = Param->getOriginalType();
13420     // FIXME: This diagnostic should point the '[*]' if source-location
13421     // information is added for it.
13422     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
13423 
13424     // If the parameter is a c++ class type and it has to be destructed in the
13425     // callee function, declare the destructor so that it can be called by the
13426     // callee function. Do not perform any direct access check on the dtor here.
13427     if (!Param->isInvalidDecl()) {
13428       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
13429         if (!ClassDecl->isInvalidDecl() &&
13430             !ClassDecl->hasIrrelevantDestructor() &&
13431             !ClassDecl->isDependentContext() &&
13432             ClassDecl->isParamDestroyedInCallee()) {
13433           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
13434           MarkFunctionReferenced(Param->getLocation(), Destructor);
13435           DiagnoseUseOfDecl(Destructor, Param->getLocation());
13436         }
13437       }
13438     }
13439 
13440     // Parameters with the pass_object_size attribute only need to be marked
13441     // constant at function definitions. Because we lack information about
13442     // whether we're on a declaration or definition when we're instantiating the
13443     // attribute, we need to check for constness here.
13444     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
13445       if (!Param->getType().isConstQualified())
13446         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
13447             << Attr->getSpelling() << 1;
13448 
13449     // Check for parameter names shadowing fields from the class.
13450     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
13451       // The owning context for the parameter should be the function, but we
13452       // want to see if this function's declaration context is a record.
13453       DeclContext *DC = Param->getDeclContext();
13454       if (DC && DC->isFunctionOrMethod()) {
13455         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
13456           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
13457                                      RD, /*DeclIsField*/ false);
13458       }
13459     }
13460   }
13461 
13462   return HasInvalidParm;
13463 }
13464 
13465 Optional<std::pair<CharUnits, CharUnits>>
13466 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
13467 
13468 /// Compute the alignment and offset of the base class object given the
13469 /// derived-to-base cast expression and the alignment and offset of the derived
13470 /// class object.
13471 static std::pair<CharUnits, CharUnits>
13472 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
13473                                    CharUnits BaseAlignment, CharUnits Offset,
13474                                    ASTContext &Ctx) {
13475   for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
13476        ++PathI) {
13477     const CXXBaseSpecifier *Base = *PathI;
13478     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
13479     if (Base->isVirtual()) {
13480       // The complete object may have a lower alignment than the non-virtual
13481       // alignment of the base, in which case the base may be misaligned. Choose
13482       // the smaller of the non-virtual alignment and BaseAlignment, which is a
13483       // conservative lower bound of the complete object alignment.
13484       CharUnits NonVirtualAlignment =
13485           Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
13486       BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
13487       Offset = CharUnits::Zero();
13488     } else {
13489       const ASTRecordLayout &RL =
13490           Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
13491       Offset += RL.getBaseClassOffset(BaseDecl);
13492     }
13493     DerivedType = Base->getType();
13494   }
13495 
13496   return std::make_pair(BaseAlignment, Offset);
13497 }
13498 
13499 /// Compute the alignment and offset of a binary additive operator.
13500 static Optional<std::pair<CharUnits, CharUnits>>
13501 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
13502                                      bool IsSub, ASTContext &Ctx) {
13503   QualType PointeeType = PtrE->getType()->getPointeeType();
13504 
13505   if (!PointeeType->isConstantSizeType())
13506     return llvm::None;
13507 
13508   auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
13509 
13510   if (!P)
13511     return llvm::None;
13512 
13513   llvm::APSInt IdxRes;
13514   CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
13515   if (IntE->isIntegerConstantExpr(IdxRes, Ctx)) {
13516     CharUnits Offset = EltSize * IdxRes.getExtValue();
13517     if (IsSub)
13518       Offset = -Offset;
13519     return std::make_pair(P->first, P->second + Offset);
13520   }
13521 
13522   // If the integer expression isn't a constant expression, compute the lower
13523   // bound of the alignment using the alignment and offset of the pointer
13524   // expression and the element size.
13525   return std::make_pair(
13526       P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
13527       CharUnits::Zero());
13528 }
13529 
13530 /// This helper function takes an lvalue expression and returns the alignment of
13531 /// a VarDecl and a constant offset from the VarDecl.
13532 Optional<std::pair<CharUnits, CharUnits>>
13533 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
13534   E = E->IgnoreParens();
13535   switch (E->getStmtClass()) {
13536   default:
13537     break;
13538   case Stmt::CStyleCastExprClass:
13539   case Stmt::CXXStaticCastExprClass:
13540   case Stmt::ImplicitCastExprClass: {
13541     auto *CE = cast<CastExpr>(E);
13542     const Expr *From = CE->getSubExpr();
13543     switch (CE->getCastKind()) {
13544     default:
13545       break;
13546     case CK_NoOp:
13547       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
13548     case CK_UncheckedDerivedToBase:
13549     case CK_DerivedToBase: {
13550       auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
13551       if (!P)
13552         break;
13553       return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
13554                                                 P->second, Ctx);
13555     }
13556     }
13557     break;
13558   }
13559   case Stmt::ArraySubscriptExprClass: {
13560     auto *ASE = cast<ArraySubscriptExpr>(E);
13561     return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
13562                                                 false, Ctx);
13563   }
13564   case Stmt::DeclRefExprClass: {
13565     if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
13566       // FIXME: If VD is captured by copy or is an escaping __block variable,
13567       // use the alignment of VD's type.
13568       if (!VD->getType()->isReferenceType())
13569         return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
13570       if (VD->hasInit())
13571         return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
13572     }
13573     break;
13574   }
13575   case Stmt::MemberExprClass: {
13576     auto *ME = cast<MemberExpr>(E);
13577     auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
13578     if (!FD || FD->getType()->isReferenceType())
13579       break;
13580     Optional<std::pair<CharUnits, CharUnits>> P;
13581     if (ME->isArrow())
13582       P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
13583     else
13584       P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
13585     if (!P)
13586       break;
13587     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
13588     uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
13589     return std::make_pair(P->first,
13590                           P->second + CharUnits::fromQuantity(Offset));
13591   }
13592   case Stmt::UnaryOperatorClass: {
13593     auto *UO = cast<UnaryOperator>(E);
13594     switch (UO->getOpcode()) {
13595     default:
13596       break;
13597     case UO_Deref:
13598       return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
13599     }
13600     break;
13601   }
13602   case Stmt::BinaryOperatorClass: {
13603     auto *BO = cast<BinaryOperator>(E);
13604     auto Opcode = BO->getOpcode();
13605     switch (Opcode) {
13606     default:
13607       break;
13608     case BO_Comma:
13609       return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
13610     }
13611     break;
13612   }
13613   }
13614   return llvm::None;
13615 }
13616 
13617 /// This helper function takes a pointer expression and returns the alignment of
13618 /// a VarDecl and a constant offset from the VarDecl.
13619 Optional<std::pair<CharUnits, CharUnits>>
13620 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
13621   E = E->IgnoreParens();
13622   switch (E->getStmtClass()) {
13623   default:
13624     break;
13625   case Stmt::CStyleCastExprClass:
13626   case Stmt::CXXStaticCastExprClass:
13627   case Stmt::ImplicitCastExprClass: {
13628     auto *CE = cast<CastExpr>(E);
13629     const Expr *From = CE->getSubExpr();
13630     switch (CE->getCastKind()) {
13631     default:
13632       break;
13633     case CK_NoOp:
13634       return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
13635     case CK_ArrayToPointerDecay:
13636       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
13637     case CK_UncheckedDerivedToBase:
13638     case CK_DerivedToBase: {
13639       auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
13640       if (!P)
13641         break;
13642       return getDerivedToBaseAlignmentAndOffset(
13643           CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
13644     }
13645     }
13646     break;
13647   }
13648   case Stmt::CXXThisExprClass: {
13649     auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
13650     CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment();
13651     return std::make_pair(Alignment, CharUnits::Zero());
13652   }
13653   case Stmt::UnaryOperatorClass: {
13654     auto *UO = cast<UnaryOperator>(E);
13655     if (UO->getOpcode() == UO_AddrOf)
13656       return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
13657     break;
13658   }
13659   case Stmt::BinaryOperatorClass: {
13660     auto *BO = cast<BinaryOperator>(E);
13661     auto Opcode = BO->getOpcode();
13662     switch (Opcode) {
13663     default:
13664       break;
13665     case BO_Add:
13666     case BO_Sub: {
13667       const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
13668       if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
13669         std::swap(LHS, RHS);
13670       return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
13671                                                   Ctx);
13672     }
13673     case BO_Comma:
13674       return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
13675     }
13676     break;
13677   }
13678   }
13679   return llvm::None;
13680 }
13681 
13682 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
13683   // See if we can compute the alignment of a VarDecl and an offset from it.
13684   Optional<std::pair<CharUnits, CharUnits>> P =
13685       getBaseAlignmentAndOffsetFromPtr(E, S.Context);
13686 
13687   if (P)
13688     return P->first.alignmentAtOffset(P->second);
13689 
13690   // If that failed, return the type's alignment.
13691   return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
13692 }
13693 
13694 /// CheckCastAlign - Implements -Wcast-align, which warns when a
13695 /// pointer cast increases the alignment requirements.
13696 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
13697   // This is actually a lot of work to potentially be doing on every
13698   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
13699   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
13700     return;
13701 
13702   // Ignore dependent types.
13703   if (T->isDependentType() || Op->getType()->isDependentType())
13704     return;
13705 
13706   // Require that the destination be a pointer type.
13707   const PointerType *DestPtr = T->getAs<PointerType>();
13708   if (!DestPtr) return;
13709 
13710   // If the destination has alignment 1, we're done.
13711   QualType DestPointee = DestPtr->getPointeeType();
13712   if (DestPointee->isIncompleteType()) return;
13713   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
13714   if (DestAlign.isOne()) return;
13715 
13716   // Require that the source be a pointer type.
13717   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
13718   if (!SrcPtr) return;
13719   QualType SrcPointee = SrcPtr->getPointeeType();
13720 
13721   // Explicitly allow casts from cv void*.  We already implicitly
13722   // allowed casts to cv void*, since they have alignment 1.
13723   // Also allow casts involving incomplete types, which implicitly
13724   // includes 'void'.
13725   if (SrcPointee->isIncompleteType()) return;
13726 
13727   CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
13728 
13729   if (SrcAlign >= DestAlign) return;
13730 
13731   Diag(TRange.getBegin(), diag::warn_cast_align)
13732     << Op->getType() << T
13733     << static_cast<unsigned>(SrcAlign.getQuantity())
13734     << static_cast<unsigned>(DestAlign.getQuantity())
13735     << TRange << Op->getSourceRange();
13736 }
13737 
13738 /// Check whether this array fits the idiom of a size-one tail padded
13739 /// array member of a struct.
13740 ///
13741 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
13742 /// commonly used to emulate flexible arrays in C89 code.
13743 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
13744                                     const NamedDecl *ND) {
13745   if (Size != 1 || !ND) return false;
13746 
13747   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
13748   if (!FD) return false;
13749 
13750   // Don't consider sizes resulting from macro expansions or template argument
13751   // substitution to form C89 tail-padded arrays.
13752 
13753   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
13754   while (TInfo) {
13755     TypeLoc TL = TInfo->getTypeLoc();
13756     // Look through typedefs.
13757     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
13758       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
13759       TInfo = TDL->getTypeSourceInfo();
13760       continue;
13761     }
13762     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
13763       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
13764       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
13765         return false;
13766     }
13767     break;
13768   }
13769 
13770   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
13771   if (!RD) return false;
13772   if (RD->isUnion()) return false;
13773   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
13774     if (!CRD->isStandardLayout()) return false;
13775   }
13776 
13777   // See if this is the last field decl in the record.
13778   const Decl *D = FD;
13779   while ((D = D->getNextDeclInContext()))
13780     if (isa<FieldDecl>(D))
13781       return false;
13782   return true;
13783 }
13784 
13785 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
13786                             const ArraySubscriptExpr *ASE,
13787                             bool AllowOnePastEnd, bool IndexNegated) {
13788   // Already diagnosed by the constant evaluator.
13789   if (isConstantEvaluated())
13790     return;
13791 
13792   IndexExpr = IndexExpr->IgnoreParenImpCasts();
13793   if (IndexExpr->isValueDependent())
13794     return;
13795 
13796   const Type *EffectiveType =
13797       BaseExpr->getType()->getPointeeOrArrayElementType();
13798   BaseExpr = BaseExpr->IgnoreParenCasts();
13799   const ConstantArrayType *ArrayTy =
13800       Context.getAsConstantArrayType(BaseExpr->getType());
13801 
13802   if (!ArrayTy)
13803     return;
13804 
13805   const Type *BaseType = ArrayTy->getElementType().getTypePtr();
13806   if (EffectiveType->isDependentType() || BaseType->isDependentType())
13807     return;
13808 
13809   Expr::EvalResult Result;
13810   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
13811     return;
13812 
13813   llvm::APSInt index = Result.Val.getInt();
13814   if (IndexNegated)
13815     index = -index;
13816 
13817   const NamedDecl *ND = nullptr;
13818   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
13819     ND = DRE->getDecl();
13820   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
13821     ND = ME->getMemberDecl();
13822 
13823   if (index.isUnsigned() || !index.isNegative()) {
13824     // It is possible that the type of the base expression after
13825     // IgnoreParenCasts is incomplete, even though the type of the base
13826     // expression before IgnoreParenCasts is complete (see PR39746 for an
13827     // example). In this case we have no information about whether the array
13828     // access exceeds the array bounds. However we can still diagnose an array
13829     // access which precedes the array bounds.
13830     if (BaseType->isIncompleteType())
13831       return;
13832 
13833     llvm::APInt size = ArrayTy->getSize();
13834     if (!size.isStrictlyPositive())
13835       return;
13836 
13837     if (BaseType != EffectiveType) {
13838       // Make sure we're comparing apples to apples when comparing index to size
13839       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
13840       uint64_t array_typesize = Context.getTypeSize(BaseType);
13841       // Handle ptrarith_typesize being zero, such as when casting to void*
13842       if (!ptrarith_typesize) ptrarith_typesize = 1;
13843       if (ptrarith_typesize != array_typesize) {
13844         // There's a cast to a different size type involved
13845         uint64_t ratio = array_typesize / ptrarith_typesize;
13846         // TODO: Be smarter about handling cases where array_typesize is not a
13847         // multiple of ptrarith_typesize
13848         if (ptrarith_typesize * ratio == array_typesize)
13849           size *= llvm::APInt(size.getBitWidth(), ratio);
13850       }
13851     }
13852 
13853     if (size.getBitWidth() > index.getBitWidth())
13854       index = index.zext(size.getBitWidth());
13855     else if (size.getBitWidth() < index.getBitWidth())
13856       size = size.zext(index.getBitWidth());
13857 
13858     // For array subscripting the index must be less than size, but for pointer
13859     // arithmetic also allow the index (offset) to be equal to size since
13860     // computing the next address after the end of the array is legal and
13861     // commonly done e.g. in C++ iterators and range-based for loops.
13862     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
13863       return;
13864 
13865     // Also don't warn for arrays of size 1 which are members of some
13866     // structure. These are often used to approximate flexible arrays in C89
13867     // code.
13868     if (IsTailPaddedMemberArray(*this, size, ND))
13869       return;
13870 
13871     // Suppress the warning if the subscript expression (as identified by the
13872     // ']' location) and the index expression are both from macro expansions
13873     // within a system header.
13874     if (ASE) {
13875       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
13876           ASE->getRBracketLoc());
13877       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
13878         SourceLocation IndexLoc =
13879             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
13880         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
13881           return;
13882       }
13883     }
13884 
13885     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
13886     if (ASE)
13887       DiagID = diag::warn_array_index_exceeds_bounds;
13888 
13889     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
13890                         PDiag(DiagID) << index.toString(10, true)
13891                                       << size.toString(10, true)
13892                                       << (unsigned)size.getLimitedValue(~0U)
13893                                       << IndexExpr->getSourceRange());
13894   } else {
13895     unsigned DiagID = diag::warn_array_index_precedes_bounds;
13896     if (!ASE) {
13897       DiagID = diag::warn_ptr_arith_precedes_bounds;
13898       if (index.isNegative()) index = -index;
13899     }
13900 
13901     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
13902                         PDiag(DiagID) << index.toString(10, true)
13903                                       << IndexExpr->getSourceRange());
13904   }
13905 
13906   if (!ND) {
13907     // Try harder to find a NamedDecl to point at in the note.
13908     while (const ArraySubscriptExpr *ASE =
13909            dyn_cast<ArraySubscriptExpr>(BaseExpr))
13910       BaseExpr = ASE->getBase()->IgnoreParenCasts();
13911     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
13912       ND = DRE->getDecl();
13913     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
13914       ND = ME->getMemberDecl();
13915   }
13916 
13917   if (ND)
13918     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
13919                         PDiag(diag::note_array_declared_here)
13920                             << ND->getDeclName());
13921 }
13922 
13923 void Sema::CheckArrayAccess(const Expr *expr) {
13924   int AllowOnePastEnd = 0;
13925   while (expr) {
13926     expr = expr->IgnoreParenImpCasts();
13927     switch (expr->getStmtClass()) {
13928       case Stmt::ArraySubscriptExprClass: {
13929         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
13930         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
13931                          AllowOnePastEnd > 0);
13932         expr = ASE->getBase();
13933         break;
13934       }
13935       case Stmt::MemberExprClass: {
13936         expr = cast<MemberExpr>(expr)->getBase();
13937         break;
13938       }
13939       case Stmt::OMPArraySectionExprClass: {
13940         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
13941         if (ASE->getLowerBound())
13942           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
13943                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
13944         return;
13945       }
13946       case Stmt::UnaryOperatorClass: {
13947         // Only unwrap the * and & unary operators
13948         const UnaryOperator *UO = cast<UnaryOperator>(expr);
13949         expr = UO->getSubExpr();
13950         switch (UO->getOpcode()) {
13951           case UO_AddrOf:
13952             AllowOnePastEnd++;
13953             break;
13954           case UO_Deref:
13955             AllowOnePastEnd--;
13956             break;
13957           default:
13958             return;
13959         }
13960         break;
13961       }
13962       case Stmt::ConditionalOperatorClass: {
13963         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
13964         if (const Expr *lhs = cond->getLHS())
13965           CheckArrayAccess(lhs);
13966         if (const Expr *rhs = cond->getRHS())
13967           CheckArrayAccess(rhs);
13968         return;
13969       }
13970       case Stmt::CXXOperatorCallExprClass: {
13971         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
13972         for (const auto *Arg : OCE->arguments())
13973           CheckArrayAccess(Arg);
13974         return;
13975       }
13976       default:
13977         return;
13978     }
13979   }
13980 }
13981 
13982 //===--- CHECK: Objective-C retain cycles ----------------------------------//
13983 
13984 namespace {
13985 
13986 struct RetainCycleOwner {
13987   VarDecl *Variable = nullptr;
13988   SourceRange Range;
13989   SourceLocation Loc;
13990   bool Indirect = false;
13991 
13992   RetainCycleOwner() = default;
13993 
13994   void setLocsFrom(Expr *e) {
13995     Loc = e->getExprLoc();
13996     Range = e->getSourceRange();
13997   }
13998 };
13999 
14000 } // namespace
14001 
14002 /// Consider whether capturing the given variable can possibly lead to
14003 /// a retain cycle.
14004 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
14005   // In ARC, it's captured strongly iff the variable has __strong
14006   // lifetime.  In MRR, it's captured strongly if the variable is
14007   // __block and has an appropriate type.
14008   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
14009     return false;
14010 
14011   owner.Variable = var;
14012   if (ref)
14013     owner.setLocsFrom(ref);
14014   return true;
14015 }
14016 
14017 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
14018   while (true) {
14019     e = e->IgnoreParens();
14020     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
14021       switch (cast->getCastKind()) {
14022       case CK_BitCast:
14023       case CK_LValueBitCast:
14024       case CK_LValueToRValue:
14025       case CK_ARCReclaimReturnedObject:
14026         e = cast->getSubExpr();
14027         continue;
14028 
14029       default:
14030         return false;
14031       }
14032     }
14033 
14034     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
14035       ObjCIvarDecl *ivar = ref->getDecl();
14036       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
14037         return false;
14038 
14039       // Try to find a retain cycle in the base.
14040       if (!findRetainCycleOwner(S, ref->getBase(), owner))
14041         return false;
14042 
14043       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
14044       owner.Indirect = true;
14045       return true;
14046     }
14047 
14048     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
14049       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
14050       if (!var) return false;
14051       return considerVariable(var, ref, owner);
14052     }
14053 
14054     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
14055       if (member->isArrow()) return false;
14056 
14057       // Don't count this as an indirect ownership.
14058       e = member->getBase();
14059       continue;
14060     }
14061 
14062     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
14063       // Only pay attention to pseudo-objects on property references.
14064       ObjCPropertyRefExpr *pre
14065         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
14066                                               ->IgnoreParens());
14067       if (!pre) return false;
14068       if (pre->isImplicitProperty()) return false;
14069       ObjCPropertyDecl *property = pre->getExplicitProperty();
14070       if (!property->isRetaining() &&
14071           !(property->getPropertyIvarDecl() &&
14072             property->getPropertyIvarDecl()->getType()
14073               .getObjCLifetime() == Qualifiers::OCL_Strong))
14074           return false;
14075 
14076       owner.Indirect = true;
14077       if (pre->isSuperReceiver()) {
14078         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
14079         if (!owner.Variable)
14080           return false;
14081         owner.Loc = pre->getLocation();
14082         owner.Range = pre->getSourceRange();
14083         return true;
14084       }
14085       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
14086                               ->getSourceExpr());
14087       continue;
14088     }
14089 
14090     // Array ivars?
14091 
14092     return false;
14093   }
14094 }
14095 
14096 namespace {
14097 
14098   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
14099     ASTContext &Context;
14100     VarDecl *Variable;
14101     Expr *Capturer = nullptr;
14102     bool VarWillBeReased = false;
14103 
14104     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
14105         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
14106           Context(Context), Variable(variable) {}
14107 
14108     void VisitDeclRefExpr(DeclRefExpr *ref) {
14109       if (ref->getDecl() == Variable && !Capturer)
14110         Capturer = ref;
14111     }
14112 
14113     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
14114       if (Capturer) return;
14115       Visit(ref->getBase());
14116       if (Capturer && ref->isFreeIvar())
14117         Capturer = ref;
14118     }
14119 
14120     void VisitBlockExpr(BlockExpr *block) {
14121       // Look inside nested blocks
14122       if (block->getBlockDecl()->capturesVariable(Variable))
14123         Visit(block->getBlockDecl()->getBody());
14124     }
14125 
14126     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
14127       if (Capturer) return;
14128       if (OVE->getSourceExpr())
14129         Visit(OVE->getSourceExpr());
14130     }
14131 
14132     void VisitBinaryOperator(BinaryOperator *BinOp) {
14133       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
14134         return;
14135       Expr *LHS = BinOp->getLHS();
14136       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
14137         if (DRE->getDecl() != Variable)
14138           return;
14139         if (Expr *RHS = BinOp->getRHS()) {
14140           RHS = RHS->IgnoreParenCasts();
14141           llvm::APSInt Value;
14142           VarWillBeReased =
14143             (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
14144         }
14145       }
14146     }
14147   };
14148 
14149 } // namespace
14150 
14151 /// Check whether the given argument is a block which captures a
14152 /// variable.
14153 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
14154   assert(owner.Variable && owner.Loc.isValid());
14155 
14156   e = e->IgnoreParenCasts();
14157 
14158   // Look through [^{...} copy] and Block_copy(^{...}).
14159   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
14160     Selector Cmd = ME->getSelector();
14161     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
14162       e = ME->getInstanceReceiver();
14163       if (!e)
14164         return nullptr;
14165       e = e->IgnoreParenCasts();
14166     }
14167   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
14168     if (CE->getNumArgs() == 1) {
14169       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
14170       if (Fn) {
14171         const IdentifierInfo *FnI = Fn->getIdentifier();
14172         if (FnI && FnI->isStr("_Block_copy")) {
14173           e = CE->getArg(0)->IgnoreParenCasts();
14174         }
14175       }
14176     }
14177   }
14178 
14179   BlockExpr *block = dyn_cast<BlockExpr>(e);
14180   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
14181     return nullptr;
14182 
14183   FindCaptureVisitor visitor(S.Context, owner.Variable);
14184   visitor.Visit(block->getBlockDecl()->getBody());
14185   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
14186 }
14187 
14188 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
14189                                 RetainCycleOwner &owner) {
14190   assert(capturer);
14191   assert(owner.Variable && owner.Loc.isValid());
14192 
14193   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
14194     << owner.Variable << capturer->getSourceRange();
14195   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
14196     << owner.Indirect << owner.Range;
14197 }
14198 
14199 /// Check for a keyword selector that starts with the word 'add' or
14200 /// 'set'.
14201 static bool isSetterLikeSelector(Selector sel) {
14202   if (sel.isUnarySelector()) return false;
14203 
14204   StringRef str = sel.getNameForSlot(0);
14205   while (!str.empty() && str.front() == '_') str = str.substr(1);
14206   if (str.startswith("set"))
14207     str = str.substr(3);
14208   else if (str.startswith("add")) {
14209     // Specially allow 'addOperationWithBlock:'.
14210     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
14211       return false;
14212     str = str.substr(3);
14213   }
14214   else
14215     return false;
14216 
14217   if (str.empty()) return true;
14218   return !isLowercase(str.front());
14219 }
14220 
14221 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
14222                                                     ObjCMessageExpr *Message) {
14223   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
14224                                                 Message->getReceiverInterface(),
14225                                                 NSAPI::ClassId_NSMutableArray);
14226   if (!IsMutableArray) {
14227     return None;
14228   }
14229 
14230   Selector Sel = Message->getSelector();
14231 
14232   Optional<NSAPI::NSArrayMethodKind> MKOpt =
14233     S.NSAPIObj->getNSArrayMethodKind(Sel);
14234   if (!MKOpt) {
14235     return None;
14236   }
14237 
14238   NSAPI::NSArrayMethodKind MK = *MKOpt;
14239 
14240   switch (MK) {
14241     case NSAPI::NSMutableArr_addObject:
14242     case NSAPI::NSMutableArr_insertObjectAtIndex:
14243     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
14244       return 0;
14245     case NSAPI::NSMutableArr_replaceObjectAtIndex:
14246       return 1;
14247 
14248     default:
14249       return None;
14250   }
14251 
14252   return None;
14253 }
14254 
14255 static
14256 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
14257                                                   ObjCMessageExpr *Message) {
14258   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
14259                                             Message->getReceiverInterface(),
14260                                             NSAPI::ClassId_NSMutableDictionary);
14261   if (!IsMutableDictionary) {
14262     return None;
14263   }
14264 
14265   Selector Sel = Message->getSelector();
14266 
14267   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
14268     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
14269   if (!MKOpt) {
14270     return None;
14271   }
14272 
14273   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
14274 
14275   switch (MK) {
14276     case NSAPI::NSMutableDict_setObjectForKey:
14277     case NSAPI::NSMutableDict_setValueForKey:
14278     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
14279       return 0;
14280 
14281     default:
14282       return None;
14283   }
14284 
14285   return None;
14286 }
14287 
14288 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
14289   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
14290                                                 Message->getReceiverInterface(),
14291                                                 NSAPI::ClassId_NSMutableSet);
14292 
14293   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
14294                                             Message->getReceiverInterface(),
14295                                             NSAPI::ClassId_NSMutableOrderedSet);
14296   if (!IsMutableSet && !IsMutableOrderedSet) {
14297     return None;
14298   }
14299 
14300   Selector Sel = Message->getSelector();
14301 
14302   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
14303   if (!MKOpt) {
14304     return None;
14305   }
14306 
14307   NSAPI::NSSetMethodKind MK = *MKOpt;
14308 
14309   switch (MK) {
14310     case NSAPI::NSMutableSet_addObject:
14311     case NSAPI::NSOrderedSet_setObjectAtIndex:
14312     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
14313     case NSAPI::NSOrderedSet_insertObjectAtIndex:
14314       return 0;
14315     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
14316       return 1;
14317   }
14318 
14319   return None;
14320 }
14321 
14322 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
14323   if (!Message->isInstanceMessage()) {
14324     return;
14325   }
14326 
14327   Optional<int> ArgOpt;
14328 
14329   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
14330       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
14331       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
14332     return;
14333   }
14334 
14335   int ArgIndex = *ArgOpt;
14336 
14337   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
14338   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
14339     Arg = OE->getSourceExpr()->IgnoreImpCasts();
14340   }
14341 
14342   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
14343     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
14344       if (ArgRE->isObjCSelfExpr()) {
14345         Diag(Message->getSourceRange().getBegin(),
14346              diag::warn_objc_circular_container)
14347           << ArgRE->getDecl() << StringRef("'super'");
14348       }
14349     }
14350   } else {
14351     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
14352 
14353     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
14354       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
14355     }
14356 
14357     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
14358       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
14359         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
14360           ValueDecl *Decl = ReceiverRE->getDecl();
14361           Diag(Message->getSourceRange().getBegin(),
14362                diag::warn_objc_circular_container)
14363             << Decl << Decl;
14364           if (!ArgRE->isObjCSelfExpr()) {
14365             Diag(Decl->getLocation(),
14366                  diag::note_objc_circular_container_declared_here)
14367               << Decl;
14368           }
14369         }
14370       }
14371     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
14372       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
14373         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
14374           ObjCIvarDecl *Decl = IvarRE->getDecl();
14375           Diag(Message->getSourceRange().getBegin(),
14376                diag::warn_objc_circular_container)
14377             << Decl << Decl;
14378           Diag(Decl->getLocation(),
14379                diag::note_objc_circular_container_declared_here)
14380             << Decl;
14381         }
14382       }
14383     }
14384   }
14385 }
14386 
14387 /// Check a message send to see if it's likely to cause a retain cycle.
14388 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
14389   // Only check instance methods whose selector looks like a setter.
14390   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
14391     return;
14392 
14393   // Try to find a variable that the receiver is strongly owned by.
14394   RetainCycleOwner owner;
14395   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
14396     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
14397       return;
14398   } else {
14399     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
14400     owner.Variable = getCurMethodDecl()->getSelfDecl();
14401     owner.Loc = msg->getSuperLoc();
14402     owner.Range = msg->getSuperLoc();
14403   }
14404 
14405   // Check whether the receiver is captured by any of the arguments.
14406   const ObjCMethodDecl *MD = msg->getMethodDecl();
14407   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
14408     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
14409       // noescape blocks should not be retained by the method.
14410       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
14411         continue;
14412       return diagnoseRetainCycle(*this, capturer, owner);
14413     }
14414   }
14415 }
14416 
14417 /// Check a property assign to see if it's likely to cause a retain cycle.
14418 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
14419   RetainCycleOwner owner;
14420   if (!findRetainCycleOwner(*this, receiver, owner))
14421     return;
14422 
14423   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
14424     diagnoseRetainCycle(*this, capturer, owner);
14425 }
14426 
14427 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
14428   RetainCycleOwner Owner;
14429   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
14430     return;
14431 
14432   // Because we don't have an expression for the variable, we have to set the
14433   // location explicitly here.
14434   Owner.Loc = Var->getLocation();
14435   Owner.Range = Var->getSourceRange();
14436 
14437   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
14438     diagnoseRetainCycle(*this, Capturer, Owner);
14439 }
14440 
14441 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
14442                                      Expr *RHS, bool isProperty) {
14443   // Check if RHS is an Objective-C object literal, which also can get
14444   // immediately zapped in a weak reference.  Note that we explicitly
14445   // allow ObjCStringLiterals, since those are designed to never really die.
14446   RHS = RHS->IgnoreParenImpCasts();
14447 
14448   // This enum needs to match with the 'select' in
14449   // warn_objc_arc_literal_assign (off-by-1).
14450   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
14451   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
14452     return false;
14453 
14454   S.Diag(Loc, diag::warn_arc_literal_assign)
14455     << (unsigned) Kind
14456     << (isProperty ? 0 : 1)
14457     << RHS->getSourceRange();
14458 
14459   return true;
14460 }
14461 
14462 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
14463                                     Qualifiers::ObjCLifetime LT,
14464                                     Expr *RHS, bool isProperty) {
14465   // Strip off any implicit cast added to get to the one ARC-specific.
14466   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
14467     if (cast->getCastKind() == CK_ARCConsumeObject) {
14468       S.Diag(Loc, diag::warn_arc_retained_assign)
14469         << (LT == Qualifiers::OCL_ExplicitNone)
14470         << (isProperty ? 0 : 1)
14471         << RHS->getSourceRange();
14472       return true;
14473     }
14474     RHS = cast->getSubExpr();
14475   }
14476 
14477   if (LT == Qualifiers::OCL_Weak &&
14478       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
14479     return true;
14480 
14481   return false;
14482 }
14483 
14484 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
14485                               QualType LHS, Expr *RHS) {
14486   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
14487 
14488   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
14489     return false;
14490 
14491   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
14492     return true;
14493 
14494   return false;
14495 }
14496 
14497 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
14498                               Expr *LHS, Expr *RHS) {
14499   QualType LHSType;
14500   // PropertyRef on LHS type need be directly obtained from
14501   // its declaration as it has a PseudoType.
14502   ObjCPropertyRefExpr *PRE
14503     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
14504   if (PRE && !PRE->isImplicitProperty()) {
14505     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
14506     if (PD)
14507       LHSType = PD->getType();
14508   }
14509 
14510   if (LHSType.isNull())
14511     LHSType = LHS->getType();
14512 
14513   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
14514 
14515   if (LT == Qualifiers::OCL_Weak) {
14516     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
14517       getCurFunction()->markSafeWeakUse(LHS);
14518   }
14519 
14520   if (checkUnsafeAssigns(Loc, LHSType, RHS))
14521     return;
14522 
14523   // FIXME. Check for other life times.
14524   if (LT != Qualifiers::OCL_None)
14525     return;
14526 
14527   if (PRE) {
14528     if (PRE->isImplicitProperty())
14529       return;
14530     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
14531     if (!PD)
14532       return;
14533 
14534     unsigned Attributes = PD->getPropertyAttributes();
14535     if (Attributes & ObjCPropertyAttribute::kind_assign) {
14536       // when 'assign' attribute was not explicitly specified
14537       // by user, ignore it and rely on property type itself
14538       // for lifetime info.
14539       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
14540       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
14541           LHSType->isObjCRetainableType())
14542         return;
14543 
14544       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
14545         if (cast->getCastKind() == CK_ARCConsumeObject) {
14546           Diag(Loc, diag::warn_arc_retained_property_assign)
14547           << RHS->getSourceRange();
14548           return;
14549         }
14550         RHS = cast->getSubExpr();
14551       }
14552     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
14553       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
14554         return;
14555     }
14556   }
14557 }
14558 
14559 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
14560 
14561 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
14562                                         SourceLocation StmtLoc,
14563                                         const NullStmt *Body) {
14564   // Do not warn if the body is a macro that expands to nothing, e.g:
14565   //
14566   // #define CALL(x)
14567   // if (condition)
14568   //   CALL(0);
14569   if (Body->hasLeadingEmptyMacro())
14570     return false;
14571 
14572   // Get line numbers of statement and body.
14573   bool StmtLineInvalid;
14574   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
14575                                                       &StmtLineInvalid);
14576   if (StmtLineInvalid)
14577     return false;
14578 
14579   bool BodyLineInvalid;
14580   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
14581                                                       &BodyLineInvalid);
14582   if (BodyLineInvalid)
14583     return false;
14584 
14585   // Warn if null statement and body are on the same line.
14586   if (StmtLine != BodyLine)
14587     return false;
14588 
14589   return true;
14590 }
14591 
14592 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
14593                                  const Stmt *Body,
14594                                  unsigned DiagID) {
14595   // Since this is a syntactic check, don't emit diagnostic for template
14596   // instantiations, this just adds noise.
14597   if (CurrentInstantiationScope)
14598     return;
14599 
14600   // The body should be a null statement.
14601   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
14602   if (!NBody)
14603     return;
14604 
14605   // Do the usual checks.
14606   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
14607     return;
14608 
14609   Diag(NBody->getSemiLoc(), DiagID);
14610   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
14611 }
14612 
14613 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
14614                                  const Stmt *PossibleBody) {
14615   assert(!CurrentInstantiationScope); // Ensured by caller
14616 
14617   SourceLocation StmtLoc;
14618   const Stmt *Body;
14619   unsigned DiagID;
14620   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
14621     StmtLoc = FS->getRParenLoc();
14622     Body = FS->getBody();
14623     DiagID = diag::warn_empty_for_body;
14624   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
14625     StmtLoc = WS->getCond()->getSourceRange().getEnd();
14626     Body = WS->getBody();
14627     DiagID = diag::warn_empty_while_body;
14628   } else
14629     return; // Neither `for' nor `while'.
14630 
14631   // The body should be a null statement.
14632   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
14633   if (!NBody)
14634     return;
14635 
14636   // Skip expensive checks if diagnostic is disabled.
14637   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
14638     return;
14639 
14640   // Do the usual checks.
14641   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
14642     return;
14643 
14644   // `for(...);' and `while(...);' are popular idioms, so in order to keep
14645   // noise level low, emit diagnostics only if for/while is followed by a
14646   // CompoundStmt, e.g.:
14647   //    for (int i = 0; i < n; i++);
14648   //    {
14649   //      a(i);
14650   //    }
14651   // or if for/while is followed by a statement with more indentation
14652   // than for/while itself:
14653   //    for (int i = 0; i < n; i++);
14654   //      a(i);
14655   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
14656   if (!ProbableTypo) {
14657     bool BodyColInvalid;
14658     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
14659         PossibleBody->getBeginLoc(), &BodyColInvalid);
14660     if (BodyColInvalid)
14661       return;
14662 
14663     bool StmtColInvalid;
14664     unsigned StmtCol =
14665         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
14666     if (StmtColInvalid)
14667       return;
14668 
14669     if (BodyCol > StmtCol)
14670       ProbableTypo = true;
14671   }
14672 
14673   if (ProbableTypo) {
14674     Diag(NBody->getSemiLoc(), DiagID);
14675     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
14676   }
14677 }
14678 
14679 //===--- CHECK: Warn on self move with std::move. -------------------------===//
14680 
14681 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
14682 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
14683                              SourceLocation OpLoc) {
14684   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
14685     return;
14686 
14687   if (inTemplateInstantiation())
14688     return;
14689 
14690   // Strip parens and casts away.
14691   LHSExpr = LHSExpr->IgnoreParenImpCasts();
14692   RHSExpr = RHSExpr->IgnoreParenImpCasts();
14693 
14694   // Check for a call expression
14695   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
14696   if (!CE || CE->getNumArgs() != 1)
14697     return;
14698 
14699   // Check for a call to std::move
14700   if (!CE->isCallToStdMove())
14701     return;
14702 
14703   // Get argument from std::move
14704   RHSExpr = CE->getArg(0);
14705 
14706   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
14707   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
14708 
14709   // Two DeclRefExpr's, check that the decls are the same.
14710   if (LHSDeclRef && RHSDeclRef) {
14711     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
14712       return;
14713     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
14714         RHSDeclRef->getDecl()->getCanonicalDecl())
14715       return;
14716 
14717     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14718                                         << LHSExpr->getSourceRange()
14719                                         << RHSExpr->getSourceRange();
14720     return;
14721   }
14722 
14723   // Member variables require a different approach to check for self moves.
14724   // MemberExpr's are the same if every nested MemberExpr refers to the same
14725   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
14726   // the base Expr's are CXXThisExpr's.
14727   const Expr *LHSBase = LHSExpr;
14728   const Expr *RHSBase = RHSExpr;
14729   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
14730   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
14731   if (!LHSME || !RHSME)
14732     return;
14733 
14734   while (LHSME && RHSME) {
14735     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
14736         RHSME->getMemberDecl()->getCanonicalDecl())
14737       return;
14738 
14739     LHSBase = LHSME->getBase();
14740     RHSBase = RHSME->getBase();
14741     LHSME = dyn_cast<MemberExpr>(LHSBase);
14742     RHSME = dyn_cast<MemberExpr>(RHSBase);
14743   }
14744 
14745   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
14746   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
14747   if (LHSDeclRef && RHSDeclRef) {
14748     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
14749       return;
14750     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
14751         RHSDeclRef->getDecl()->getCanonicalDecl())
14752       return;
14753 
14754     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14755                                         << LHSExpr->getSourceRange()
14756                                         << RHSExpr->getSourceRange();
14757     return;
14758   }
14759 
14760   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
14761     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14762                                         << LHSExpr->getSourceRange()
14763                                         << RHSExpr->getSourceRange();
14764 }
14765 
14766 //===--- Layout compatibility ----------------------------------------------//
14767 
14768 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
14769 
14770 /// Check if two enumeration types are layout-compatible.
14771 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
14772   // C++11 [dcl.enum] p8:
14773   // Two enumeration types are layout-compatible if they have the same
14774   // underlying type.
14775   return ED1->isComplete() && ED2->isComplete() &&
14776          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
14777 }
14778 
14779 /// Check if two fields are layout-compatible.
14780 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
14781                                FieldDecl *Field2) {
14782   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
14783     return false;
14784 
14785   if (Field1->isBitField() != Field2->isBitField())
14786     return false;
14787 
14788   if (Field1->isBitField()) {
14789     // Make sure that the bit-fields are the same length.
14790     unsigned Bits1 = Field1->getBitWidthValue(C);
14791     unsigned Bits2 = Field2->getBitWidthValue(C);
14792 
14793     if (Bits1 != Bits2)
14794       return false;
14795   }
14796 
14797   return true;
14798 }
14799 
14800 /// Check if two standard-layout structs are layout-compatible.
14801 /// (C++11 [class.mem] p17)
14802 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
14803                                      RecordDecl *RD2) {
14804   // If both records are C++ classes, check that base classes match.
14805   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
14806     // If one of records is a CXXRecordDecl we are in C++ mode,
14807     // thus the other one is a CXXRecordDecl, too.
14808     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
14809     // Check number of base classes.
14810     if (D1CXX->getNumBases() != D2CXX->getNumBases())
14811       return false;
14812 
14813     // Check the base classes.
14814     for (CXXRecordDecl::base_class_const_iterator
14815                Base1 = D1CXX->bases_begin(),
14816            BaseEnd1 = D1CXX->bases_end(),
14817               Base2 = D2CXX->bases_begin();
14818          Base1 != BaseEnd1;
14819          ++Base1, ++Base2) {
14820       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
14821         return false;
14822     }
14823   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
14824     // If only RD2 is a C++ class, it should have zero base classes.
14825     if (D2CXX->getNumBases() > 0)
14826       return false;
14827   }
14828 
14829   // Check the fields.
14830   RecordDecl::field_iterator Field2 = RD2->field_begin(),
14831                              Field2End = RD2->field_end(),
14832                              Field1 = RD1->field_begin(),
14833                              Field1End = RD1->field_end();
14834   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
14835     if (!isLayoutCompatible(C, *Field1, *Field2))
14836       return false;
14837   }
14838   if (Field1 != Field1End || Field2 != Field2End)
14839     return false;
14840 
14841   return true;
14842 }
14843 
14844 /// Check if two standard-layout unions are layout-compatible.
14845 /// (C++11 [class.mem] p18)
14846 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
14847                                     RecordDecl *RD2) {
14848   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
14849   for (auto *Field2 : RD2->fields())
14850     UnmatchedFields.insert(Field2);
14851 
14852   for (auto *Field1 : RD1->fields()) {
14853     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
14854         I = UnmatchedFields.begin(),
14855         E = UnmatchedFields.end();
14856 
14857     for ( ; I != E; ++I) {
14858       if (isLayoutCompatible(C, Field1, *I)) {
14859         bool Result = UnmatchedFields.erase(*I);
14860         (void) Result;
14861         assert(Result);
14862         break;
14863       }
14864     }
14865     if (I == E)
14866       return false;
14867   }
14868 
14869   return UnmatchedFields.empty();
14870 }
14871 
14872 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
14873                                RecordDecl *RD2) {
14874   if (RD1->isUnion() != RD2->isUnion())
14875     return false;
14876 
14877   if (RD1->isUnion())
14878     return isLayoutCompatibleUnion(C, RD1, RD2);
14879   else
14880     return isLayoutCompatibleStruct(C, RD1, RD2);
14881 }
14882 
14883 /// Check if two types are layout-compatible in C++11 sense.
14884 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
14885   if (T1.isNull() || T2.isNull())
14886     return false;
14887 
14888   // C++11 [basic.types] p11:
14889   // If two types T1 and T2 are the same type, then T1 and T2 are
14890   // layout-compatible types.
14891   if (C.hasSameType(T1, T2))
14892     return true;
14893 
14894   T1 = T1.getCanonicalType().getUnqualifiedType();
14895   T2 = T2.getCanonicalType().getUnqualifiedType();
14896 
14897   const Type::TypeClass TC1 = T1->getTypeClass();
14898   const Type::TypeClass TC2 = T2->getTypeClass();
14899 
14900   if (TC1 != TC2)
14901     return false;
14902 
14903   if (TC1 == Type::Enum) {
14904     return isLayoutCompatible(C,
14905                               cast<EnumType>(T1)->getDecl(),
14906                               cast<EnumType>(T2)->getDecl());
14907   } else if (TC1 == Type::Record) {
14908     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
14909       return false;
14910 
14911     return isLayoutCompatible(C,
14912                               cast<RecordType>(T1)->getDecl(),
14913                               cast<RecordType>(T2)->getDecl());
14914   }
14915 
14916   return false;
14917 }
14918 
14919 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
14920 
14921 /// Given a type tag expression find the type tag itself.
14922 ///
14923 /// \param TypeExpr Type tag expression, as it appears in user's code.
14924 ///
14925 /// \param VD Declaration of an identifier that appears in a type tag.
14926 ///
14927 /// \param MagicValue Type tag magic value.
14928 ///
14929 /// \param isConstantEvaluated wether the evalaution should be performed in
14930 
14931 /// constant context.
14932 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
14933                             const ValueDecl **VD, uint64_t *MagicValue,
14934                             bool isConstantEvaluated) {
14935   while(true) {
14936     if (!TypeExpr)
14937       return false;
14938 
14939     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
14940 
14941     switch (TypeExpr->getStmtClass()) {
14942     case Stmt::UnaryOperatorClass: {
14943       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
14944       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
14945         TypeExpr = UO->getSubExpr();
14946         continue;
14947       }
14948       return false;
14949     }
14950 
14951     case Stmt::DeclRefExprClass: {
14952       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
14953       *VD = DRE->getDecl();
14954       return true;
14955     }
14956 
14957     case Stmt::IntegerLiteralClass: {
14958       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
14959       llvm::APInt MagicValueAPInt = IL->getValue();
14960       if (MagicValueAPInt.getActiveBits() <= 64) {
14961         *MagicValue = MagicValueAPInt.getZExtValue();
14962         return true;
14963       } else
14964         return false;
14965     }
14966 
14967     case Stmt::BinaryConditionalOperatorClass:
14968     case Stmt::ConditionalOperatorClass: {
14969       const AbstractConditionalOperator *ACO =
14970           cast<AbstractConditionalOperator>(TypeExpr);
14971       bool Result;
14972       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
14973                                                      isConstantEvaluated)) {
14974         if (Result)
14975           TypeExpr = ACO->getTrueExpr();
14976         else
14977           TypeExpr = ACO->getFalseExpr();
14978         continue;
14979       }
14980       return false;
14981     }
14982 
14983     case Stmt::BinaryOperatorClass: {
14984       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
14985       if (BO->getOpcode() == BO_Comma) {
14986         TypeExpr = BO->getRHS();
14987         continue;
14988       }
14989       return false;
14990     }
14991 
14992     default:
14993       return false;
14994     }
14995   }
14996 }
14997 
14998 /// Retrieve the C type corresponding to type tag TypeExpr.
14999 ///
15000 /// \param TypeExpr Expression that specifies a type tag.
15001 ///
15002 /// \param MagicValues Registered magic values.
15003 ///
15004 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
15005 ///        kind.
15006 ///
15007 /// \param TypeInfo Information about the corresponding C type.
15008 ///
15009 /// \param isConstantEvaluated wether the evalaution should be performed in
15010 /// constant context.
15011 ///
15012 /// \returns true if the corresponding C type was found.
15013 static bool GetMatchingCType(
15014     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
15015     const ASTContext &Ctx,
15016     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
15017         *MagicValues,
15018     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
15019     bool isConstantEvaluated) {
15020   FoundWrongKind = false;
15021 
15022   // Variable declaration that has type_tag_for_datatype attribute.
15023   const ValueDecl *VD = nullptr;
15024 
15025   uint64_t MagicValue;
15026 
15027   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
15028     return false;
15029 
15030   if (VD) {
15031     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
15032       if (I->getArgumentKind() != ArgumentKind) {
15033         FoundWrongKind = true;
15034         return false;
15035       }
15036       TypeInfo.Type = I->getMatchingCType();
15037       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
15038       TypeInfo.MustBeNull = I->getMustBeNull();
15039       return true;
15040     }
15041     return false;
15042   }
15043 
15044   if (!MagicValues)
15045     return false;
15046 
15047   llvm::DenseMap<Sema::TypeTagMagicValue,
15048                  Sema::TypeTagData>::const_iterator I =
15049       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
15050   if (I == MagicValues->end())
15051     return false;
15052 
15053   TypeInfo = I->second;
15054   return true;
15055 }
15056 
15057 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
15058                                       uint64_t MagicValue, QualType Type,
15059                                       bool LayoutCompatible,
15060                                       bool MustBeNull) {
15061   if (!TypeTagForDatatypeMagicValues)
15062     TypeTagForDatatypeMagicValues.reset(
15063         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
15064 
15065   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
15066   (*TypeTagForDatatypeMagicValues)[Magic] =
15067       TypeTagData(Type, LayoutCompatible, MustBeNull);
15068 }
15069 
15070 static bool IsSameCharType(QualType T1, QualType T2) {
15071   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
15072   if (!BT1)
15073     return false;
15074 
15075   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
15076   if (!BT2)
15077     return false;
15078 
15079   BuiltinType::Kind T1Kind = BT1->getKind();
15080   BuiltinType::Kind T2Kind = BT2->getKind();
15081 
15082   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
15083          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
15084          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
15085          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
15086 }
15087 
15088 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
15089                                     const ArrayRef<const Expr *> ExprArgs,
15090                                     SourceLocation CallSiteLoc) {
15091   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
15092   bool IsPointerAttr = Attr->getIsPointer();
15093 
15094   // Retrieve the argument representing the 'type_tag'.
15095   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
15096   if (TypeTagIdxAST >= ExprArgs.size()) {
15097     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
15098         << 0 << Attr->getTypeTagIdx().getSourceIndex();
15099     return;
15100   }
15101   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
15102   bool FoundWrongKind;
15103   TypeTagData TypeInfo;
15104   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
15105                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
15106                         TypeInfo, isConstantEvaluated())) {
15107     if (FoundWrongKind)
15108       Diag(TypeTagExpr->getExprLoc(),
15109            diag::warn_type_tag_for_datatype_wrong_kind)
15110         << TypeTagExpr->getSourceRange();
15111     return;
15112   }
15113 
15114   // Retrieve the argument representing the 'arg_idx'.
15115   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
15116   if (ArgumentIdxAST >= ExprArgs.size()) {
15117     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
15118         << 1 << Attr->getArgumentIdx().getSourceIndex();
15119     return;
15120   }
15121   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
15122   if (IsPointerAttr) {
15123     // Skip implicit cast of pointer to `void *' (as a function argument).
15124     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
15125       if (ICE->getType()->isVoidPointerType() &&
15126           ICE->getCastKind() == CK_BitCast)
15127         ArgumentExpr = ICE->getSubExpr();
15128   }
15129   QualType ArgumentType = ArgumentExpr->getType();
15130 
15131   // Passing a `void*' pointer shouldn't trigger a warning.
15132   if (IsPointerAttr && ArgumentType->isVoidPointerType())
15133     return;
15134 
15135   if (TypeInfo.MustBeNull) {
15136     // Type tag with matching void type requires a null pointer.
15137     if (!ArgumentExpr->isNullPointerConstant(Context,
15138                                              Expr::NPC_ValueDependentIsNotNull)) {
15139       Diag(ArgumentExpr->getExprLoc(),
15140            diag::warn_type_safety_null_pointer_required)
15141           << ArgumentKind->getName()
15142           << ArgumentExpr->getSourceRange()
15143           << TypeTagExpr->getSourceRange();
15144     }
15145     return;
15146   }
15147 
15148   QualType RequiredType = TypeInfo.Type;
15149   if (IsPointerAttr)
15150     RequiredType = Context.getPointerType(RequiredType);
15151 
15152   bool mismatch = false;
15153   if (!TypeInfo.LayoutCompatible) {
15154     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
15155 
15156     // C++11 [basic.fundamental] p1:
15157     // Plain char, signed char, and unsigned char are three distinct types.
15158     //
15159     // But we treat plain `char' as equivalent to `signed char' or `unsigned
15160     // char' depending on the current char signedness mode.
15161     if (mismatch)
15162       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
15163                                            RequiredType->getPointeeType())) ||
15164           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
15165         mismatch = false;
15166   } else
15167     if (IsPointerAttr)
15168       mismatch = !isLayoutCompatible(Context,
15169                                      ArgumentType->getPointeeType(),
15170                                      RequiredType->getPointeeType());
15171     else
15172       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
15173 
15174   if (mismatch)
15175     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
15176         << ArgumentType << ArgumentKind
15177         << TypeInfo.LayoutCompatible << RequiredType
15178         << ArgumentExpr->getSourceRange()
15179         << TypeTagExpr->getSourceRange();
15180 }
15181 
15182 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
15183                                          CharUnits Alignment) {
15184   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
15185 }
15186 
15187 void Sema::DiagnoseMisalignedMembers() {
15188   for (MisalignedMember &m : MisalignedMembers) {
15189     const NamedDecl *ND = m.RD;
15190     if (ND->getName().empty()) {
15191       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
15192         ND = TD;
15193     }
15194     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
15195         << m.MD << ND << m.E->getSourceRange();
15196   }
15197   MisalignedMembers.clear();
15198 }
15199 
15200 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
15201   E = E->IgnoreParens();
15202   if (!T->isPointerType() && !T->isIntegerType())
15203     return;
15204   if (isa<UnaryOperator>(E) &&
15205       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
15206     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
15207     if (isa<MemberExpr>(Op)) {
15208       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
15209       if (MA != MisalignedMembers.end() &&
15210           (T->isIntegerType() ||
15211            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
15212                                    Context.getTypeAlignInChars(
15213                                        T->getPointeeType()) <= MA->Alignment))))
15214         MisalignedMembers.erase(MA);
15215     }
15216   }
15217 }
15218 
15219 void Sema::RefersToMemberWithReducedAlignment(
15220     Expr *E,
15221     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
15222         Action) {
15223   const auto *ME = dyn_cast<MemberExpr>(E);
15224   if (!ME)
15225     return;
15226 
15227   // No need to check expressions with an __unaligned-qualified type.
15228   if (E->getType().getQualifiers().hasUnaligned())
15229     return;
15230 
15231   // For a chain of MemberExpr like "a.b.c.d" this list
15232   // will keep FieldDecl's like [d, c, b].
15233   SmallVector<FieldDecl *, 4> ReverseMemberChain;
15234   const MemberExpr *TopME = nullptr;
15235   bool AnyIsPacked = false;
15236   do {
15237     QualType BaseType = ME->getBase()->getType();
15238     if (BaseType->isDependentType())
15239       return;
15240     if (ME->isArrow())
15241       BaseType = BaseType->getPointeeType();
15242     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
15243     if (RD->isInvalidDecl())
15244       return;
15245 
15246     ValueDecl *MD = ME->getMemberDecl();
15247     auto *FD = dyn_cast<FieldDecl>(MD);
15248     // We do not care about non-data members.
15249     if (!FD || FD->isInvalidDecl())
15250       return;
15251 
15252     AnyIsPacked =
15253         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
15254     ReverseMemberChain.push_back(FD);
15255 
15256     TopME = ME;
15257     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
15258   } while (ME);
15259   assert(TopME && "We did not compute a topmost MemberExpr!");
15260 
15261   // Not the scope of this diagnostic.
15262   if (!AnyIsPacked)
15263     return;
15264 
15265   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
15266   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
15267   // TODO: The innermost base of the member expression may be too complicated.
15268   // For now, just disregard these cases. This is left for future
15269   // improvement.
15270   if (!DRE && !isa<CXXThisExpr>(TopBase))
15271       return;
15272 
15273   // Alignment expected by the whole expression.
15274   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
15275 
15276   // No need to do anything else with this case.
15277   if (ExpectedAlignment.isOne())
15278     return;
15279 
15280   // Synthesize offset of the whole access.
15281   CharUnits Offset;
15282   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
15283        I++) {
15284     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
15285   }
15286 
15287   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
15288   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
15289       ReverseMemberChain.back()->getParent()->getTypeForDecl());
15290 
15291   // The base expression of the innermost MemberExpr may give
15292   // stronger guarantees than the class containing the member.
15293   if (DRE && !TopME->isArrow()) {
15294     const ValueDecl *VD = DRE->getDecl();
15295     if (!VD->getType()->isReferenceType())
15296       CompleteObjectAlignment =
15297           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
15298   }
15299 
15300   // Check if the synthesized offset fulfills the alignment.
15301   if (Offset % ExpectedAlignment != 0 ||
15302       // It may fulfill the offset it but the effective alignment may still be
15303       // lower than the expected expression alignment.
15304       CompleteObjectAlignment < ExpectedAlignment) {
15305     // If this happens, we want to determine a sensible culprit of this.
15306     // Intuitively, watching the chain of member expressions from right to
15307     // left, we start with the required alignment (as required by the field
15308     // type) but some packed attribute in that chain has reduced the alignment.
15309     // It may happen that another packed structure increases it again. But if
15310     // we are here such increase has not been enough. So pointing the first
15311     // FieldDecl that either is packed or else its RecordDecl is,
15312     // seems reasonable.
15313     FieldDecl *FD = nullptr;
15314     CharUnits Alignment;
15315     for (FieldDecl *FDI : ReverseMemberChain) {
15316       if (FDI->hasAttr<PackedAttr>() ||
15317           FDI->getParent()->hasAttr<PackedAttr>()) {
15318         FD = FDI;
15319         Alignment = std::min(
15320             Context.getTypeAlignInChars(FD->getType()),
15321             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
15322         break;
15323       }
15324     }
15325     assert(FD && "We did not find a packed FieldDecl!");
15326     Action(E, FD->getParent(), FD, Alignment);
15327   }
15328 }
15329 
15330 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
15331   using namespace std::placeholders;
15332 
15333   RefersToMemberWithReducedAlignment(
15334       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
15335                      _2, _3, _4));
15336 }
15337 
15338 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
15339                                             ExprResult CallResult) {
15340   if (checkArgCount(*this, TheCall, 1))
15341     return ExprError();
15342 
15343   ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
15344   if (MatrixArg.isInvalid())
15345     return MatrixArg;
15346   Expr *Matrix = MatrixArg.get();
15347 
15348   auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
15349   if (!MType) {
15350     Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg);
15351     return ExprError();
15352   }
15353 
15354   // Create returned matrix type by swapping rows and columns of the argument
15355   // matrix type.
15356   QualType ResultType = Context.getConstantMatrixType(
15357       MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
15358 
15359   // Change the return type to the type of the returned matrix.
15360   TheCall->setType(ResultType);
15361 
15362   // Update call argument to use the possibly converted matrix argument.
15363   TheCall->setArg(0, Matrix);
15364   return CallResult;
15365 }
15366 
15367 // Get and verify the matrix dimensions.
15368 static llvm::Optional<unsigned>
15369 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
15370   llvm::APSInt Value(64);
15371   SourceLocation ErrorPos;
15372   if (!Expr->isIntegerConstantExpr(Value, S.Context, &ErrorPos)) {
15373     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
15374         << Name;
15375     return {};
15376   }
15377   uint64_t Dim = Value.getZExtValue();
15378   if (!ConstantMatrixType::isDimensionValid(Dim)) {
15379     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
15380         << Name << ConstantMatrixType::getMaxElementsPerDimension();
15381     return {};
15382   }
15383   return Dim;
15384 }
15385 
15386 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
15387                                                   ExprResult CallResult) {
15388   if (!getLangOpts().MatrixTypes) {
15389     Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
15390     return ExprError();
15391   }
15392 
15393   if (checkArgCount(*this, TheCall, 4))
15394     return ExprError();
15395 
15396   unsigned PtrArgIdx = 0;
15397   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
15398   Expr *RowsExpr = TheCall->getArg(1);
15399   Expr *ColumnsExpr = TheCall->getArg(2);
15400   Expr *StrideExpr = TheCall->getArg(3);
15401 
15402   bool ArgError = false;
15403 
15404   // Check pointer argument.
15405   {
15406     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
15407     if (PtrConv.isInvalid())
15408       return PtrConv;
15409     PtrExpr = PtrConv.get();
15410     TheCall->setArg(0, PtrExpr);
15411     if (PtrExpr->isTypeDependent()) {
15412       TheCall->setType(Context.DependentTy);
15413       return TheCall;
15414     }
15415   }
15416 
15417   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
15418   QualType ElementTy;
15419   if (!PtrTy) {
15420     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
15421         << PtrArgIdx + 1;
15422     ArgError = true;
15423   } else {
15424     ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
15425 
15426     if (!ConstantMatrixType::isValidElementType(ElementTy)) {
15427       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
15428           << PtrArgIdx + 1;
15429       ArgError = true;
15430     }
15431   }
15432 
15433   // Apply default Lvalue conversions and convert the expression to size_t.
15434   auto ApplyArgumentConversions = [this](Expr *E) {
15435     ExprResult Conv = DefaultLvalueConversion(E);
15436     if (Conv.isInvalid())
15437       return Conv;
15438 
15439     return tryConvertExprToType(Conv.get(), Context.getSizeType());
15440   };
15441 
15442   // Apply conversion to row and column expressions.
15443   ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
15444   if (!RowsConv.isInvalid()) {
15445     RowsExpr = RowsConv.get();
15446     TheCall->setArg(1, RowsExpr);
15447   } else
15448     RowsExpr = nullptr;
15449 
15450   ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
15451   if (!ColumnsConv.isInvalid()) {
15452     ColumnsExpr = ColumnsConv.get();
15453     TheCall->setArg(2, ColumnsExpr);
15454   } else
15455     ColumnsExpr = nullptr;
15456 
15457   // If any any part of the result matrix type is still pending, just use
15458   // Context.DependentTy, until all parts are resolved.
15459   if ((RowsExpr && RowsExpr->isTypeDependent()) ||
15460       (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
15461     TheCall->setType(Context.DependentTy);
15462     return CallResult;
15463   }
15464 
15465   // Check row and column dimenions.
15466   llvm::Optional<unsigned> MaybeRows;
15467   if (RowsExpr)
15468     MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
15469 
15470   llvm::Optional<unsigned> MaybeColumns;
15471   if (ColumnsExpr)
15472     MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
15473 
15474   // Check stride argument.
15475   ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
15476   if (StrideConv.isInvalid())
15477     return ExprError();
15478   StrideExpr = StrideConv.get();
15479   TheCall->setArg(3, StrideExpr);
15480 
15481   llvm::APSInt Value(64);
15482   if (MaybeRows && StrideExpr->isIntegerConstantExpr(Value, Context)) {
15483     uint64_t Stride = Value.getZExtValue();
15484     if (Stride < *MaybeRows) {
15485       Diag(StrideExpr->getBeginLoc(),
15486            diag::err_builtin_matrix_stride_too_small);
15487       ArgError = true;
15488     }
15489   }
15490 
15491   if (ArgError || !MaybeRows || !MaybeColumns)
15492     return ExprError();
15493 
15494   TheCall->setType(
15495       Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
15496   return CallResult;
15497 }
15498 
15499 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
15500                                                    ExprResult CallResult) {
15501   if (checkArgCount(*this, TheCall, 3))
15502     return ExprError();
15503 
15504   unsigned PtrArgIdx = 1;
15505   Expr *MatrixExpr = TheCall->getArg(0);
15506   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
15507   Expr *StrideExpr = TheCall->getArg(2);
15508 
15509   bool ArgError = false;
15510 
15511   {
15512     ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
15513     if (MatrixConv.isInvalid())
15514       return MatrixConv;
15515     MatrixExpr = MatrixConv.get();
15516     TheCall->setArg(0, MatrixExpr);
15517   }
15518   if (MatrixExpr->isTypeDependent()) {
15519     TheCall->setType(Context.DependentTy);
15520     return TheCall;
15521   }
15522 
15523   auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
15524   if (!MatrixTy) {
15525     Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0;
15526     ArgError = true;
15527   }
15528 
15529   {
15530     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
15531     if (PtrConv.isInvalid())
15532       return PtrConv;
15533     PtrExpr = PtrConv.get();
15534     TheCall->setArg(1, PtrExpr);
15535     if (PtrExpr->isTypeDependent()) {
15536       TheCall->setType(Context.DependentTy);
15537       return TheCall;
15538     }
15539   }
15540 
15541   // Check pointer argument.
15542   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
15543   if (!PtrTy) {
15544     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
15545         << PtrArgIdx + 1;
15546     ArgError = true;
15547   } else {
15548     QualType ElementTy = PtrTy->getPointeeType();
15549     if (ElementTy.isConstQualified()) {
15550       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
15551       ArgError = true;
15552     }
15553     ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
15554     if (MatrixTy &&
15555         !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
15556       Diag(PtrExpr->getBeginLoc(),
15557            diag::err_builtin_matrix_pointer_arg_mismatch)
15558           << ElementTy << MatrixTy->getElementType();
15559       ArgError = true;
15560     }
15561   }
15562 
15563   // Apply default Lvalue conversions and convert the stride expression to
15564   // size_t.
15565   {
15566     ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
15567     if (StrideConv.isInvalid())
15568       return StrideConv;
15569 
15570     StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
15571     if (StrideConv.isInvalid())
15572       return StrideConv;
15573     StrideExpr = StrideConv.get();
15574     TheCall->setArg(2, StrideExpr);
15575   }
15576 
15577   // Check stride argument.
15578   llvm::APSInt Value(64);
15579   if (MatrixTy && StrideExpr->isIntegerConstantExpr(Value, Context)) {
15580     uint64_t Stride = Value.getZExtValue();
15581     if (Stride < MatrixTy->getNumRows()) {
15582       Diag(StrideExpr->getBeginLoc(),
15583            diag::err_builtin_matrix_stride_too_small);
15584       ArgError = true;
15585     }
15586   }
15587 
15588   if (ArgError)
15589     return ExprError();
15590 
15591   return CallResult;
15592 }
15593