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/Stmt.h"
34 #include "clang/AST/TemplateBase.h"
35 #include "clang/AST/Type.h"
36 #include "clang/AST/TypeLoc.h"
37 #include "clang/AST/UnresolvedSet.h"
38 #include "clang/Basic/AddressSpaces.h"
39 #include "clang/Basic/CharInfo.h"
40 #include "clang/Basic/Diagnostic.h"
41 #include "clang/Basic/IdentifierTable.h"
42 #include "clang/Basic/LLVM.h"
43 #include "clang/Basic/LangOptions.h"
44 #include "clang/Basic/OpenCLOptions.h"
45 #include "clang/Basic/OperatorKinds.h"
46 #include "clang/Basic/PartialDiagnostic.h"
47 #include "clang/Basic/SourceLocation.h"
48 #include "clang/Basic/SourceManager.h"
49 #include "clang/Basic/Specifiers.h"
50 #include "clang/Basic/SyncScope.h"
51 #include "clang/Basic/TargetBuiltins.h"
52 #include "clang/Basic/TargetCXXABI.h"
53 #include "clang/Basic/TargetInfo.h"
54 #include "clang/Basic/TypeTraits.h"
55 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
56 #include "clang/Sema/Initialization.h"
57 #include "clang/Sema/Lookup.h"
58 #include "clang/Sema/Ownership.h"
59 #include "clang/Sema/Scope.h"
60 #include "clang/Sema/ScopeInfo.h"
61 #include "clang/Sema/Sema.h"
62 #include "clang/Sema/SemaInternal.h"
63 #include "llvm/ADT/APFloat.h"
64 #include "llvm/ADT/APInt.h"
65 #include "llvm/ADT/APSInt.h"
66 #include "llvm/ADT/ArrayRef.h"
67 #include "llvm/ADT/DenseMap.h"
68 #include "llvm/ADT/FoldingSet.h"
69 #include "llvm/ADT/None.h"
70 #include "llvm/ADT/Optional.h"
71 #include "llvm/ADT/STLExtras.h"
72 #include "llvm/ADT/SmallBitVector.h"
73 #include "llvm/ADT/SmallPtrSet.h"
74 #include "llvm/ADT/SmallString.h"
75 #include "llvm/ADT/SmallVector.h"
76 #include "llvm/ADT/StringRef.h"
77 #include "llvm/ADT/StringSwitch.h"
78 #include "llvm/ADT/Triple.h"
79 #include "llvm/Support/AtomicOrdering.h"
80 #include "llvm/Support/Casting.h"
81 #include "llvm/Support/Compiler.h"
82 #include "llvm/Support/ConvertUTF.h"
83 #include "llvm/Support/ErrorHandling.h"
84 #include "llvm/Support/Format.h"
85 #include "llvm/Support/Locale.h"
86 #include "llvm/Support/MathExtras.h"
87 #include "llvm/Support/SaveAndRestore.h"
88 #include "llvm/Support/raw_ostream.h"
89 #include <algorithm>
90 #include <cassert>
91 #include <cstddef>
92 #include <cstdint>
93 #include <functional>
94 #include <limits>
95 #include <string>
96 #include <tuple>
97 #include <utility>
98 
99 using namespace clang;
100 using namespace sema;
101 
102 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
103                                                     unsigned ByteNo) const {
104   return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
105                                Context.getTargetInfo());
106 }
107 
108 /// Checks that a call expression's argument count is the desired number.
109 /// This is useful when doing custom type-checking.  Returns true on error.
110 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
111   unsigned argCount = call->getNumArgs();
112   if (argCount == desiredArgCount) return false;
113 
114   if (argCount < desiredArgCount)
115     return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args)
116            << 0 /*function call*/ << desiredArgCount << argCount
117            << call->getSourceRange();
118 
119   // Highlight all the excess arguments.
120   SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(),
121                     call->getArg(argCount - 1)->getEndLoc());
122 
123   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
124     << 0 /*function call*/ << desiredArgCount << argCount
125     << call->getArg(1)->getSourceRange();
126 }
127 
128 /// Check that the first argument to __builtin_annotation is an integer
129 /// and the second argument is a non-wide string literal.
130 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
131   if (checkArgCount(S, TheCall, 2))
132     return true;
133 
134   // First argument should be an integer.
135   Expr *ValArg = TheCall->getArg(0);
136   QualType Ty = ValArg->getType();
137   if (!Ty->isIntegerType()) {
138     S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
139         << ValArg->getSourceRange();
140     return true;
141   }
142 
143   // Second argument should be a constant string.
144   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
145   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
146   if (!Literal || !Literal->isAscii()) {
147     S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
148         << StrArg->getSourceRange();
149     return true;
150   }
151 
152   TheCall->setType(Ty);
153   return false;
154 }
155 
156 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
157   // We need at least one argument.
158   if (TheCall->getNumArgs() < 1) {
159     S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
160         << 0 << 1 << TheCall->getNumArgs()
161         << TheCall->getCallee()->getSourceRange();
162     return true;
163   }
164 
165   // All arguments should be wide string literals.
166   for (Expr *Arg : TheCall->arguments()) {
167     auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
168     if (!Literal || !Literal->isWide()) {
169       S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
170           << Arg->getSourceRange();
171       return true;
172     }
173   }
174 
175   return false;
176 }
177 
178 /// Check that the argument to __builtin_addressof is a glvalue, and set the
179 /// result type to the corresponding pointer type.
180 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
181   if (checkArgCount(S, TheCall, 1))
182     return true;
183 
184   ExprResult Arg(TheCall->getArg(0));
185   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
186   if (ResultType.isNull())
187     return true;
188 
189   TheCall->setArg(0, Arg.get());
190   TheCall->setType(ResultType);
191   return false;
192 }
193 
194 /// Check the number of arguments and set the result type to
195 /// the argument type.
196 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
197   if (checkArgCount(S, TheCall, 1))
198     return true;
199 
200   TheCall->setType(TheCall->getArg(0)->getType());
201   return false;
202 }
203 
204 /// Check that the value argument for __builtin_is_aligned(value, alignment) and
205 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
206 /// type (but not a function pointer) and that the alignment is a power-of-two.
207 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
208   if (checkArgCount(S, TheCall, 2))
209     return true;
210 
211   clang::Expr *Source = TheCall->getArg(0);
212   bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
213 
214   auto IsValidIntegerType = [](QualType Ty) {
215     return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
216   };
217   QualType SrcTy = Source->getType();
218   // We should also be able to use it with arrays (but not functions!).
219   if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
220     SrcTy = S.Context.getDecayedType(SrcTy);
221   }
222   if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
223       SrcTy->isFunctionPointerType()) {
224     // FIXME: this is not quite the right error message since we don't allow
225     // floating point types, or member pointers.
226     S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
227         << SrcTy;
228     return true;
229   }
230 
231   clang::Expr *AlignOp = TheCall->getArg(1);
232   if (!IsValidIntegerType(AlignOp->getType())) {
233     S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
234         << AlignOp->getType();
235     return true;
236   }
237   Expr::EvalResult AlignResult;
238   unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
239   // We can't check validity of alignment if it is type dependent.
240   if (!AlignOp->isInstantiationDependent() &&
241       AlignOp->EvaluateAsInt(AlignResult, S.Context,
242                              Expr::SE_AllowSideEffects)) {
243     llvm::APSInt AlignValue = AlignResult.Val.getInt();
244     llvm::APSInt MaxValue(
245         llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
246     if (AlignValue < 1) {
247       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
248       return true;
249     }
250     if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
251       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
252           << MaxValue.toString(10);
253       return true;
254     }
255     if (!AlignValue.isPowerOf2()) {
256       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
257       return true;
258     }
259     if (AlignValue == 1) {
260       S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
261           << IsBooleanAlignBuiltin;
262     }
263   }
264 
265   ExprResult SrcArg = S.PerformCopyInitialization(
266       InitializedEntity::InitializeParameter(S.Context, SrcTy, false),
267       SourceLocation(), Source);
268   if (SrcArg.isInvalid())
269     return true;
270   TheCall->setArg(0, SrcArg.get());
271   ExprResult AlignArg =
272       S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
273                                       S.Context, AlignOp->getType(), false),
274                                   SourceLocation(), AlignOp);
275   if (AlignArg.isInvalid())
276     return true;
277   TheCall->setArg(1, AlignArg.get());
278   // For align_up/align_down, the return type is the same as the (potentially
279   // decayed) argument type including qualifiers. For is_aligned(), the result
280   // is always bool.
281   TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
282   return false;
283 }
284 
285 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
286   if (checkArgCount(S, TheCall, 3))
287     return true;
288 
289   // First two arguments should be integers.
290   for (unsigned I = 0; I < 2; ++I) {
291     ExprResult Arg = TheCall->getArg(I);
292     QualType Ty = Arg.get()->getType();
293     if (!Ty->isIntegerType()) {
294       S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
295           << Ty << Arg.get()->getSourceRange();
296       return true;
297     }
298     InitializedEntity Entity = InitializedEntity::InitializeParameter(
299         S.getASTContext(), Ty, /*consume*/ false);
300     Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
301     if (Arg.isInvalid())
302       return true;
303     TheCall->setArg(I, Arg.get());
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 = TheCall->getArg(2);
311     QualType Ty = Arg.get()->getType();
312     const auto *PtrTy = Ty->getAs<PointerType>();
313     if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
314           !PtrTy->getPointeeType().isConstQualified())) {
315       S.Diag(Arg.get()->getBeginLoc(),
316              diag::err_overflow_builtin_must_be_ptr_int)
317           << Ty << Arg.get()->getSourceRange();
318       return true;
319     }
320     InitializedEntity Entity = InitializedEntity::InitializeParameter(
321         S.getASTContext(), Ty, /*consume*/ false);
322     Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
323     if (Arg.isInvalid())
324       return true;
325     TheCall->setArg(2, Arg.get());
326   }
327   return false;
328 }
329 
330 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
331   if (checkArgCount(S, BuiltinCall, 2))
332     return true;
333 
334   SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
335   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
336   Expr *Call = BuiltinCall->getArg(0);
337   Expr *Chain = BuiltinCall->getArg(1);
338 
339   if (Call->getStmtClass() != Stmt::CallExprClass) {
340     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
341         << Call->getSourceRange();
342     return true;
343   }
344 
345   auto CE = cast<CallExpr>(Call);
346   if (CE->getCallee()->getType()->isBlockPointerType()) {
347     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
348         << Call->getSourceRange();
349     return true;
350   }
351 
352   const Decl *TargetDecl = CE->getCalleeDecl();
353   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
354     if (FD->getBuiltinID()) {
355       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
356           << Call->getSourceRange();
357       return true;
358     }
359 
360   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
361     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
362         << Call->getSourceRange();
363     return true;
364   }
365 
366   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
367   if (ChainResult.isInvalid())
368     return true;
369   if (!ChainResult.get()->getType()->isPointerType()) {
370     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
371         << Chain->getSourceRange();
372     return true;
373   }
374 
375   QualType ReturnTy = CE->getCallReturnType(S.Context);
376   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
377   QualType BuiltinTy = S.Context.getFunctionType(
378       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
379   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
380 
381   Builtin =
382       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
383 
384   BuiltinCall->setType(CE->getType());
385   BuiltinCall->setValueKind(CE->getValueKind());
386   BuiltinCall->setObjectKind(CE->getObjectKind());
387   BuiltinCall->setCallee(Builtin);
388   BuiltinCall->setArg(1, ChainResult.get());
389 
390   return false;
391 }
392 
393 namespace {
394 
395 class EstimateSizeFormatHandler
396     : public analyze_format_string::FormatStringHandler {
397   size_t Size;
398 
399 public:
400   EstimateSizeFormatHandler(StringRef Format)
401       : Size(std::min(Format.find(0), Format.size()) +
402              1 /* null byte always written by sprintf */) {}
403 
404   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
405                              const char *, unsigned SpecifierLen) override {
406 
407     const size_t FieldWidth = computeFieldWidth(FS);
408     const size_t Precision = computePrecision(FS);
409 
410     // The actual format.
411     switch (FS.getConversionSpecifier().getKind()) {
412     // Just a char.
413     case analyze_format_string::ConversionSpecifier::cArg:
414     case analyze_format_string::ConversionSpecifier::CArg:
415       Size += std::max(FieldWidth, (size_t)1);
416       break;
417     // Just an integer.
418     case analyze_format_string::ConversionSpecifier::dArg:
419     case analyze_format_string::ConversionSpecifier::DArg:
420     case analyze_format_string::ConversionSpecifier::iArg:
421     case analyze_format_string::ConversionSpecifier::oArg:
422     case analyze_format_string::ConversionSpecifier::OArg:
423     case analyze_format_string::ConversionSpecifier::uArg:
424     case analyze_format_string::ConversionSpecifier::UArg:
425     case analyze_format_string::ConversionSpecifier::xArg:
426     case analyze_format_string::ConversionSpecifier::XArg:
427       Size += std::max(FieldWidth, Precision);
428       break;
429 
430     // %g style conversion switches between %f or %e style dynamically.
431     // %f always takes less space, so default to it.
432     case analyze_format_string::ConversionSpecifier::gArg:
433     case analyze_format_string::ConversionSpecifier::GArg:
434 
435     // Floating point number in the form '[+]ddd.ddd'.
436     case analyze_format_string::ConversionSpecifier::fArg:
437     case analyze_format_string::ConversionSpecifier::FArg:
438       Size += std::max(FieldWidth, 1 /* integer part */ +
439                                        (Precision ? 1 + Precision
440                                                   : 0) /* period + decimal */);
441       break;
442 
443     // Floating point number in the form '[-]d.ddde[+-]dd'.
444     case analyze_format_string::ConversionSpecifier::eArg:
445     case analyze_format_string::ConversionSpecifier::EArg:
446       Size +=
447           std::max(FieldWidth,
448                    1 /* integer part */ +
449                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
450                        1 /* e or E letter */ + 2 /* exponent */);
451       break;
452 
453     // Floating point number in the form '[-]0xh.hhhhp±dd'.
454     case analyze_format_string::ConversionSpecifier::aArg:
455     case analyze_format_string::ConversionSpecifier::AArg:
456       Size +=
457           std::max(FieldWidth,
458                    2 /* 0x */ + 1 /* integer part */ +
459                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
460                        1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
461       break;
462 
463     // Just a string.
464     case analyze_format_string::ConversionSpecifier::sArg:
465     case analyze_format_string::ConversionSpecifier::SArg:
466       Size += FieldWidth;
467       break;
468 
469     // Just a pointer in the form '0xddd'.
470     case analyze_format_string::ConversionSpecifier::pArg:
471       Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
472       break;
473 
474     // A plain percent.
475     case analyze_format_string::ConversionSpecifier::PercentArg:
476       Size += 1;
477       break;
478 
479     default:
480       break;
481     }
482 
483     Size += FS.hasPlusPrefix() || FS.hasSpacePrefix();
484 
485     if (FS.hasAlternativeForm()) {
486       switch (FS.getConversionSpecifier().getKind()) {
487       default:
488         break;
489       // Force a leading '0'.
490       case analyze_format_string::ConversionSpecifier::oArg:
491         Size += 1;
492         break;
493       // Force a leading '0x'.
494       case analyze_format_string::ConversionSpecifier::xArg:
495       case analyze_format_string::ConversionSpecifier::XArg:
496         Size += 2;
497         break;
498       // Force a period '.' before decimal, even if precision is 0.
499       case analyze_format_string::ConversionSpecifier::aArg:
500       case analyze_format_string::ConversionSpecifier::AArg:
501       case analyze_format_string::ConversionSpecifier::eArg:
502       case analyze_format_string::ConversionSpecifier::EArg:
503       case analyze_format_string::ConversionSpecifier::fArg:
504       case analyze_format_string::ConversionSpecifier::FArg:
505       case analyze_format_string::ConversionSpecifier::gArg:
506       case analyze_format_string::ConversionSpecifier::GArg:
507         Size += (Precision ? 0 : 1);
508         break;
509       }
510     }
511     assert(SpecifierLen <= Size && "no underflow");
512     Size -= SpecifierLen;
513     return true;
514   }
515 
516   size_t getSizeLowerBound() const { return Size; }
517 
518 private:
519   static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
520     const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
521     size_t FieldWidth = 0;
522     if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant)
523       FieldWidth = FW.getConstantAmount();
524     return FieldWidth;
525   }
526 
527   static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
528     const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
529     size_t Precision = 0;
530 
531     // See man 3 printf for default precision value based on the specifier.
532     switch (FW.getHowSpecified()) {
533     case analyze_format_string::OptionalAmount::NotSpecified:
534       switch (FS.getConversionSpecifier().getKind()) {
535       default:
536         break;
537       case analyze_format_string::ConversionSpecifier::dArg: // %d
538       case analyze_format_string::ConversionSpecifier::DArg: // %D
539       case analyze_format_string::ConversionSpecifier::iArg: // %i
540         Precision = 1;
541         break;
542       case analyze_format_string::ConversionSpecifier::oArg: // %d
543       case analyze_format_string::ConversionSpecifier::OArg: // %D
544       case analyze_format_string::ConversionSpecifier::uArg: // %d
545       case analyze_format_string::ConversionSpecifier::UArg: // %D
546       case analyze_format_string::ConversionSpecifier::xArg: // %d
547       case analyze_format_string::ConversionSpecifier::XArg: // %D
548         Precision = 1;
549         break;
550       case analyze_format_string::ConversionSpecifier::fArg: // %f
551       case analyze_format_string::ConversionSpecifier::FArg: // %F
552       case analyze_format_string::ConversionSpecifier::eArg: // %e
553       case analyze_format_string::ConversionSpecifier::EArg: // %E
554       case analyze_format_string::ConversionSpecifier::gArg: // %g
555       case analyze_format_string::ConversionSpecifier::GArg: // %G
556         Precision = 6;
557         break;
558       case analyze_format_string::ConversionSpecifier::pArg: // %d
559         Precision = 1;
560         break;
561       }
562       break;
563     case analyze_format_string::OptionalAmount::Constant:
564       Precision = FW.getConstantAmount();
565       break;
566     default:
567       break;
568     }
569     return Precision;
570   }
571 };
572 
573 } // namespace
574 
575 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a
576 /// __builtin_*_chk function, then use the object size argument specified in the
577 /// source. Otherwise, infer the object size using __builtin_object_size.
578 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
579                                                CallExpr *TheCall) {
580   // FIXME: There are some more useful checks we could be doing here:
581   //  - Evaluate strlen of strcpy arguments, use as object size.
582 
583   if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
584       isConstantEvaluated())
585     return;
586 
587   unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
588   if (!BuiltinID)
589     return;
590 
591   const TargetInfo &TI = getASTContext().getTargetInfo();
592   unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
593 
594   unsigned DiagID = 0;
595   bool IsChkVariant = false;
596   Optional<llvm::APSInt> UsedSize;
597   unsigned SizeIndex, ObjectIndex;
598   switch (BuiltinID) {
599   default:
600     return;
601   case Builtin::BIsprintf:
602   case Builtin::BI__builtin___sprintf_chk: {
603     size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
604     auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
605 
606     if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) {
607 
608       if (!Format->isAscii() && !Format->isUTF8())
609         return;
610 
611       StringRef FormatStrRef = Format->getString();
612       EstimateSizeFormatHandler H(FormatStrRef);
613       const char *FormatBytes = FormatStrRef.data();
614       const ConstantArrayType *T =
615           Context.getAsConstantArrayType(Format->getType());
616       assert(T && "String literal not of constant array type!");
617       size_t TypeSize = T->getSize().getZExtValue();
618 
619       // In case there's a null byte somewhere.
620       size_t StrLen =
621           std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
622       if (!analyze_format_string::ParsePrintfString(
623               H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
624               Context.getTargetInfo(), false)) {
625         DiagID = diag::warn_fortify_source_format_overflow;
626         UsedSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
627                        .extOrTrunc(SizeTypeWidth);
628         if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
629           IsChkVariant = true;
630           ObjectIndex = 2;
631         } else {
632           IsChkVariant = false;
633           ObjectIndex = 0;
634         }
635         break;
636       }
637     }
638     return;
639   }
640   case Builtin::BI__builtin___memcpy_chk:
641   case Builtin::BI__builtin___memmove_chk:
642   case Builtin::BI__builtin___memset_chk:
643   case Builtin::BI__builtin___strlcat_chk:
644   case Builtin::BI__builtin___strlcpy_chk:
645   case Builtin::BI__builtin___strncat_chk:
646   case Builtin::BI__builtin___strncpy_chk:
647   case Builtin::BI__builtin___stpncpy_chk:
648   case Builtin::BI__builtin___memccpy_chk:
649   case Builtin::BI__builtin___mempcpy_chk: {
650     DiagID = diag::warn_builtin_chk_overflow;
651     IsChkVariant = true;
652     SizeIndex = TheCall->getNumArgs() - 2;
653     ObjectIndex = TheCall->getNumArgs() - 1;
654     break;
655   }
656 
657   case Builtin::BI__builtin___snprintf_chk:
658   case Builtin::BI__builtin___vsnprintf_chk: {
659     DiagID = diag::warn_builtin_chk_overflow;
660     IsChkVariant = true;
661     SizeIndex = 1;
662     ObjectIndex = 3;
663     break;
664   }
665 
666   case Builtin::BIstrncat:
667   case Builtin::BI__builtin_strncat:
668   case Builtin::BIstrncpy:
669   case Builtin::BI__builtin_strncpy:
670   case Builtin::BIstpncpy:
671   case Builtin::BI__builtin_stpncpy: {
672     // Whether these functions overflow depends on the runtime strlen of the
673     // string, not just the buffer size, so emitting the "always overflow"
674     // diagnostic isn't quite right. We should still diagnose passing a buffer
675     // size larger than the destination buffer though; this is a runtime abort
676     // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
677     DiagID = diag::warn_fortify_source_size_mismatch;
678     SizeIndex = TheCall->getNumArgs() - 1;
679     ObjectIndex = 0;
680     break;
681   }
682 
683   case Builtin::BImemcpy:
684   case Builtin::BI__builtin_memcpy:
685   case Builtin::BImemmove:
686   case Builtin::BI__builtin_memmove:
687   case Builtin::BImemset:
688   case Builtin::BI__builtin_memset:
689   case Builtin::BImempcpy:
690   case Builtin::BI__builtin_mempcpy: {
691     DiagID = diag::warn_fortify_source_overflow;
692     SizeIndex = TheCall->getNumArgs() - 1;
693     ObjectIndex = 0;
694     break;
695   }
696   case Builtin::BIsnprintf:
697   case Builtin::BI__builtin_snprintf:
698   case Builtin::BIvsnprintf:
699   case Builtin::BI__builtin_vsnprintf: {
700     DiagID = diag::warn_fortify_source_size_mismatch;
701     SizeIndex = 1;
702     ObjectIndex = 0;
703     break;
704   }
705   }
706 
707   llvm::APSInt ObjectSize;
708   // For __builtin___*_chk, the object size is explicitly provided by the caller
709   // (usually using __builtin_object_size). Use that value to check this call.
710   if (IsChkVariant) {
711     Expr::EvalResult Result;
712     Expr *SizeArg = TheCall->getArg(ObjectIndex);
713     if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
714       return;
715     ObjectSize = Result.Val.getInt();
716 
717   // Otherwise, try to evaluate an imaginary call to __builtin_object_size.
718   } else {
719     // If the parameter has a pass_object_size attribute, then we should use its
720     // (potentially) more strict checking mode. Otherwise, conservatively assume
721     // type 0.
722     int BOSType = 0;
723     if (const auto *POS =
724             FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>())
725       BOSType = POS->getType();
726 
727     Expr *ObjArg = TheCall->getArg(ObjectIndex);
728     uint64_t Result;
729     if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
730       return;
731     // Get the object size in the target's size_t width.
732     ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
733   }
734 
735   // Evaluate the number of bytes of the object that this call will use.
736   if (!UsedSize) {
737     Expr::EvalResult Result;
738     Expr *UsedSizeArg = TheCall->getArg(SizeIndex);
739     if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext()))
740       return;
741     UsedSize = Result.Val.getInt().extOrTrunc(SizeTypeWidth);
742   }
743 
744   if (UsedSize.getValue().ule(ObjectSize))
745     return;
746 
747   StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
748   // Skim off the details of whichever builtin was called to produce a better
749   // diagnostic, as it's unlikley that the user wrote the __builtin explicitly.
750   if (IsChkVariant) {
751     FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
752     FunctionName = FunctionName.drop_back(std::strlen("_chk"));
753   } else if (FunctionName.startswith("__builtin_")) {
754     FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
755   }
756 
757   DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
758                       PDiag(DiagID)
759                           << FunctionName << ObjectSize.toString(/*Radix=*/10)
760                           << UsedSize.getValue().toString(/*Radix=*/10));
761 }
762 
763 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
764                                      Scope::ScopeFlags NeededScopeFlags,
765                                      unsigned DiagID) {
766   // Scopes aren't available during instantiation. Fortunately, builtin
767   // functions cannot be template args so they cannot be formed through template
768   // instantiation. Therefore checking once during the parse is sufficient.
769   if (SemaRef.inTemplateInstantiation())
770     return false;
771 
772   Scope *S = SemaRef.getCurScope();
773   while (S && !S->isSEHExceptScope())
774     S = S->getParent();
775   if (!S || !(S->getFlags() & NeededScopeFlags)) {
776     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
777     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
778         << DRE->getDecl()->getIdentifier();
779     return true;
780   }
781 
782   return false;
783 }
784 
785 static inline bool isBlockPointer(Expr *Arg) {
786   return Arg->getType()->isBlockPointerType();
787 }
788 
789 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
790 /// void*, which is a requirement of device side enqueue.
791 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
792   const BlockPointerType *BPT =
793       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
794   ArrayRef<QualType> Params =
795       BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
796   unsigned ArgCounter = 0;
797   bool IllegalParams = false;
798   // Iterate through the block parameters until either one is found that is not
799   // a local void*, or the block is valid.
800   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
801        I != E; ++I, ++ArgCounter) {
802     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
803         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
804             LangAS::opencl_local) {
805       // Get the location of the error. If a block literal has been passed
806       // (BlockExpr) then we can point straight to the offending argument,
807       // else we just point to the variable reference.
808       SourceLocation ErrorLoc;
809       if (isa<BlockExpr>(BlockArg)) {
810         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
811         ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
812       } else if (isa<DeclRefExpr>(BlockArg)) {
813         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
814       }
815       S.Diag(ErrorLoc,
816              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
817       IllegalParams = true;
818     }
819   }
820 
821   return IllegalParams;
822 }
823 
824 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
825   if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
826     S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
827         << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
828     return true;
829   }
830   return false;
831 }
832 
833 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
834   if (checkArgCount(S, TheCall, 2))
835     return true;
836 
837   if (checkOpenCLSubgroupExt(S, TheCall))
838     return true;
839 
840   // First argument is an ndrange_t type.
841   Expr *NDRangeArg = TheCall->getArg(0);
842   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
843     S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
844         << TheCall->getDirectCallee() << "'ndrange_t'";
845     return true;
846   }
847 
848   Expr *BlockArg = TheCall->getArg(1);
849   if (!isBlockPointer(BlockArg)) {
850     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
851         << TheCall->getDirectCallee() << "block";
852     return true;
853   }
854   return checkOpenCLBlockArgs(S, BlockArg);
855 }
856 
857 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
858 /// get_kernel_work_group_size
859 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
860 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
861   if (checkArgCount(S, TheCall, 1))
862     return true;
863 
864   Expr *BlockArg = TheCall->getArg(0);
865   if (!isBlockPointer(BlockArg)) {
866     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
867         << TheCall->getDirectCallee() << "block";
868     return true;
869   }
870   return checkOpenCLBlockArgs(S, BlockArg);
871 }
872 
873 /// Diagnose integer type and any valid implicit conversion to it.
874 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
875                                       const QualType &IntType);
876 
877 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
878                                             unsigned Start, unsigned End) {
879   bool IllegalParams = false;
880   for (unsigned I = Start; I <= End; ++I)
881     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
882                                               S.Context.getSizeType());
883   return IllegalParams;
884 }
885 
886 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
887 /// 'local void*' parameter of passed block.
888 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
889                                            Expr *BlockArg,
890                                            unsigned NumNonVarArgs) {
891   const BlockPointerType *BPT =
892       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
893   unsigned NumBlockParams =
894       BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
895   unsigned TotalNumArgs = TheCall->getNumArgs();
896 
897   // For each argument passed to the block, a corresponding uint needs to
898   // be passed to describe the size of the local memory.
899   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
900     S.Diag(TheCall->getBeginLoc(),
901            diag::err_opencl_enqueue_kernel_local_size_args);
902     return true;
903   }
904 
905   // Check that the sizes of the local memory are specified by integers.
906   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
907                                          TotalNumArgs - 1);
908 }
909 
910 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
911 /// overload formats specified in Table 6.13.17.1.
912 /// int enqueue_kernel(queue_t queue,
913 ///                    kernel_enqueue_flags_t flags,
914 ///                    const ndrange_t ndrange,
915 ///                    void (^block)(void))
916 /// int enqueue_kernel(queue_t queue,
917 ///                    kernel_enqueue_flags_t flags,
918 ///                    const ndrange_t ndrange,
919 ///                    uint num_events_in_wait_list,
920 ///                    clk_event_t *event_wait_list,
921 ///                    clk_event_t *event_ret,
922 ///                    void (^block)(void))
923 /// int enqueue_kernel(queue_t queue,
924 ///                    kernel_enqueue_flags_t flags,
925 ///                    const ndrange_t ndrange,
926 ///                    void (^block)(local void*, ...),
927 ///                    uint size0, ...)
928 /// int enqueue_kernel(queue_t queue,
929 ///                    kernel_enqueue_flags_t flags,
930 ///                    const ndrange_t ndrange,
931 ///                    uint num_events_in_wait_list,
932 ///                    clk_event_t *event_wait_list,
933 ///                    clk_event_t *event_ret,
934 ///                    void (^block)(local void*, ...),
935 ///                    uint size0, ...)
936 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
937   unsigned NumArgs = TheCall->getNumArgs();
938 
939   if (NumArgs < 4) {
940     S.Diag(TheCall->getBeginLoc(),
941            diag::err_typecheck_call_too_few_args_at_least)
942         << 0 << 4 << NumArgs;
943     return true;
944   }
945 
946   Expr *Arg0 = TheCall->getArg(0);
947   Expr *Arg1 = TheCall->getArg(1);
948   Expr *Arg2 = TheCall->getArg(2);
949   Expr *Arg3 = TheCall->getArg(3);
950 
951   // First argument always needs to be a queue_t type.
952   if (!Arg0->getType()->isQueueT()) {
953     S.Diag(TheCall->getArg(0)->getBeginLoc(),
954            diag::err_opencl_builtin_expected_type)
955         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
956     return true;
957   }
958 
959   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
960   if (!Arg1->getType()->isIntegerType()) {
961     S.Diag(TheCall->getArg(1)->getBeginLoc(),
962            diag::err_opencl_builtin_expected_type)
963         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
964     return true;
965   }
966 
967   // Third argument is always an ndrange_t type.
968   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
969     S.Diag(TheCall->getArg(2)->getBeginLoc(),
970            diag::err_opencl_builtin_expected_type)
971         << TheCall->getDirectCallee() << "'ndrange_t'";
972     return true;
973   }
974 
975   // With four arguments, there is only one form that the function could be
976   // called in: no events and no variable arguments.
977   if (NumArgs == 4) {
978     // check that the last argument is the right block type.
979     if (!isBlockPointer(Arg3)) {
980       S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
981           << TheCall->getDirectCallee() << "block";
982       return true;
983     }
984     // we have a block type, check the prototype
985     const BlockPointerType *BPT =
986         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
987     if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
988       S.Diag(Arg3->getBeginLoc(),
989              diag::err_opencl_enqueue_kernel_blocks_no_args);
990       return true;
991     }
992     return false;
993   }
994   // we can have block + varargs.
995   if (isBlockPointer(Arg3))
996     return (checkOpenCLBlockArgs(S, Arg3) ||
997             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
998   // last two cases with either exactly 7 args or 7 args and varargs.
999   if (NumArgs >= 7) {
1000     // check common block argument.
1001     Expr *Arg6 = TheCall->getArg(6);
1002     if (!isBlockPointer(Arg6)) {
1003       S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1004           << TheCall->getDirectCallee() << "block";
1005       return true;
1006     }
1007     if (checkOpenCLBlockArgs(S, Arg6))
1008       return true;
1009 
1010     // Forth argument has to be any integer type.
1011     if (!Arg3->getType()->isIntegerType()) {
1012       S.Diag(TheCall->getArg(3)->getBeginLoc(),
1013              diag::err_opencl_builtin_expected_type)
1014           << TheCall->getDirectCallee() << "integer";
1015       return true;
1016     }
1017     // check remaining common arguments.
1018     Expr *Arg4 = TheCall->getArg(4);
1019     Expr *Arg5 = TheCall->getArg(5);
1020 
1021     // Fifth argument is always passed as a pointer to clk_event_t.
1022     if (!Arg4->isNullPointerConstant(S.Context,
1023                                      Expr::NPC_ValueDependentIsNotNull) &&
1024         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
1025       S.Diag(TheCall->getArg(4)->getBeginLoc(),
1026              diag::err_opencl_builtin_expected_type)
1027           << TheCall->getDirectCallee()
1028           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1029       return true;
1030     }
1031 
1032     // Sixth argument is always passed as a pointer to clk_event_t.
1033     if (!Arg5->isNullPointerConstant(S.Context,
1034                                      Expr::NPC_ValueDependentIsNotNull) &&
1035         !(Arg5->getType()->isPointerType() &&
1036           Arg5->getType()->getPointeeType()->isClkEventT())) {
1037       S.Diag(TheCall->getArg(5)->getBeginLoc(),
1038              diag::err_opencl_builtin_expected_type)
1039           << TheCall->getDirectCallee()
1040           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1041       return true;
1042     }
1043 
1044     if (NumArgs == 7)
1045       return false;
1046 
1047     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
1048   }
1049 
1050   // None of the specific case has been detected, give generic error
1051   S.Diag(TheCall->getBeginLoc(),
1052          diag::err_opencl_enqueue_kernel_incorrect_args);
1053   return true;
1054 }
1055 
1056 /// Returns OpenCL access qual.
1057 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
1058     return D->getAttr<OpenCLAccessAttr>();
1059 }
1060 
1061 /// Returns true if pipe element type is different from the pointer.
1062 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
1063   const Expr *Arg0 = Call->getArg(0);
1064   // First argument type should always be pipe.
1065   if (!Arg0->getType()->isPipeType()) {
1066     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1067         << Call->getDirectCallee() << Arg0->getSourceRange();
1068     return true;
1069   }
1070   OpenCLAccessAttr *AccessQual =
1071       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
1072   // Validates the access qualifier is compatible with the call.
1073   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
1074   // read_only and write_only, and assumed to be read_only if no qualifier is
1075   // specified.
1076   switch (Call->getDirectCallee()->getBuiltinID()) {
1077   case Builtin::BIread_pipe:
1078   case Builtin::BIreserve_read_pipe:
1079   case Builtin::BIcommit_read_pipe:
1080   case Builtin::BIwork_group_reserve_read_pipe:
1081   case Builtin::BIsub_group_reserve_read_pipe:
1082   case Builtin::BIwork_group_commit_read_pipe:
1083   case Builtin::BIsub_group_commit_read_pipe:
1084     if (!(!AccessQual || AccessQual->isReadOnly())) {
1085       S.Diag(Arg0->getBeginLoc(),
1086              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1087           << "read_only" << Arg0->getSourceRange();
1088       return true;
1089     }
1090     break;
1091   case Builtin::BIwrite_pipe:
1092   case Builtin::BIreserve_write_pipe:
1093   case Builtin::BIcommit_write_pipe:
1094   case Builtin::BIwork_group_reserve_write_pipe:
1095   case Builtin::BIsub_group_reserve_write_pipe:
1096   case Builtin::BIwork_group_commit_write_pipe:
1097   case Builtin::BIsub_group_commit_write_pipe:
1098     if (!(AccessQual && AccessQual->isWriteOnly())) {
1099       S.Diag(Arg0->getBeginLoc(),
1100              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1101           << "write_only" << Arg0->getSourceRange();
1102       return true;
1103     }
1104     break;
1105   default:
1106     break;
1107   }
1108   return false;
1109 }
1110 
1111 /// Returns true if pipe element type is different from the pointer.
1112 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
1113   const Expr *Arg0 = Call->getArg(0);
1114   const Expr *ArgIdx = Call->getArg(Idx);
1115   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
1116   const QualType EltTy = PipeTy->getElementType();
1117   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
1118   // The Idx argument should be a pointer and the type of the pointer and
1119   // the type of pipe element should also be the same.
1120   if (!ArgTy ||
1121       !S.Context.hasSameType(
1122           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
1123     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1124         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
1125         << ArgIdx->getType() << ArgIdx->getSourceRange();
1126     return true;
1127   }
1128   return false;
1129 }
1130 
1131 // Performs semantic analysis for the read/write_pipe call.
1132 // \param S Reference to the semantic analyzer.
1133 // \param Call A pointer to the builtin call.
1134 // \return True if a semantic error has been found, false otherwise.
1135 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
1136   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
1137   // functions have two forms.
1138   switch (Call->getNumArgs()) {
1139   case 2:
1140     if (checkOpenCLPipeArg(S, Call))
1141       return true;
1142     // The call with 2 arguments should be
1143     // read/write_pipe(pipe T, T*).
1144     // Check packet type T.
1145     if (checkOpenCLPipePacketType(S, Call, 1))
1146       return true;
1147     break;
1148 
1149   case 4: {
1150     if (checkOpenCLPipeArg(S, Call))
1151       return true;
1152     // The call with 4 arguments should be
1153     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
1154     // Check reserve_id_t.
1155     if (!Call->getArg(1)->getType()->isReserveIDT()) {
1156       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1157           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1158           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1159       return true;
1160     }
1161 
1162     // Check the index.
1163     const Expr *Arg2 = Call->getArg(2);
1164     if (!Arg2->getType()->isIntegerType() &&
1165         !Arg2->getType()->isUnsignedIntegerType()) {
1166       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1167           << Call->getDirectCallee() << S.Context.UnsignedIntTy
1168           << Arg2->getType() << Arg2->getSourceRange();
1169       return true;
1170     }
1171 
1172     // Check packet type T.
1173     if (checkOpenCLPipePacketType(S, Call, 3))
1174       return true;
1175   } break;
1176   default:
1177     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
1178         << Call->getDirectCallee() << Call->getSourceRange();
1179     return true;
1180   }
1181 
1182   return false;
1183 }
1184 
1185 // Performs a semantic analysis on the {work_group_/sub_group_
1186 //        /_}reserve_{read/write}_pipe
1187 // \param S Reference to the semantic analyzer.
1188 // \param Call The call to the builtin function to be analyzed.
1189 // \return True if a semantic error was found, false otherwise.
1190 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
1191   if (checkArgCount(S, Call, 2))
1192     return true;
1193 
1194   if (checkOpenCLPipeArg(S, Call))
1195     return true;
1196 
1197   // Check the reserve size.
1198   if (!Call->getArg(1)->getType()->isIntegerType() &&
1199       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
1200     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1201         << Call->getDirectCallee() << S.Context.UnsignedIntTy
1202         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1203     return true;
1204   }
1205 
1206   // Since return type of reserve_read/write_pipe built-in function is
1207   // reserve_id_t, which is not defined in the builtin def file , we used int
1208   // as return type and need to override the return type of these functions.
1209   Call->setType(S.Context.OCLReserveIDTy);
1210 
1211   return false;
1212 }
1213 
1214 // Performs a semantic analysis on {work_group_/sub_group_
1215 //        /_}commit_{read/write}_pipe
1216 // \param S Reference to the semantic analyzer.
1217 // \param Call The call to the builtin function to be analyzed.
1218 // \return True if a semantic error was found, false otherwise.
1219 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
1220   if (checkArgCount(S, Call, 2))
1221     return true;
1222 
1223   if (checkOpenCLPipeArg(S, Call))
1224     return true;
1225 
1226   // Check reserve_id_t.
1227   if (!Call->getArg(1)->getType()->isReserveIDT()) {
1228     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1229         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1230         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1231     return true;
1232   }
1233 
1234   return false;
1235 }
1236 
1237 // Performs a semantic analysis on the call to built-in Pipe
1238 //        Query Functions.
1239 // \param S Reference to the semantic analyzer.
1240 // \param Call The call to the builtin function to be analyzed.
1241 // \return True if a semantic error was found, false otherwise.
1242 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
1243   if (checkArgCount(S, Call, 1))
1244     return true;
1245 
1246   if (!Call->getArg(0)->getType()->isPipeType()) {
1247     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1248         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
1249     return true;
1250   }
1251 
1252   return false;
1253 }
1254 
1255 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
1256 // Performs semantic analysis for the to_global/local/private call.
1257 // \param S Reference to the semantic analyzer.
1258 // \param BuiltinID ID of the builtin function.
1259 // \param Call A pointer to the builtin call.
1260 // \return True if a semantic error has been found, false otherwise.
1261 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
1262                                     CallExpr *Call) {
1263   if (Call->getNumArgs() != 1) {
1264     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num)
1265         << Call->getDirectCallee() << Call->getSourceRange();
1266     return true;
1267   }
1268 
1269   auto RT = Call->getArg(0)->getType();
1270   if (!RT->isPointerType() || RT->getPointeeType()
1271       .getAddressSpace() == LangAS::opencl_constant) {
1272     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
1273         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
1274     return true;
1275   }
1276 
1277   if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
1278     S.Diag(Call->getArg(0)->getBeginLoc(),
1279            diag::warn_opencl_generic_address_space_arg)
1280         << Call->getDirectCallee()->getNameInfo().getAsString()
1281         << Call->getArg(0)->getSourceRange();
1282   }
1283 
1284   RT = RT->getPointeeType();
1285   auto Qual = RT.getQualifiers();
1286   switch (BuiltinID) {
1287   case Builtin::BIto_global:
1288     Qual.setAddressSpace(LangAS::opencl_global);
1289     break;
1290   case Builtin::BIto_local:
1291     Qual.setAddressSpace(LangAS::opencl_local);
1292     break;
1293   case Builtin::BIto_private:
1294     Qual.setAddressSpace(LangAS::opencl_private);
1295     break;
1296   default:
1297     llvm_unreachable("Invalid builtin function");
1298   }
1299   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
1300       RT.getUnqualifiedType(), Qual)));
1301 
1302   return false;
1303 }
1304 
1305 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
1306   if (checkArgCount(S, TheCall, 1))
1307     return ExprError();
1308 
1309   // Compute __builtin_launder's parameter type from the argument.
1310   // The parameter type is:
1311   //  * The type of the argument if it's not an array or function type,
1312   //  Otherwise,
1313   //  * The decayed argument type.
1314   QualType ParamTy = [&]() {
1315     QualType ArgTy = TheCall->getArg(0)->getType();
1316     if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1317       return S.Context.getPointerType(Ty->getElementType());
1318     if (ArgTy->isFunctionType()) {
1319       return S.Context.getPointerType(ArgTy);
1320     }
1321     return ArgTy;
1322   }();
1323 
1324   TheCall->setType(ParamTy);
1325 
1326   auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1327     if (!ParamTy->isPointerType())
1328       return 0;
1329     if (ParamTy->isFunctionPointerType())
1330       return 1;
1331     if (ParamTy->isVoidPointerType())
1332       return 2;
1333     return llvm::Optional<unsigned>{};
1334   }();
1335   if (DiagSelect.hasValue()) {
1336     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1337         << DiagSelect.getValue() << TheCall->getSourceRange();
1338     return ExprError();
1339   }
1340 
1341   // We either have an incomplete class type, or we have a class template
1342   // whose instantiation has not been forced. Example:
1343   //
1344   //   template <class T> struct Foo { T value; };
1345   //   Foo<int> *p = nullptr;
1346   //   auto *d = __builtin_launder(p);
1347   if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1348                             diag::err_incomplete_type))
1349     return ExprError();
1350 
1351   assert(ParamTy->getPointeeType()->isObjectType() &&
1352          "Unhandled non-object pointer case");
1353 
1354   InitializedEntity Entity =
1355       InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1356   ExprResult Arg =
1357       S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1358   if (Arg.isInvalid())
1359     return ExprError();
1360   TheCall->setArg(0, Arg.get());
1361 
1362   return TheCall;
1363 }
1364 
1365 // Emit an error and return true if the current architecture is not in the list
1366 // of supported architectures.
1367 static bool
1368 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1369                           ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1370   llvm::Triple::ArchType CurArch =
1371       S.getASTContext().getTargetInfo().getTriple().getArch();
1372   if (llvm::is_contained(SupportedArchs, CurArch))
1373     return false;
1374   S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1375       << TheCall->getSourceRange();
1376   return true;
1377 }
1378 
1379 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
1380                                  SourceLocation CallSiteLoc);
1381 
1382 bool Sema::CheckTSBuiltinFunctionCall(llvm::Triple::ArchType Arch,
1383                                       unsigned BuiltinID, CallExpr *TheCall) {
1384   switch (Arch) {
1385   default:
1386     // Some builtins don't require additional checking, so just consider these
1387     // acceptable.
1388     return false;
1389   case llvm::Triple::arm:
1390   case llvm::Triple::armeb:
1391   case llvm::Triple::thumb:
1392   case llvm::Triple::thumbeb:
1393     return CheckARMBuiltinFunctionCall(BuiltinID, TheCall);
1394   case llvm::Triple::aarch64:
1395   case llvm::Triple::aarch64_32:
1396   case llvm::Triple::aarch64_be:
1397     return CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall);
1398   case llvm::Triple::bpfeb:
1399   case llvm::Triple::bpfel:
1400     return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
1401   case llvm::Triple::hexagon:
1402     return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
1403   case llvm::Triple::mips:
1404   case llvm::Triple::mipsel:
1405   case llvm::Triple::mips64:
1406   case llvm::Triple::mips64el:
1407     return CheckMipsBuiltinFunctionCall(BuiltinID, TheCall);
1408   case llvm::Triple::systemz:
1409     return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
1410   case llvm::Triple::x86:
1411   case llvm::Triple::x86_64:
1412     return CheckX86BuiltinFunctionCall(BuiltinID, TheCall);
1413   case llvm::Triple::ppc:
1414   case llvm::Triple::ppc64:
1415   case llvm::Triple::ppc64le:
1416     return CheckPPCBuiltinFunctionCall(BuiltinID, TheCall);
1417   case llvm::Triple::amdgcn:
1418     return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
1419   }
1420 }
1421 
1422 ExprResult
1423 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1424                                CallExpr *TheCall) {
1425   ExprResult TheCallResult(TheCall);
1426 
1427   // Find out if any arguments are required to be integer constant expressions.
1428   unsigned ICEArguments = 0;
1429   ASTContext::GetBuiltinTypeError Error;
1430   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1431   if (Error != ASTContext::GE_None)
1432     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
1433 
1434   // If any arguments are required to be ICE's, check and diagnose.
1435   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1436     // Skip arguments not required to be ICE's.
1437     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1438 
1439     llvm::APSInt Result;
1440     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1441       return true;
1442     ICEArguments &= ~(1 << ArgNo);
1443   }
1444 
1445   switch (BuiltinID) {
1446   case Builtin::BI__builtin___CFStringMakeConstantString:
1447     assert(TheCall->getNumArgs() == 1 &&
1448            "Wrong # arguments to builtin CFStringMakeConstantString");
1449     if (CheckObjCString(TheCall->getArg(0)))
1450       return ExprError();
1451     break;
1452   case Builtin::BI__builtin_ms_va_start:
1453   case Builtin::BI__builtin_stdarg_start:
1454   case Builtin::BI__builtin_va_start:
1455     if (SemaBuiltinVAStart(BuiltinID, TheCall))
1456       return ExprError();
1457     break;
1458   case Builtin::BI__va_start: {
1459     switch (Context.getTargetInfo().getTriple().getArch()) {
1460     case llvm::Triple::aarch64:
1461     case llvm::Triple::arm:
1462     case llvm::Triple::thumb:
1463       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1464         return ExprError();
1465       break;
1466     default:
1467       if (SemaBuiltinVAStart(BuiltinID, TheCall))
1468         return ExprError();
1469       break;
1470     }
1471     break;
1472   }
1473 
1474   // The acquire, release, and no fence variants are ARM and AArch64 only.
1475   case Builtin::BI_interlockedbittestandset_acq:
1476   case Builtin::BI_interlockedbittestandset_rel:
1477   case Builtin::BI_interlockedbittestandset_nf:
1478   case Builtin::BI_interlockedbittestandreset_acq:
1479   case Builtin::BI_interlockedbittestandreset_rel:
1480   case Builtin::BI_interlockedbittestandreset_nf:
1481     if (CheckBuiltinTargetSupport(
1482             *this, BuiltinID, TheCall,
1483             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1484       return ExprError();
1485     break;
1486 
1487   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1488   case Builtin::BI_bittest64:
1489   case Builtin::BI_bittestandcomplement64:
1490   case Builtin::BI_bittestandreset64:
1491   case Builtin::BI_bittestandset64:
1492   case Builtin::BI_interlockedbittestandreset64:
1493   case Builtin::BI_interlockedbittestandset64:
1494     if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1495                                   {llvm::Triple::x86_64, llvm::Triple::arm,
1496                                    llvm::Triple::thumb, llvm::Triple::aarch64}))
1497       return ExprError();
1498     break;
1499 
1500   case Builtin::BI__builtin_isgreater:
1501   case Builtin::BI__builtin_isgreaterequal:
1502   case Builtin::BI__builtin_isless:
1503   case Builtin::BI__builtin_islessequal:
1504   case Builtin::BI__builtin_islessgreater:
1505   case Builtin::BI__builtin_isunordered:
1506     if (SemaBuiltinUnorderedCompare(TheCall))
1507       return ExprError();
1508     break;
1509   case Builtin::BI__builtin_fpclassify:
1510     if (SemaBuiltinFPClassification(TheCall, 6))
1511       return ExprError();
1512     break;
1513   case Builtin::BI__builtin_isfinite:
1514   case Builtin::BI__builtin_isinf:
1515   case Builtin::BI__builtin_isinf_sign:
1516   case Builtin::BI__builtin_isnan:
1517   case Builtin::BI__builtin_isnormal:
1518   case Builtin::BI__builtin_signbit:
1519   case Builtin::BI__builtin_signbitf:
1520   case Builtin::BI__builtin_signbitl:
1521     if (SemaBuiltinFPClassification(TheCall, 1))
1522       return ExprError();
1523     break;
1524   case Builtin::BI__builtin_shufflevector:
1525     return SemaBuiltinShuffleVector(TheCall);
1526     // TheCall will be freed by the smart pointer here, but that's fine, since
1527     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1528   case Builtin::BI__builtin_prefetch:
1529     if (SemaBuiltinPrefetch(TheCall))
1530       return ExprError();
1531     break;
1532   case Builtin::BI__builtin_alloca_with_align:
1533     if (SemaBuiltinAllocaWithAlign(TheCall))
1534       return ExprError();
1535     LLVM_FALLTHROUGH;
1536   case Builtin::BI__builtin_alloca:
1537     Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1538         << TheCall->getDirectCallee();
1539     break;
1540   case Builtin::BI__assume:
1541   case Builtin::BI__builtin_assume:
1542     if (SemaBuiltinAssume(TheCall))
1543       return ExprError();
1544     break;
1545   case Builtin::BI__builtin_assume_aligned:
1546     if (SemaBuiltinAssumeAligned(TheCall))
1547       return ExprError();
1548     break;
1549   case Builtin::BI__builtin_dynamic_object_size:
1550   case Builtin::BI__builtin_object_size:
1551     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1552       return ExprError();
1553     break;
1554   case Builtin::BI__builtin_longjmp:
1555     if (SemaBuiltinLongjmp(TheCall))
1556       return ExprError();
1557     break;
1558   case Builtin::BI__builtin_setjmp:
1559     if (SemaBuiltinSetjmp(TheCall))
1560       return ExprError();
1561     break;
1562   case Builtin::BI_setjmp:
1563   case Builtin::BI_setjmpex:
1564     if (checkArgCount(*this, TheCall, 1))
1565       return true;
1566     break;
1567   case Builtin::BI__builtin_classify_type:
1568     if (checkArgCount(*this, TheCall, 1)) return true;
1569     TheCall->setType(Context.IntTy);
1570     break;
1571   case Builtin::BI__builtin_constant_p: {
1572     if (checkArgCount(*this, TheCall, 1)) return true;
1573     ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1574     if (Arg.isInvalid()) return true;
1575     TheCall->setArg(0, Arg.get());
1576     TheCall->setType(Context.IntTy);
1577     break;
1578   }
1579   case Builtin::BI__builtin_launder:
1580     return SemaBuiltinLaunder(*this, TheCall);
1581   case Builtin::BI__sync_fetch_and_add:
1582   case Builtin::BI__sync_fetch_and_add_1:
1583   case Builtin::BI__sync_fetch_and_add_2:
1584   case Builtin::BI__sync_fetch_and_add_4:
1585   case Builtin::BI__sync_fetch_and_add_8:
1586   case Builtin::BI__sync_fetch_and_add_16:
1587   case Builtin::BI__sync_fetch_and_sub:
1588   case Builtin::BI__sync_fetch_and_sub_1:
1589   case Builtin::BI__sync_fetch_and_sub_2:
1590   case Builtin::BI__sync_fetch_and_sub_4:
1591   case Builtin::BI__sync_fetch_and_sub_8:
1592   case Builtin::BI__sync_fetch_and_sub_16:
1593   case Builtin::BI__sync_fetch_and_or:
1594   case Builtin::BI__sync_fetch_and_or_1:
1595   case Builtin::BI__sync_fetch_and_or_2:
1596   case Builtin::BI__sync_fetch_and_or_4:
1597   case Builtin::BI__sync_fetch_and_or_8:
1598   case Builtin::BI__sync_fetch_and_or_16:
1599   case Builtin::BI__sync_fetch_and_and:
1600   case Builtin::BI__sync_fetch_and_and_1:
1601   case Builtin::BI__sync_fetch_and_and_2:
1602   case Builtin::BI__sync_fetch_and_and_4:
1603   case Builtin::BI__sync_fetch_and_and_8:
1604   case Builtin::BI__sync_fetch_and_and_16:
1605   case Builtin::BI__sync_fetch_and_xor:
1606   case Builtin::BI__sync_fetch_and_xor_1:
1607   case Builtin::BI__sync_fetch_and_xor_2:
1608   case Builtin::BI__sync_fetch_and_xor_4:
1609   case Builtin::BI__sync_fetch_and_xor_8:
1610   case Builtin::BI__sync_fetch_and_xor_16:
1611   case Builtin::BI__sync_fetch_and_nand:
1612   case Builtin::BI__sync_fetch_and_nand_1:
1613   case Builtin::BI__sync_fetch_and_nand_2:
1614   case Builtin::BI__sync_fetch_and_nand_4:
1615   case Builtin::BI__sync_fetch_and_nand_8:
1616   case Builtin::BI__sync_fetch_and_nand_16:
1617   case Builtin::BI__sync_add_and_fetch:
1618   case Builtin::BI__sync_add_and_fetch_1:
1619   case Builtin::BI__sync_add_and_fetch_2:
1620   case Builtin::BI__sync_add_and_fetch_4:
1621   case Builtin::BI__sync_add_and_fetch_8:
1622   case Builtin::BI__sync_add_and_fetch_16:
1623   case Builtin::BI__sync_sub_and_fetch:
1624   case Builtin::BI__sync_sub_and_fetch_1:
1625   case Builtin::BI__sync_sub_and_fetch_2:
1626   case Builtin::BI__sync_sub_and_fetch_4:
1627   case Builtin::BI__sync_sub_and_fetch_8:
1628   case Builtin::BI__sync_sub_and_fetch_16:
1629   case Builtin::BI__sync_and_and_fetch:
1630   case Builtin::BI__sync_and_and_fetch_1:
1631   case Builtin::BI__sync_and_and_fetch_2:
1632   case Builtin::BI__sync_and_and_fetch_4:
1633   case Builtin::BI__sync_and_and_fetch_8:
1634   case Builtin::BI__sync_and_and_fetch_16:
1635   case Builtin::BI__sync_or_and_fetch:
1636   case Builtin::BI__sync_or_and_fetch_1:
1637   case Builtin::BI__sync_or_and_fetch_2:
1638   case Builtin::BI__sync_or_and_fetch_4:
1639   case Builtin::BI__sync_or_and_fetch_8:
1640   case Builtin::BI__sync_or_and_fetch_16:
1641   case Builtin::BI__sync_xor_and_fetch:
1642   case Builtin::BI__sync_xor_and_fetch_1:
1643   case Builtin::BI__sync_xor_and_fetch_2:
1644   case Builtin::BI__sync_xor_and_fetch_4:
1645   case Builtin::BI__sync_xor_and_fetch_8:
1646   case Builtin::BI__sync_xor_and_fetch_16:
1647   case Builtin::BI__sync_nand_and_fetch:
1648   case Builtin::BI__sync_nand_and_fetch_1:
1649   case Builtin::BI__sync_nand_and_fetch_2:
1650   case Builtin::BI__sync_nand_and_fetch_4:
1651   case Builtin::BI__sync_nand_and_fetch_8:
1652   case Builtin::BI__sync_nand_and_fetch_16:
1653   case Builtin::BI__sync_val_compare_and_swap:
1654   case Builtin::BI__sync_val_compare_and_swap_1:
1655   case Builtin::BI__sync_val_compare_and_swap_2:
1656   case Builtin::BI__sync_val_compare_and_swap_4:
1657   case Builtin::BI__sync_val_compare_and_swap_8:
1658   case Builtin::BI__sync_val_compare_and_swap_16:
1659   case Builtin::BI__sync_bool_compare_and_swap:
1660   case Builtin::BI__sync_bool_compare_and_swap_1:
1661   case Builtin::BI__sync_bool_compare_and_swap_2:
1662   case Builtin::BI__sync_bool_compare_and_swap_4:
1663   case Builtin::BI__sync_bool_compare_and_swap_8:
1664   case Builtin::BI__sync_bool_compare_and_swap_16:
1665   case Builtin::BI__sync_lock_test_and_set:
1666   case Builtin::BI__sync_lock_test_and_set_1:
1667   case Builtin::BI__sync_lock_test_and_set_2:
1668   case Builtin::BI__sync_lock_test_and_set_4:
1669   case Builtin::BI__sync_lock_test_and_set_8:
1670   case Builtin::BI__sync_lock_test_and_set_16:
1671   case Builtin::BI__sync_lock_release:
1672   case Builtin::BI__sync_lock_release_1:
1673   case Builtin::BI__sync_lock_release_2:
1674   case Builtin::BI__sync_lock_release_4:
1675   case Builtin::BI__sync_lock_release_8:
1676   case Builtin::BI__sync_lock_release_16:
1677   case Builtin::BI__sync_swap:
1678   case Builtin::BI__sync_swap_1:
1679   case Builtin::BI__sync_swap_2:
1680   case Builtin::BI__sync_swap_4:
1681   case Builtin::BI__sync_swap_8:
1682   case Builtin::BI__sync_swap_16:
1683     return SemaBuiltinAtomicOverloaded(TheCallResult);
1684   case Builtin::BI__sync_synchronize:
1685     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1686         << TheCall->getCallee()->getSourceRange();
1687     break;
1688   case Builtin::BI__builtin_nontemporal_load:
1689   case Builtin::BI__builtin_nontemporal_store:
1690     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1691   case Builtin::BI__builtin_memcpy_inline: {
1692     clang::Expr *SizeOp = TheCall->getArg(2);
1693     // We warn about copying to or from `nullptr` pointers when `size` is
1694     // greater than 0. When `size` is value dependent we cannot evaluate its
1695     // value so we bail out.
1696     if (SizeOp->isValueDependent())
1697       break;
1698     if (!SizeOp->EvaluateKnownConstInt(Context).isNullValue()) {
1699       CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
1700       CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
1701     }
1702     break;
1703   }
1704 #define BUILTIN(ID, TYPE, ATTRS)
1705 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1706   case Builtin::BI##ID: \
1707     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1708 #include "clang/Basic/Builtins.def"
1709   case Builtin::BI__annotation:
1710     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1711       return ExprError();
1712     break;
1713   case Builtin::BI__builtin_annotation:
1714     if (SemaBuiltinAnnotation(*this, TheCall))
1715       return ExprError();
1716     break;
1717   case Builtin::BI__builtin_addressof:
1718     if (SemaBuiltinAddressof(*this, TheCall))
1719       return ExprError();
1720     break;
1721   case Builtin::BI__builtin_is_aligned:
1722   case Builtin::BI__builtin_align_up:
1723   case Builtin::BI__builtin_align_down:
1724     if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
1725       return ExprError();
1726     break;
1727   case Builtin::BI__builtin_add_overflow:
1728   case Builtin::BI__builtin_sub_overflow:
1729   case Builtin::BI__builtin_mul_overflow:
1730     if (SemaBuiltinOverflow(*this, TheCall))
1731       return ExprError();
1732     break;
1733   case Builtin::BI__builtin_operator_new:
1734   case Builtin::BI__builtin_operator_delete: {
1735     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1736     ExprResult Res =
1737         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1738     if (Res.isInvalid())
1739       CorrectDelayedTyposInExpr(TheCallResult.get());
1740     return Res;
1741   }
1742   case Builtin::BI__builtin_dump_struct: {
1743     // We first want to ensure we are called with 2 arguments
1744     if (checkArgCount(*this, TheCall, 2))
1745       return ExprError();
1746     // Ensure that the first argument is of type 'struct XX *'
1747     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1748     const QualType PtrArgType = PtrArg->getType();
1749     if (!PtrArgType->isPointerType() ||
1750         !PtrArgType->getPointeeType()->isRecordType()) {
1751       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1752           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1753           << "structure pointer";
1754       return ExprError();
1755     }
1756 
1757     // Ensure that the second argument is of type 'FunctionType'
1758     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1759     const QualType FnPtrArgType = FnPtrArg->getType();
1760     if (!FnPtrArgType->isPointerType()) {
1761       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1762           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1763           << FnPtrArgType << "'int (*)(const char *, ...)'";
1764       return ExprError();
1765     }
1766 
1767     const auto *FuncType =
1768         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1769 
1770     if (!FuncType) {
1771       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1772           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1773           << FnPtrArgType << "'int (*)(const char *, ...)'";
1774       return ExprError();
1775     }
1776 
1777     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1778       if (!FT->getNumParams()) {
1779         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1780             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1781             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1782         return ExprError();
1783       }
1784       QualType PT = FT->getParamType(0);
1785       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1786           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1787           !PT->getPointeeType().isConstQualified()) {
1788         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1789             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1790             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1791         return ExprError();
1792       }
1793     }
1794 
1795     TheCall->setType(Context.IntTy);
1796     break;
1797   }
1798   case Builtin::BI__builtin_preserve_access_index:
1799     if (SemaBuiltinPreserveAI(*this, TheCall))
1800       return ExprError();
1801     break;
1802   case Builtin::BI__builtin_call_with_static_chain:
1803     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1804       return ExprError();
1805     break;
1806   case Builtin::BI__exception_code:
1807   case Builtin::BI_exception_code:
1808     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1809                                  diag::err_seh___except_block))
1810       return ExprError();
1811     break;
1812   case Builtin::BI__exception_info:
1813   case Builtin::BI_exception_info:
1814     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1815                                  diag::err_seh___except_filter))
1816       return ExprError();
1817     break;
1818   case Builtin::BI__GetExceptionInfo:
1819     if (checkArgCount(*this, TheCall, 1))
1820       return ExprError();
1821 
1822     if (CheckCXXThrowOperand(
1823             TheCall->getBeginLoc(),
1824             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1825             TheCall))
1826       return ExprError();
1827 
1828     TheCall->setType(Context.VoidPtrTy);
1829     break;
1830   // OpenCL v2.0, s6.13.16 - Pipe functions
1831   case Builtin::BIread_pipe:
1832   case Builtin::BIwrite_pipe:
1833     // Since those two functions are declared with var args, we need a semantic
1834     // check for the argument.
1835     if (SemaBuiltinRWPipe(*this, TheCall))
1836       return ExprError();
1837     break;
1838   case Builtin::BIreserve_read_pipe:
1839   case Builtin::BIreserve_write_pipe:
1840   case Builtin::BIwork_group_reserve_read_pipe:
1841   case Builtin::BIwork_group_reserve_write_pipe:
1842     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1843       return ExprError();
1844     break;
1845   case Builtin::BIsub_group_reserve_read_pipe:
1846   case Builtin::BIsub_group_reserve_write_pipe:
1847     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1848         SemaBuiltinReserveRWPipe(*this, TheCall))
1849       return ExprError();
1850     break;
1851   case Builtin::BIcommit_read_pipe:
1852   case Builtin::BIcommit_write_pipe:
1853   case Builtin::BIwork_group_commit_read_pipe:
1854   case Builtin::BIwork_group_commit_write_pipe:
1855     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1856       return ExprError();
1857     break;
1858   case Builtin::BIsub_group_commit_read_pipe:
1859   case Builtin::BIsub_group_commit_write_pipe:
1860     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1861         SemaBuiltinCommitRWPipe(*this, TheCall))
1862       return ExprError();
1863     break;
1864   case Builtin::BIget_pipe_num_packets:
1865   case Builtin::BIget_pipe_max_packets:
1866     if (SemaBuiltinPipePackets(*this, TheCall))
1867       return ExprError();
1868     break;
1869   case Builtin::BIto_global:
1870   case Builtin::BIto_local:
1871   case Builtin::BIto_private:
1872     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1873       return ExprError();
1874     break;
1875   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1876   case Builtin::BIenqueue_kernel:
1877     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1878       return ExprError();
1879     break;
1880   case Builtin::BIget_kernel_work_group_size:
1881   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1882     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1883       return ExprError();
1884     break;
1885   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1886   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1887     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1888       return ExprError();
1889     break;
1890   case Builtin::BI__builtin_os_log_format:
1891     Cleanup.setExprNeedsCleanups(true);
1892     LLVM_FALLTHROUGH;
1893   case Builtin::BI__builtin_os_log_format_buffer_size:
1894     if (SemaBuiltinOSLogFormat(TheCall))
1895       return ExprError();
1896     break;
1897   case Builtin::BI__builtin_frame_address:
1898   case Builtin::BI__builtin_return_address:
1899     if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
1900       return ExprError();
1901 
1902     // -Wframe-address warning if non-zero passed to builtin
1903     // return/frame address.
1904     Expr::EvalResult Result;
1905     if (TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
1906         Result.Val.getInt() != 0)
1907       Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
1908           << ((BuiltinID == Builtin::BI__builtin_return_address)
1909                   ? "__builtin_return_address"
1910                   : "__builtin_frame_address")
1911           << TheCall->getSourceRange();
1912     break;
1913   }
1914 
1915   // Since the target specific builtins for each arch overlap, only check those
1916   // of the arch we are compiling for.
1917   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1918     if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
1919       assert(Context.getAuxTargetInfo() &&
1920              "Aux Target Builtin, but not an aux target?");
1921 
1922       if (CheckTSBuiltinFunctionCall(
1923               Context.getAuxTargetInfo()->getTriple().getArch(),
1924               Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
1925         return ExprError();
1926     } else {
1927       if (CheckTSBuiltinFunctionCall(
1928               Context.getTargetInfo().getTriple().getArch(), BuiltinID,
1929               TheCall))
1930         return ExprError();
1931     }
1932   }
1933 
1934   return TheCallResult;
1935 }
1936 
1937 // Get the valid immediate range for the specified NEON type code.
1938 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1939   NeonTypeFlags Type(t);
1940   int IsQuad = ForceQuad ? true : Type.isQuad();
1941   switch (Type.getEltType()) {
1942   case NeonTypeFlags::Int8:
1943   case NeonTypeFlags::Poly8:
1944     return shift ? 7 : (8 << IsQuad) - 1;
1945   case NeonTypeFlags::Int16:
1946   case NeonTypeFlags::Poly16:
1947     return shift ? 15 : (4 << IsQuad) - 1;
1948   case NeonTypeFlags::Int32:
1949     return shift ? 31 : (2 << IsQuad) - 1;
1950   case NeonTypeFlags::Int64:
1951   case NeonTypeFlags::Poly64:
1952     return shift ? 63 : (1 << IsQuad) - 1;
1953   case NeonTypeFlags::Poly128:
1954     return shift ? 127 : (1 << IsQuad) - 1;
1955   case NeonTypeFlags::Float16:
1956     assert(!shift && "cannot shift float types!");
1957     return (4 << IsQuad) - 1;
1958   case NeonTypeFlags::Float32:
1959     assert(!shift && "cannot shift float types!");
1960     return (2 << IsQuad) - 1;
1961   case NeonTypeFlags::Float64:
1962     assert(!shift && "cannot shift float types!");
1963     return (1 << IsQuad) - 1;
1964   }
1965   llvm_unreachable("Invalid NeonTypeFlag!");
1966 }
1967 
1968 /// getNeonEltType - Return the QualType corresponding to the elements of
1969 /// the vector type specified by the NeonTypeFlags.  This is used to check
1970 /// the pointer arguments for Neon load/store intrinsics.
1971 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
1972                                bool IsPolyUnsigned, bool IsInt64Long) {
1973   switch (Flags.getEltType()) {
1974   case NeonTypeFlags::Int8:
1975     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1976   case NeonTypeFlags::Int16:
1977     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1978   case NeonTypeFlags::Int32:
1979     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1980   case NeonTypeFlags::Int64:
1981     if (IsInt64Long)
1982       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1983     else
1984       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1985                                 : Context.LongLongTy;
1986   case NeonTypeFlags::Poly8:
1987     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
1988   case NeonTypeFlags::Poly16:
1989     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
1990   case NeonTypeFlags::Poly64:
1991     if (IsInt64Long)
1992       return Context.UnsignedLongTy;
1993     else
1994       return Context.UnsignedLongLongTy;
1995   case NeonTypeFlags::Poly128:
1996     break;
1997   case NeonTypeFlags::Float16:
1998     return Context.HalfTy;
1999   case NeonTypeFlags::Float32:
2000     return Context.FloatTy;
2001   case NeonTypeFlags::Float64:
2002     return Context.DoubleTy;
2003   }
2004   llvm_unreachable("Invalid NeonTypeFlag!");
2005 }
2006 
2007 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2008   // Range check SVE intrinsics that take immediate values.
2009   SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
2010 
2011   switch (BuiltinID) {
2012   default:
2013     return false;
2014 #define GET_SVE_IMMEDIATE_CHECK
2015 #include "clang/Basic/arm_sve_sema_rangechecks.inc"
2016 #undef GET_SVE_IMMEDIATE_CHECK
2017   }
2018 
2019   // Perform all the immediate checks for this builtin call.
2020   bool HasError = false;
2021   for (auto &I : ImmChecks) {
2022     int ArgNum, CheckTy, ElementSizeInBits;
2023     std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
2024 
2025     typedef bool(*OptionSetCheckFnTy)(int64_t Value);
2026 
2027     // Function that checks whether the operand (ArgNum) is an immediate
2028     // that is one of the predefined values.
2029     auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
2030                                    int ErrDiag) -> bool {
2031       // We can't check the value of a dependent argument.
2032       Expr *Arg = TheCall->getArg(ArgNum);
2033       if (Arg->isTypeDependent() || Arg->isValueDependent())
2034         return false;
2035 
2036       // Check constant-ness first.
2037       llvm::APSInt Imm;
2038       if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
2039         return true;
2040 
2041       if (!CheckImm(Imm.getSExtValue()))
2042         return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
2043       return false;
2044     };
2045 
2046     switch ((SVETypeFlags::ImmCheckType)CheckTy) {
2047     case SVETypeFlags::ImmCheck0_31:
2048       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
2049         HasError = true;
2050       break;
2051     case SVETypeFlags::ImmCheck0_13:
2052       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
2053         HasError = true;
2054       break;
2055     case SVETypeFlags::ImmCheck1_16:
2056       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
2057         HasError = true;
2058       break;
2059     case SVETypeFlags::ImmCheck0_7:
2060       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
2061         HasError = true;
2062       break;
2063     case SVETypeFlags::ImmCheckExtract:
2064       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2065                                       (2048 / ElementSizeInBits) - 1))
2066         HasError = true;
2067       break;
2068     case SVETypeFlags::ImmCheckShiftRight:
2069       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
2070         HasError = true;
2071       break;
2072     case SVETypeFlags::ImmCheckShiftRightNarrow:
2073       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
2074                                       ElementSizeInBits / 2))
2075         HasError = true;
2076       break;
2077     case SVETypeFlags::ImmCheckShiftLeft:
2078       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2079                                       ElementSizeInBits - 1))
2080         HasError = true;
2081       break;
2082     case SVETypeFlags::ImmCheckLaneIndex:
2083       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2084                                       (128 / (1 * ElementSizeInBits)) - 1))
2085         HasError = true;
2086       break;
2087     case SVETypeFlags::ImmCheckLaneIndexCompRotate:
2088       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2089                                       (128 / (2 * ElementSizeInBits)) - 1))
2090         HasError = true;
2091       break;
2092     case SVETypeFlags::ImmCheckLaneIndexDot:
2093       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2094                                       (128 / (4 * ElementSizeInBits)) - 1))
2095         HasError = true;
2096       break;
2097     case SVETypeFlags::ImmCheckComplexRot90_270:
2098       if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
2099                               diag::err_rotation_argument_to_cadd))
2100         HasError = true;
2101       break;
2102     case SVETypeFlags::ImmCheckComplexRotAll90:
2103       if (CheckImmediateInSet(
2104               [](int64_t V) {
2105                 return V == 0 || V == 90 || V == 180 || V == 270;
2106               },
2107               diag::err_rotation_argument_to_cmla))
2108         HasError = true;
2109       break;
2110     }
2111   }
2112 
2113   return HasError;
2114 }
2115 
2116 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2117   llvm::APSInt Result;
2118   uint64_t mask = 0;
2119   unsigned TV = 0;
2120   int PtrArgNum = -1;
2121   bool HasConstPtr = false;
2122   switch (BuiltinID) {
2123 #define GET_NEON_OVERLOAD_CHECK
2124 #include "clang/Basic/arm_neon.inc"
2125 #include "clang/Basic/arm_fp16.inc"
2126 #undef GET_NEON_OVERLOAD_CHECK
2127   }
2128 
2129   // For NEON intrinsics which are overloaded on vector element type, validate
2130   // the immediate which specifies which variant to emit.
2131   unsigned ImmArg = TheCall->getNumArgs()-1;
2132   if (mask) {
2133     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
2134       return true;
2135 
2136     TV = Result.getLimitedValue(64);
2137     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
2138       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
2139              << TheCall->getArg(ImmArg)->getSourceRange();
2140   }
2141 
2142   if (PtrArgNum >= 0) {
2143     // Check that pointer arguments have the specified type.
2144     Expr *Arg = TheCall->getArg(PtrArgNum);
2145     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
2146       Arg = ICE->getSubExpr();
2147     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
2148     QualType RHSTy = RHS.get()->getType();
2149 
2150     llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
2151     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2152                           Arch == llvm::Triple::aarch64_32 ||
2153                           Arch == llvm::Triple::aarch64_be;
2154     bool IsInt64Long =
2155         Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
2156     QualType EltTy =
2157         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2158     if (HasConstPtr)
2159       EltTy = EltTy.withConst();
2160     QualType LHSTy = Context.getPointerType(EltTy);
2161     AssignConvertType ConvTy;
2162     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2163     if (RHS.isInvalid())
2164       return true;
2165     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2166                                  RHS.get(), AA_Assigning))
2167       return true;
2168   }
2169 
2170   // For NEON intrinsics which take an immediate value as part of the
2171   // instruction, range check them here.
2172   unsigned i = 0, l = 0, u = 0;
2173   switch (BuiltinID) {
2174   default:
2175     return false;
2176   #define GET_NEON_IMMEDIATE_CHECK
2177   #include "clang/Basic/arm_neon.inc"
2178   #include "clang/Basic/arm_fp16.inc"
2179   #undef GET_NEON_IMMEDIATE_CHECK
2180   }
2181 
2182   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2183 }
2184 
2185 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2186   switch (BuiltinID) {
2187   default:
2188     return false;
2189   #include "clang/Basic/arm_mve_builtin_sema.inc"
2190   }
2191 }
2192 
2193 bool Sema::CheckCDEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2194   bool Err = false;
2195   switch (BuiltinID) {
2196   default:
2197     return false;
2198 #include "clang/Basic/arm_cde_builtin_sema.inc"
2199   }
2200 
2201   if (Err)
2202     return true;
2203 
2204   return CheckARMCoprocessorImmediate(TheCall->getArg(0), /*WantCDE*/ true);
2205 }
2206 
2207 bool Sema::CheckARMCoprocessorImmediate(const Expr *CoprocArg, bool WantCDE) {
2208   if (isConstantEvaluated())
2209     return false;
2210 
2211   // We can't check the value of a dependent argument.
2212   if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
2213     return false;
2214 
2215   llvm::APSInt CoprocNoAP;
2216   bool IsICE = CoprocArg->isIntegerConstantExpr(CoprocNoAP, Context);
2217   (void)IsICE;
2218   assert(IsICE && "Coprocossor immediate is not a constant expression");
2219   int64_t CoprocNo = CoprocNoAP.getExtValue();
2220   assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
2221 
2222   uint32_t CDECoprocMask = Context.getTargetInfo().getARMCDECoprocMask();
2223   bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
2224 
2225   if (IsCDECoproc != WantCDE)
2226     return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
2227            << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
2228 
2229   return false;
2230 }
2231 
2232 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2233                                         unsigned MaxWidth) {
2234   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
2235           BuiltinID == ARM::BI__builtin_arm_ldaex ||
2236           BuiltinID == ARM::BI__builtin_arm_strex ||
2237           BuiltinID == ARM::BI__builtin_arm_stlex ||
2238           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2239           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2240           BuiltinID == AArch64::BI__builtin_arm_strex ||
2241           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
2242          "unexpected ARM builtin");
2243   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2244                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
2245                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2246                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
2247 
2248   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2249 
2250   // Ensure that we have the proper number of arguments.
2251   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
2252     return true;
2253 
2254   // Inspect the pointer argument of the atomic builtin.  This should always be
2255   // a pointer type, whose element is an integral scalar or pointer type.
2256   // Because it is a pointer type, we don't have to worry about any implicit
2257   // casts here.
2258   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
2259   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
2260   if (PointerArgRes.isInvalid())
2261     return true;
2262   PointerArg = PointerArgRes.get();
2263 
2264   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2265   if (!pointerType) {
2266     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
2267         << PointerArg->getType() << PointerArg->getSourceRange();
2268     return true;
2269   }
2270 
2271   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
2272   // task is to insert the appropriate casts into the AST. First work out just
2273   // what the appropriate type is.
2274   QualType ValType = pointerType->getPointeeType();
2275   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
2276   if (IsLdrex)
2277     AddrType.addConst();
2278 
2279   // Issue a warning if the cast is dodgy.
2280   CastKind CastNeeded = CK_NoOp;
2281   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
2282     CastNeeded = CK_BitCast;
2283     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
2284         << PointerArg->getType() << Context.getPointerType(AddrType)
2285         << AA_Passing << PointerArg->getSourceRange();
2286   }
2287 
2288   // Finally, do the cast and replace the argument with the corrected version.
2289   AddrType = Context.getPointerType(AddrType);
2290   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
2291   if (PointerArgRes.isInvalid())
2292     return true;
2293   PointerArg = PointerArgRes.get();
2294 
2295   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
2296 
2297   // In general, we allow ints, floats and pointers to be loaded and stored.
2298   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2299       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
2300     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
2301         << PointerArg->getType() << PointerArg->getSourceRange();
2302     return true;
2303   }
2304 
2305   // But ARM doesn't have instructions to deal with 128-bit versions.
2306   if (Context.getTypeSize(ValType) > MaxWidth) {
2307     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
2308     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
2309         << PointerArg->getType() << PointerArg->getSourceRange();
2310     return true;
2311   }
2312 
2313   switch (ValType.getObjCLifetime()) {
2314   case Qualifiers::OCL_None:
2315   case Qualifiers::OCL_ExplicitNone:
2316     // okay
2317     break;
2318 
2319   case Qualifiers::OCL_Weak:
2320   case Qualifiers::OCL_Strong:
2321   case Qualifiers::OCL_Autoreleasing:
2322     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
2323         << ValType << PointerArg->getSourceRange();
2324     return true;
2325   }
2326 
2327   if (IsLdrex) {
2328     TheCall->setType(ValType);
2329     return false;
2330   }
2331 
2332   // Initialize the argument to be stored.
2333   ExprResult ValArg = TheCall->getArg(0);
2334   InitializedEntity Entity = InitializedEntity::InitializeParameter(
2335       Context, ValType, /*consume*/ false);
2336   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2337   if (ValArg.isInvalid())
2338     return true;
2339   TheCall->setArg(0, ValArg.get());
2340 
2341   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
2342   // but the custom checker bypasses all default analysis.
2343   TheCall->setType(Context.IntTy);
2344   return false;
2345 }
2346 
2347 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2348   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
2349       BuiltinID == ARM::BI__builtin_arm_ldaex ||
2350       BuiltinID == ARM::BI__builtin_arm_strex ||
2351       BuiltinID == ARM::BI__builtin_arm_stlex) {
2352     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
2353   }
2354 
2355   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
2356     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2357       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
2358   }
2359 
2360   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2361       BuiltinID == ARM::BI__builtin_arm_wsr64)
2362     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
2363 
2364   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
2365       BuiltinID == ARM::BI__builtin_arm_rsrp ||
2366       BuiltinID == ARM::BI__builtin_arm_wsr ||
2367       BuiltinID == ARM::BI__builtin_arm_wsrp)
2368     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2369 
2370   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
2371     return true;
2372   if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
2373     return true;
2374   if (CheckCDEBuiltinFunctionCall(BuiltinID, TheCall))
2375     return true;
2376 
2377   // For intrinsics which take an immediate value as part of the instruction,
2378   // range check them here.
2379   // FIXME: VFP Intrinsics should error if VFP not present.
2380   switch (BuiltinID) {
2381   default: return false;
2382   case ARM::BI__builtin_arm_ssat:
2383     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
2384   case ARM::BI__builtin_arm_usat:
2385     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
2386   case ARM::BI__builtin_arm_ssat16:
2387     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
2388   case ARM::BI__builtin_arm_usat16:
2389     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2390   case ARM::BI__builtin_arm_vcvtr_f:
2391   case ARM::BI__builtin_arm_vcvtr_d:
2392     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2393   case ARM::BI__builtin_arm_dmb:
2394   case ARM::BI__builtin_arm_dsb:
2395   case ARM::BI__builtin_arm_isb:
2396   case ARM::BI__builtin_arm_dbg:
2397     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
2398   case ARM::BI__builtin_arm_cdp:
2399   case ARM::BI__builtin_arm_cdp2:
2400   case ARM::BI__builtin_arm_mcr:
2401   case ARM::BI__builtin_arm_mcr2:
2402   case ARM::BI__builtin_arm_mrc:
2403   case ARM::BI__builtin_arm_mrc2:
2404   case ARM::BI__builtin_arm_mcrr:
2405   case ARM::BI__builtin_arm_mcrr2:
2406   case ARM::BI__builtin_arm_mrrc:
2407   case ARM::BI__builtin_arm_mrrc2:
2408   case ARM::BI__builtin_arm_ldc:
2409   case ARM::BI__builtin_arm_ldcl:
2410   case ARM::BI__builtin_arm_ldc2:
2411   case ARM::BI__builtin_arm_ldc2l:
2412   case ARM::BI__builtin_arm_stc:
2413   case ARM::BI__builtin_arm_stcl:
2414   case ARM::BI__builtin_arm_stc2:
2415   case ARM::BI__builtin_arm_stc2l:
2416     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
2417            CheckARMCoprocessorImmediate(TheCall->getArg(0), /*WantCDE*/ false);
2418   }
2419 }
2420 
2421 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
2422                                          CallExpr *TheCall) {
2423   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2424       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2425       BuiltinID == AArch64::BI__builtin_arm_strex ||
2426       BuiltinID == AArch64::BI__builtin_arm_stlex) {
2427     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
2428   }
2429 
2430   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
2431     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2432       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
2433       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2434       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2435   }
2436 
2437   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2438       BuiltinID == AArch64::BI__builtin_arm_wsr64)
2439     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2440 
2441   // Memory Tagging Extensions (MTE) Intrinsics
2442   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2443       BuiltinID == AArch64::BI__builtin_arm_addg ||
2444       BuiltinID == AArch64::BI__builtin_arm_gmi ||
2445       BuiltinID == AArch64::BI__builtin_arm_ldg ||
2446       BuiltinID == AArch64::BI__builtin_arm_stg ||
2447       BuiltinID == AArch64::BI__builtin_arm_subp) {
2448     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2449   }
2450 
2451   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2452       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2453       BuiltinID == AArch64::BI__builtin_arm_wsr ||
2454       BuiltinID == AArch64::BI__builtin_arm_wsrp)
2455     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2456 
2457   // Only check the valid encoding range. Any constant in this range would be
2458   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2459   // an exception for incorrect registers. This matches MSVC behavior.
2460   if (BuiltinID == AArch64::BI_ReadStatusReg ||
2461       BuiltinID == AArch64::BI_WriteStatusReg)
2462     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2463 
2464   if (BuiltinID == AArch64::BI__getReg)
2465     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2466 
2467   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
2468     return true;
2469 
2470   if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
2471     return true;
2472 
2473   // For intrinsics which take an immediate value as part of the instruction,
2474   // range check them here.
2475   unsigned i = 0, l = 0, u = 0;
2476   switch (BuiltinID) {
2477   default: return false;
2478   case AArch64::BI__builtin_arm_dmb:
2479   case AArch64::BI__builtin_arm_dsb:
2480   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2481   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2482   }
2483 
2484   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2485 }
2486 
2487 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
2488                                        CallExpr *TheCall) {
2489   assert(BuiltinID == BPF::BI__builtin_preserve_field_info &&
2490          "unexpected ARM builtin");
2491 
2492   if (checkArgCount(*this, TheCall, 2))
2493     return true;
2494 
2495   // The first argument needs to be a record field access.
2496   // If it is an array element access, we delay decision
2497   // to BPF backend to check whether the access is a
2498   // field access or not.
2499   Expr *Arg = TheCall->getArg(0);
2500   if (Arg->getType()->getAsPlaceholderType() ||
2501       (Arg->IgnoreParens()->getObjectKind() != OK_BitField &&
2502        !dyn_cast<MemberExpr>(Arg->IgnoreParens()) &&
2503        !dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()))) {
2504     Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_field)
2505         << 1 << Arg->getSourceRange();
2506     return true;
2507   }
2508 
2509   // The second argument needs to be a constant int
2510   llvm::APSInt Value;
2511   if (!TheCall->getArg(1)->isIntegerConstantExpr(Value, Context)) {
2512     Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_const)
2513         << 2 << Arg->getSourceRange();
2514     return true;
2515   }
2516 
2517   TheCall->setType(Context.UnsignedIntTy);
2518   return false;
2519 }
2520 
2521 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2522   struct ArgInfo {
2523     uint8_t OpNum;
2524     bool IsSigned;
2525     uint8_t BitWidth;
2526     uint8_t Align;
2527   };
2528   struct BuiltinInfo {
2529     unsigned BuiltinID;
2530     ArgInfo Infos[2];
2531   };
2532 
2533   static BuiltinInfo Infos[] = {
2534     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2535     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2536     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2537     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  1 }} },
2538     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2539     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2540     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2541     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2542     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2543     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2544     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2545 
2546     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2547     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2548     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2549     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2550     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2551     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2552     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2553     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2554     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2555     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2556     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2557 
2558     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2559     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2560     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2561     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2562     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2563     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2564     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2565     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2566     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2567     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2568     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2569     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2570     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2571     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2572     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2573     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2574     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2575     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2576     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2577     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2578     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2579     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2580     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2581     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2582     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2583     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2584     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2585     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2586     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2587     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2588     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2589     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
2590     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
2591     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
2592     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
2593     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
2594     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
2595     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
2596     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
2597     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
2598     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
2599     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
2600     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
2601     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
2602     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
2603     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
2604     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
2605     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
2606     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
2607     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
2608     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
2609     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2610                                                       {{ 1, false, 6,  0 }} },
2611     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
2612     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
2613     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
2614     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
2615     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
2616     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
2617     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2618                                                       {{ 1, false, 5,  0 }} },
2619     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
2620     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
2621     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
2622     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
2623     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
2624     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
2625                                                        { 2, false, 5,  0 }} },
2626     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
2627                                                        { 2, false, 6,  0 }} },
2628     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
2629                                                        { 3, false, 5,  0 }} },
2630     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
2631                                                        { 3, false, 6,  0 }} },
2632     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
2633     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
2634     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
2635     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
2636     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
2637     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
2638     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
2639     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
2640     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
2641     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
2642     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
2643     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
2644     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
2645     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
2646     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
2647     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2648                                                       {{ 2, false, 4,  0 },
2649                                                        { 3, false, 5,  0 }} },
2650     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2651                                                       {{ 2, false, 4,  0 },
2652                                                        { 3, false, 5,  0 }} },
2653     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2654                                                       {{ 2, false, 4,  0 },
2655                                                        { 3, false, 5,  0 }} },
2656     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2657                                                       {{ 2, false, 4,  0 },
2658                                                        { 3, false, 5,  0 }} },
2659     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
2660     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
2661     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
2662     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
2663     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
2664     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
2665     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
2666     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
2667     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
2668     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
2669     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
2670                                                        { 2, false, 5,  0 }} },
2671     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
2672                                                        { 2, false, 6,  0 }} },
2673     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
2674     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
2675     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
2676     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
2677     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
2678     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
2679     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
2680     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
2681     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2682                                                       {{ 1, false, 4,  0 }} },
2683     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
2684     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2685                                                       {{ 1, false, 4,  0 }} },
2686     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
2687     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
2688     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
2689     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
2690     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
2691     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
2692     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
2693     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
2694     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
2695     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
2696     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
2697     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
2698     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
2699     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
2700     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
2701     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
2702     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
2703     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
2704     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
2705     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2706                                                       {{ 3, false, 1,  0 }} },
2707     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
2708     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
2709     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
2710     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2711                                                       {{ 3, false, 1,  0 }} },
2712     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
2713     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
2714     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
2715     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2716                                                       {{ 3, false, 1,  0 }} },
2717   };
2718 
2719   // Use a dynamically initialized static to sort the table exactly once on
2720   // first run.
2721   static const bool SortOnce =
2722       (llvm::sort(Infos,
2723                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
2724                    return LHS.BuiltinID < RHS.BuiltinID;
2725                  }),
2726        true);
2727   (void)SortOnce;
2728 
2729   const BuiltinInfo *F = llvm::partition_point(
2730       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
2731   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
2732     return false;
2733 
2734   bool Error = false;
2735 
2736   for (const ArgInfo &A : F->Infos) {
2737     // Ignore empty ArgInfo elements.
2738     if (A.BitWidth == 0)
2739       continue;
2740 
2741     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
2742     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
2743     if (!A.Align) {
2744       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2745     } else {
2746       unsigned M = 1 << A.Align;
2747       Min *= M;
2748       Max *= M;
2749       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
2750                SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
2751     }
2752   }
2753   return Error;
2754 }
2755 
2756 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
2757                                            CallExpr *TheCall) {
2758   return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
2759 }
2760 
2761 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2762   return CheckMipsBuiltinCpu(BuiltinID, TheCall) ||
2763          CheckMipsBuiltinArgument(BuiltinID, TheCall);
2764 }
2765 
2766 bool Sema::CheckMipsBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) {
2767   const TargetInfo &TI = Context.getTargetInfo();
2768 
2769   if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
2770       BuiltinID <= Mips::BI__builtin_mips_lwx) {
2771     if (!TI.hasFeature("dsp"))
2772       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
2773   }
2774 
2775   if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
2776       BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
2777     if (!TI.hasFeature("dspr2"))
2778       return Diag(TheCall->getBeginLoc(),
2779                   diag::err_mips_builtin_requires_dspr2);
2780   }
2781 
2782   if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
2783       BuiltinID <= Mips::BI__builtin_msa_xori_b) {
2784     if (!TI.hasFeature("msa"))
2785       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
2786   }
2787 
2788   return false;
2789 }
2790 
2791 // CheckMipsBuiltinArgument - Checks the constant value passed to the
2792 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
2793 // ordering for DSP is unspecified. MSA is ordered by the data format used
2794 // by the underlying instruction i.e., df/m, df/n and then by size.
2795 //
2796 // FIXME: The size tests here should instead be tablegen'd along with the
2797 //        definitions from include/clang/Basic/BuiltinsMips.def.
2798 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
2799 //        be too.
2800 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2801   unsigned i = 0, l = 0, u = 0, m = 0;
2802   switch (BuiltinID) {
2803   default: return false;
2804   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
2805   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
2806   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
2807   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
2808   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
2809   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
2810   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
2811   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
2812   // df/m field.
2813   // These intrinsics take an unsigned 3 bit immediate.
2814   case Mips::BI__builtin_msa_bclri_b:
2815   case Mips::BI__builtin_msa_bnegi_b:
2816   case Mips::BI__builtin_msa_bseti_b:
2817   case Mips::BI__builtin_msa_sat_s_b:
2818   case Mips::BI__builtin_msa_sat_u_b:
2819   case Mips::BI__builtin_msa_slli_b:
2820   case Mips::BI__builtin_msa_srai_b:
2821   case Mips::BI__builtin_msa_srari_b:
2822   case Mips::BI__builtin_msa_srli_b:
2823   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
2824   case Mips::BI__builtin_msa_binsli_b:
2825   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
2826   // These intrinsics take an unsigned 4 bit immediate.
2827   case Mips::BI__builtin_msa_bclri_h:
2828   case Mips::BI__builtin_msa_bnegi_h:
2829   case Mips::BI__builtin_msa_bseti_h:
2830   case Mips::BI__builtin_msa_sat_s_h:
2831   case Mips::BI__builtin_msa_sat_u_h:
2832   case Mips::BI__builtin_msa_slli_h:
2833   case Mips::BI__builtin_msa_srai_h:
2834   case Mips::BI__builtin_msa_srari_h:
2835   case Mips::BI__builtin_msa_srli_h:
2836   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
2837   case Mips::BI__builtin_msa_binsli_h:
2838   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
2839   // These intrinsics take an unsigned 5 bit immediate.
2840   // The first block of intrinsics actually have an unsigned 5 bit field,
2841   // not a df/n field.
2842   case Mips::BI__builtin_msa_cfcmsa:
2843   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
2844   case Mips::BI__builtin_msa_clei_u_b:
2845   case Mips::BI__builtin_msa_clei_u_h:
2846   case Mips::BI__builtin_msa_clei_u_w:
2847   case Mips::BI__builtin_msa_clei_u_d:
2848   case Mips::BI__builtin_msa_clti_u_b:
2849   case Mips::BI__builtin_msa_clti_u_h:
2850   case Mips::BI__builtin_msa_clti_u_w:
2851   case Mips::BI__builtin_msa_clti_u_d:
2852   case Mips::BI__builtin_msa_maxi_u_b:
2853   case Mips::BI__builtin_msa_maxi_u_h:
2854   case Mips::BI__builtin_msa_maxi_u_w:
2855   case Mips::BI__builtin_msa_maxi_u_d:
2856   case Mips::BI__builtin_msa_mini_u_b:
2857   case Mips::BI__builtin_msa_mini_u_h:
2858   case Mips::BI__builtin_msa_mini_u_w:
2859   case Mips::BI__builtin_msa_mini_u_d:
2860   case Mips::BI__builtin_msa_addvi_b:
2861   case Mips::BI__builtin_msa_addvi_h:
2862   case Mips::BI__builtin_msa_addvi_w:
2863   case Mips::BI__builtin_msa_addvi_d:
2864   case Mips::BI__builtin_msa_bclri_w:
2865   case Mips::BI__builtin_msa_bnegi_w:
2866   case Mips::BI__builtin_msa_bseti_w:
2867   case Mips::BI__builtin_msa_sat_s_w:
2868   case Mips::BI__builtin_msa_sat_u_w:
2869   case Mips::BI__builtin_msa_slli_w:
2870   case Mips::BI__builtin_msa_srai_w:
2871   case Mips::BI__builtin_msa_srari_w:
2872   case Mips::BI__builtin_msa_srli_w:
2873   case Mips::BI__builtin_msa_srlri_w:
2874   case Mips::BI__builtin_msa_subvi_b:
2875   case Mips::BI__builtin_msa_subvi_h:
2876   case Mips::BI__builtin_msa_subvi_w:
2877   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
2878   case Mips::BI__builtin_msa_binsli_w:
2879   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
2880   // These intrinsics take an unsigned 6 bit immediate.
2881   case Mips::BI__builtin_msa_bclri_d:
2882   case Mips::BI__builtin_msa_bnegi_d:
2883   case Mips::BI__builtin_msa_bseti_d:
2884   case Mips::BI__builtin_msa_sat_s_d:
2885   case Mips::BI__builtin_msa_sat_u_d:
2886   case Mips::BI__builtin_msa_slli_d:
2887   case Mips::BI__builtin_msa_srai_d:
2888   case Mips::BI__builtin_msa_srari_d:
2889   case Mips::BI__builtin_msa_srli_d:
2890   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
2891   case Mips::BI__builtin_msa_binsli_d:
2892   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
2893   // These intrinsics take a signed 5 bit immediate.
2894   case Mips::BI__builtin_msa_ceqi_b:
2895   case Mips::BI__builtin_msa_ceqi_h:
2896   case Mips::BI__builtin_msa_ceqi_w:
2897   case Mips::BI__builtin_msa_ceqi_d:
2898   case Mips::BI__builtin_msa_clti_s_b:
2899   case Mips::BI__builtin_msa_clti_s_h:
2900   case Mips::BI__builtin_msa_clti_s_w:
2901   case Mips::BI__builtin_msa_clti_s_d:
2902   case Mips::BI__builtin_msa_clei_s_b:
2903   case Mips::BI__builtin_msa_clei_s_h:
2904   case Mips::BI__builtin_msa_clei_s_w:
2905   case Mips::BI__builtin_msa_clei_s_d:
2906   case Mips::BI__builtin_msa_maxi_s_b:
2907   case Mips::BI__builtin_msa_maxi_s_h:
2908   case Mips::BI__builtin_msa_maxi_s_w:
2909   case Mips::BI__builtin_msa_maxi_s_d:
2910   case Mips::BI__builtin_msa_mini_s_b:
2911   case Mips::BI__builtin_msa_mini_s_h:
2912   case Mips::BI__builtin_msa_mini_s_w:
2913   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
2914   // These intrinsics take an unsigned 8 bit immediate.
2915   case Mips::BI__builtin_msa_andi_b:
2916   case Mips::BI__builtin_msa_nori_b:
2917   case Mips::BI__builtin_msa_ori_b:
2918   case Mips::BI__builtin_msa_shf_b:
2919   case Mips::BI__builtin_msa_shf_h:
2920   case Mips::BI__builtin_msa_shf_w:
2921   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
2922   case Mips::BI__builtin_msa_bseli_b:
2923   case Mips::BI__builtin_msa_bmnzi_b:
2924   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
2925   // df/n format
2926   // These intrinsics take an unsigned 4 bit immediate.
2927   case Mips::BI__builtin_msa_copy_s_b:
2928   case Mips::BI__builtin_msa_copy_u_b:
2929   case Mips::BI__builtin_msa_insve_b:
2930   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
2931   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
2932   // These intrinsics take an unsigned 3 bit immediate.
2933   case Mips::BI__builtin_msa_copy_s_h:
2934   case Mips::BI__builtin_msa_copy_u_h:
2935   case Mips::BI__builtin_msa_insve_h:
2936   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
2937   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
2938   // These intrinsics take an unsigned 2 bit immediate.
2939   case Mips::BI__builtin_msa_copy_s_w:
2940   case Mips::BI__builtin_msa_copy_u_w:
2941   case Mips::BI__builtin_msa_insve_w:
2942   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
2943   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
2944   // These intrinsics take an unsigned 1 bit immediate.
2945   case Mips::BI__builtin_msa_copy_s_d:
2946   case Mips::BI__builtin_msa_copy_u_d:
2947   case Mips::BI__builtin_msa_insve_d:
2948   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
2949   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
2950   // Memory offsets and immediate loads.
2951   // These intrinsics take a signed 10 bit immediate.
2952   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
2953   case Mips::BI__builtin_msa_ldi_h:
2954   case Mips::BI__builtin_msa_ldi_w:
2955   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
2956   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
2957   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
2958   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
2959   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
2960   case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
2961   case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
2962   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
2963   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
2964   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
2965   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
2966   case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
2967   case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
2968   }
2969 
2970   if (!m)
2971     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2972 
2973   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
2974          SemaBuiltinConstantArgMultiple(TheCall, i, m);
2975 }
2976 
2977 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2978   unsigned i = 0, l = 0, u = 0;
2979   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
2980                       BuiltinID == PPC::BI__builtin_divdeu ||
2981                       BuiltinID == PPC::BI__builtin_bpermd;
2982   bool IsTarget64Bit = Context.getTargetInfo()
2983                               .getTypeWidth(Context
2984                                             .getTargetInfo()
2985                                             .getIntPtrType()) == 64;
2986   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
2987                        BuiltinID == PPC::BI__builtin_divweu ||
2988                        BuiltinID == PPC::BI__builtin_divde ||
2989                        BuiltinID == PPC::BI__builtin_divdeu;
2990 
2991   if (Is64BitBltin && !IsTarget64Bit)
2992     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
2993            << TheCall->getSourceRange();
2994 
2995   if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
2996       (BuiltinID == PPC::BI__builtin_bpermd &&
2997        !Context.getTargetInfo().hasFeature("bpermd")))
2998     return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
2999            << TheCall->getSourceRange();
3000 
3001   auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
3002     if (!Context.getTargetInfo().hasFeature("vsx"))
3003       return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3004              << TheCall->getSourceRange();
3005     return false;
3006   };
3007 
3008   switch (BuiltinID) {
3009   default: return false;
3010   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3011   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3012     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3013            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3014   case PPC::BI__builtin_altivec_dss:
3015     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3016   case PPC::BI__builtin_tbegin:
3017   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3018   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3019   case PPC::BI__builtin_tabortwc:
3020   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3021   case PPC::BI__builtin_tabortwci:
3022   case PPC::BI__builtin_tabortdci:
3023     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3024            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3025   case PPC::BI__builtin_altivec_dst:
3026   case PPC::BI__builtin_altivec_dstt:
3027   case PPC::BI__builtin_altivec_dstst:
3028   case PPC::BI__builtin_altivec_dststt:
3029     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3030   case PPC::BI__builtin_vsx_xxpermdi:
3031   case PPC::BI__builtin_vsx_xxsldwi:
3032     return SemaBuiltinVSX(TheCall);
3033   case PPC::BI__builtin_unpack_vector_int128:
3034     return SemaVSXCheck(TheCall) ||
3035            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3036   case PPC::BI__builtin_pack_vector_int128:
3037     return SemaVSXCheck(TheCall);
3038   }
3039   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3040 }
3041 
3042 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
3043                                           CallExpr *TheCall) {
3044   switch (BuiltinID) {
3045   case AMDGPU::BI__builtin_amdgcn_fence: {
3046     ExprResult Arg = TheCall->getArg(0);
3047     auto ArgExpr = Arg.get();
3048     Expr::EvalResult ArgResult;
3049 
3050     if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
3051       return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
3052              << ArgExpr->getType();
3053     int ord = ArgResult.Val.getInt().getZExtValue();
3054 
3055     // Check valididty of memory ordering as per C11 / C++11's memody model.
3056     switch (static_cast<llvm::AtomicOrderingCABI>(ord)) {
3057     case llvm::AtomicOrderingCABI::acquire:
3058     case llvm::AtomicOrderingCABI::release:
3059     case llvm::AtomicOrderingCABI::acq_rel:
3060     case llvm::AtomicOrderingCABI::seq_cst:
3061       break;
3062     default: {
3063       return Diag(ArgExpr->getBeginLoc(),
3064                   diag::warn_atomic_op_has_invalid_memory_order)
3065              << ArgExpr->getSourceRange();
3066     }
3067     }
3068 
3069     Arg = TheCall->getArg(1);
3070     ArgExpr = Arg.get();
3071     Expr::EvalResult ArgResult1;
3072     // Check that sync scope is a constant literal
3073     if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Expr::EvaluateForCodeGen,
3074                                          Context))
3075       return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
3076              << ArgExpr->getType();
3077   } break;
3078   }
3079   return false;
3080 }
3081 
3082 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3083                                            CallExpr *TheCall) {
3084   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3085     Expr *Arg = TheCall->getArg(0);
3086     llvm::APSInt AbortCode(32);
3087     if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
3088         AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
3089       return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3090              << Arg->getSourceRange();
3091   }
3092 
3093   // For intrinsics which take an immediate value as part of the instruction,
3094   // range check them here.
3095   unsigned i = 0, l = 0, u = 0;
3096   switch (BuiltinID) {
3097   default: return false;
3098   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3099   case SystemZ::BI__builtin_s390_verimb:
3100   case SystemZ::BI__builtin_s390_verimh:
3101   case SystemZ::BI__builtin_s390_verimf:
3102   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3103   case SystemZ::BI__builtin_s390_vfaeb:
3104   case SystemZ::BI__builtin_s390_vfaeh:
3105   case SystemZ::BI__builtin_s390_vfaef:
3106   case SystemZ::BI__builtin_s390_vfaebs:
3107   case SystemZ::BI__builtin_s390_vfaehs:
3108   case SystemZ::BI__builtin_s390_vfaefs:
3109   case SystemZ::BI__builtin_s390_vfaezb:
3110   case SystemZ::BI__builtin_s390_vfaezh:
3111   case SystemZ::BI__builtin_s390_vfaezf:
3112   case SystemZ::BI__builtin_s390_vfaezbs:
3113   case SystemZ::BI__builtin_s390_vfaezhs:
3114   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3115   case SystemZ::BI__builtin_s390_vfisb:
3116   case SystemZ::BI__builtin_s390_vfidb:
3117     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3118            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3119   case SystemZ::BI__builtin_s390_vftcisb:
3120   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3121   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3122   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3123   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3124   case SystemZ::BI__builtin_s390_vstrcb:
3125   case SystemZ::BI__builtin_s390_vstrch:
3126   case SystemZ::BI__builtin_s390_vstrcf:
3127   case SystemZ::BI__builtin_s390_vstrczb:
3128   case SystemZ::BI__builtin_s390_vstrczh:
3129   case SystemZ::BI__builtin_s390_vstrczf:
3130   case SystemZ::BI__builtin_s390_vstrcbs:
3131   case SystemZ::BI__builtin_s390_vstrchs:
3132   case SystemZ::BI__builtin_s390_vstrcfs:
3133   case SystemZ::BI__builtin_s390_vstrczbs:
3134   case SystemZ::BI__builtin_s390_vstrczhs:
3135   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3136   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3137   case SystemZ::BI__builtin_s390_vfminsb:
3138   case SystemZ::BI__builtin_s390_vfmaxsb:
3139   case SystemZ::BI__builtin_s390_vfmindb:
3140   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3141   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
3142   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
3143   }
3144   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3145 }
3146 
3147 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3148 /// This checks that the target supports __builtin_cpu_supports and
3149 /// that the string argument is constant and valid.
3150 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
3151   Expr *Arg = TheCall->getArg(0);
3152 
3153   // Check if the argument is a string literal.
3154   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3155     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3156            << Arg->getSourceRange();
3157 
3158   // Check the contents of the string.
3159   StringRef Feature =
3160       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3161   if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
3162     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3163            << Arg->getSourceRange();
3164   return false;
3165 }
3166 
3167 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3168 /// This checks that the target supports __builtin_cpu_is and
3169 /// that the string argument is constant and valid.
3170 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
3171   Expr *Arg = TheCall->getArg(0);
3172 
3173   // Check if the argument is a string literal.
3174   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3175     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3176            << Arg->getSourceRange();
3177 
3178   // Check the contents of the string.
3179   StringRef Feature =
3180       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3181   if (!S.Context.getTargetInfo().validateCpuIs(Feature))
3182     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3183            << Arg->getSourceRange();
3184   return false;
3185 }
3186 
3187 // Check if the rounding mode is legal.
3188 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3189   // Indicates if this instruction has rounding control or just SAE.
3190   bool HasRC = false;
3191 
3192   unsigned ArgNum = 0;
3193   switch (BuiltinID) {
3194   default:
3195     return false;
3196   case X86::BI__builtin_ia32_vcvttsd2si32:
3197   case X86::BI__builtin_ia32_vcvttsd2si64:
3198   case X86::BI__builtin_ia32_vcvttsd2usi32:
3199   case X86::BI__builtin_ia32_vcvttsd2usi64:
3200   case X86::BI__builtin_ia32_vcvttss2si32:
3201   case X86::BI__builtin_ia32_vcvttss2si64:
3202   case X86::BI__builtin_ia32_vcvttss2usi32:
3203   case X86::BI__builtin_ia32_vcvttss2usi64:
3204     ArgNum = 1;
3205     break;
3206   case X86::BI__builtin_ia32_maxpd512:
3207   case X86::BI__builtin_ia32_maxps512:
3208   case X86::BI__builtin_ia32_minpd512:
3209   case X86::BI__builtin_ia32_minps512:
3210     ArgNum = 2;
3211     break;
3212   case X86::BI__builtin_ia32_cvtps2pd512_mask:
3213   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3214   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3215   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3216   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3217   case X86::BI__builtin_ia32_cvttps2dq512_mask:
3218   case X86::BI__builtin_ia32_cvttps2qq512_mask:
3219   case X86::BI__builtin_ia32_cvttps2udq512_mask:
3220   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3221   case X86::BI__builtin_ia32_exp2pd_mask:
3222   case X86::BI__builtin_ia32_exp2ps_mask:
3223   case X86::BI__builtin_ia32_getexppd512_mask:
3224   case X86::BI__builtin_ia32_getexpps512_mask:
3225   case X86::BI__builtin_ia32_rcp28pd_mask:
3226   case X86::BI__builtin_ia32_rcp28ps_mask:
3227   case X86::BI__builtin_ia32_rsqrt28pd_mask:
3228   case X86::BI__builtin_ia32_rsqrt28ps_mask:
3229   case X86::BI__builtin_ia32_vcomisd:
3230   case X86::BI__builtin_ia32_vcomiss:
3231   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3232     ArgNum = 3;
3233     break;
3234   case X86::BI__builtin_ia32_cmppd512_mask:
3235   case X86::BI__builtin_ia32_cmpps512_mask:
3236   case X86::BI__builtin_ia32_cmpsd_mask:
3237   case X86::BI__builtin_ia32_cmpss_mask:
3238   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3239   case X86::BI__builtin_ia32_getexpsd128_round_mask:
3240   case X86::BI__builtin_ia32_getexpss128_round_mask:
3241   case X86::BI__builtin_ia32_getmantpd512_mask:
3242   case X86::BI__builtin_ia32_getmantps512_mask:
3243   case X86::BI__builtin_ia32_maxsd_round_mask:
3244   case X86::BI__builtin_ia32_maxss_round_mask:
3245   case X86::BI__builtin_ia32_minsd_round_mask:
3246   case X86::BI__builtin_ia32_minss_round_mask:
3247   case X86::BI__builtin_ia32_rcp28sd_round_mask:
3248   case X86::BI__builtin_ia32_rcp28ss_round_mask:
3249   case X86::BI__builtin_ia32_reducepd512_mask:
3250   case X86::BI__builtin_ia32_reduceps512_mask:
3251   case X86::BI__builtin_ia32_rndscalepd_mask:
3252   case X86::BI__builtin_ia32_rndscaleps_mask:
3253   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3254   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3255     ArgNum = 4;
3256     break;
3257   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3258   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3259   case X86::BI__builtin_ia32_fixupimmps512_mask:
3260   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3261   case X86::BI__builtin_ia32_fixupimmsd_mask:
3262   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3263   case X86::BI__builtin_ia32_fixupimmss_mask:
3264   case X86::BI__builtin_ia32_fixupimmss_maskz:
3265   case X86::BI__builtin_ia32_getmantsd_round_mask:
3266   case X86::BI__builtin_ia32_getmantss_round_mask:
3267   case X86::BI__builtin_ia32_rangepd512_mask:
3268   case X86::BI__builtin_ia32_rangeps512_mask:
3269   case X86::BI__builtin_ia32_rangesd128_round_mask:
3270   case X86::BI__builtin_ia32_rangess128_round_mask:
3271   case X86::BI__builtin_ia32_reducesd_mask:
3272   case X86::BI__builtin_ia32_reducess_mask:
3273   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3274   case X86::BI__builtin_ia32_rndscaless_round_mask:
3275     ArgNum = 5;
3276     break;
3277   case X86::BI__builtin_ia32_vcvtsd2si64:
3278   case X86::BI__builtin_ia32_vcvtsd2si32:
3279   case X86::BI__builtin_ia32_vcvtsd2usi32:
3280   case X86::BI__builtin_ia32_vcvtsd2usi64:
3281   case X86::BI__builtin_ia32_vcvtss2si32:
3282   case X86::BI__builtin_ia32_vcvtss2si64:
3283   case X86::BI__builtin_ia32_vcvtss2usi32:
3284   case X86::BI__builtin_ia32_vcvtss2usi64:
3285   case X86::BI__builtin_ia32_sqrtpd512:
3286   case X86::BI__builtin_ia32_sqrtps512:
3287     ArgNum = 1;
3288     HasRC = true;
3289     break;
3290   case X86::BI__builtin_ia32_addpd512:
3291   case X86::BI__builtin_ia32_addps512:
3292   case X86::BI__builtin_ia32_divpd512:
3293   case X86::BI__builtin_ia32_divps512:
3294   case X86::BI__builtin_ia32_mulpd512:
3295   case X86::BI__builtin_ia32_mulps512:
3296   case X86::BI__builtin_ia32_subpd512:
3297   case X86::BI__builtin_ia32_subps512:
3298   case X86::BI__builtin_ia32_cvtsi2sd64:
3299   case X86::BI__builtin_ia32_cvtsi2ss32:
3300   case X86::BI__builtin_ia32_cvtsi2ss64:
3301   case X86::BI__builtin_ia32_cvtusi2sd64:
3302   case X86::BI__builtin_ia32_cvtusi2ss32:
3303   case X86::BI__builtin_ia32_cvtusi2ss64:
3304     ArgNum = 2;
3305     HasRC = true;
3306     break;
3307   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3308   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3309   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
3310   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
3311   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3312   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
3313   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3314   case X86::BI__builtin_ia32_cvtps2dq512_mask:
3315   case X86::BI__builtin_ia32_cvtps2qq512_mask:
3316   case X86::BI__builtin_ia32_cvtps2udq512_mask:
3317   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3318   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3319   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3320   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3321   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3322     ArgNum = 3;
3323     HasRC = true;
3324     break;
3325   case X86::BI__builtin_ia32_addss_round_mask:
3326   case X86::BI__builtin_ia32_addsd_round_mask:
3327   case X86::BI__builtin_ia32_divss_round_mask:
3328   case X86::BI__builtin_ia32_divsd_round_mask:
3329   case X86::BI__builtin_ia32_mulss_round_mask:
3330   case X86::BI__builtin_ia32_mulsd_round_mask:
3331   case X86::BI__builtin_ia32_subss_round_mask:
3332   case X86::BI__builtin_ia32_subsd_round_mask:
3333   case X86::BI__builtin_ia32_scalefpd512_mask:
3334   case X86::BI__builtin_ia32_scalefps512_mask:
3335   case X86::BI__builtin_ia32_scalefsd_round_mask:
3336   case X86::BI__builtin_ia32_scalefss_round_mask:
3337   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3338   case X86::BI__builtin_ia32_sqrtsd_round_mask:
3339   case X86::BI__builtin_ia32_sqrtss_round_mask:
3340   case X86::BI__builtin_ia32_vfmaddsd3_mask:
3341   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3342   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
3343   case X86::BI__builtin_ia32_vfmaddss3_mask:
3344   case X86::BI__builtin_ia32_vfmaddss3_maskz:
3345   case X86::BI__builtin_ia32_vfmaddss3_mask3:
3346   case X86::BI__builtin_ia32_vfmaddpd512_mask:
3347   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
3348   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
3349   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
3350   case X86::BI__builtin_ia32_vfmaddps512_mask:
3351   case X86::BI__builtin_ia32_vfmaddps512_maskz:
3352   case X86::BI__builtin_ia32_vfmaddps512_mask3:
3353   case X86::BI__builtin_ia32_vfmsubps512_mask3:
3354   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
3355   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
3356   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
3357   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
3358   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
3359   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
3360   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
3361   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
3362     ArgNum = 4;
3363     HasRC = true;
3364     break;
3365   }
3366 
3367   llvm::APSInt Result;
3368 
3369   // We can't check the value of a dependent argument.
3370   Expr *Arg = TheCall->getArg(ArgNum);
3371   if (Arg->isTypeDependent() || Arg->isValueDependent())
3372     return false;
3373 
3374   // Check constant-ness first.
3375   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3376     return true;
3377 
3378   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
3379   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
3380   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
3381   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
3382   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
3383       Result == 8/*ROUND_NO_EXC*/ ||
3384       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
3385       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
3386     return false;
3387 
3388   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
3389          << Arg->getSourceRange();
3390 }
3391 
3392 // Check if the gather/scatter scale is legal.
3393 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
3394                                              CallExpr *TheCall) {
3395   unsigned ArgNum = 0;
3396   switch (BuiltinID) {
3397   default:
3398     return false;
3399   case X86::BI__builtin_ia32_gatherpfdpd:
3400   case X86::BI__builtin_ia32_gatherpfdps:
3401   case X86::BI__builtin_ia32_gatherpfqpd:
3402   case X86::BI__builtin_ia32_gatherpfqps:
3403   case X86::BI__builtin_ia32_scatterpfdpd:
3404   case X86::BI__builtin_ia32_scatterpfdps:
3405   case X86::BI__builtin_ia32_scatterpfqpd:
3406   case X86::BI__builtin_ia32_scatterpfqps:
3407     ArgNum = 3;
3408     break;
3409   case X86::BI__builtin_ia32_gatherd_pd:
3410   case X86::BI__builtin_ia32_gatherd_pd256:
3411   case X86::BI__builtin_ia32_gatherq_pd:
3412   case X86::BI__builtin_ia32_gatherq_pd256:
3413   case X86::BI__builtin_ia32_gatherd_ps:
3414   case X86::BI__builtin_ia32_gatherd_ps256:
3415   case X86::BI__builtin_ia32_gatherq_ps:
3416   case X86::BI__builtin_ia32_gatherq_ps256:
3417   case X86::BI__builtin_ia32_gatherd_q:
3418   case X86::BI__builtin_ia32_gatherd_q256:
3419   case X86::BI__builtin_ia32_gatherq_q:
3420   case X86::BI__builtin_ia32_gatherq_q256:
3421   case X86::BI__builtin_ia32_gatherd_d:
3422   case X86::BI__builtin_ia32_gatherd_d256:
3423   case X86::BI__builtin_ia32_gatherq_d:
3424   case X86::BI__builtin_ia32_gatherq_d256:
3425   case X86::BI__builtin_ia32_gather3div2df:
3426   case X86::BI__builtin_ia32_gather3div2di:
3427   case X86::BI__builtin_ia32_gather3div4df:
3428   case X86::BI__builtin_ia32_gather3div4di:
3429   case X86::BI__builtin_ia32_gather3div4sf:
3430   case X86::BI__builtin_ia32_gather3div4si:
3431   case X86::BI__builtin_ia32_gather3div8sf:
3432   case X86::BI__builtin_ia32_gather3div8si:
3433   case X86::BI__builtin_ia32_gather3siv2df:
3434   case X86::BI__builtin_ia32_gather3siv2di:
3435   case X86::BI__builtin_ia32_gather3siv4df:
3436   case X86::BI__builtin_ia32_gather3siv4di:
3437   case X86::BI__builtin_ia32_gather3siv4sf:
3438   case X86::BI__builtin_ia32_gather3siv4si:
3439   case X86::BI__builtin_ia32_gather3siv8sf:
3440   case X86::BI__builtin_ia32_gather3siv8si:
3441   case X86::BI__builtin_ia32_gathersiv8df:
3442   case X86::BI__builtin_ia32_gathersiv16sf:
3443   case X86::BI__builtin_ia32_gatherdiv8df:
3444   case X86::BI__builtin_ia32_gatherdiv16sf:
3445   case X86::BI__builtin_ia32_gathersiv8di:
3446   case X86::BI__builtin_ia32_gathersiv16si:
3447   case X86::BI__builtin_ia32_gatherdiv8di:
3448   case X86::BI__builtin_ia32_gatherdiv16si:
3449   case X86::BI__builtin_ia32_scatterdiv2df:
3450   case X86::BI__builtin_ia32_scatterdiv2di:
3451   case X86::BI__builtin_ia32_scatterdiv4df:
3452   case X86::BI__builtin_ia32_scatterdiv4di:
3453   case X86::BI__builtin_ia32_scatterdiv4sf:
3454   case X86::BI__builtin_ia32_scatterdiv4si:
3455   case X86::BI__builtin_ia32_scatterdiv8sf:
3456   case X86::BI__builtin_ia32_scatterdiv8si:
3457   case X86::BI__builtin_ia32_scattersiv2df:
3458   case X86::BI__builtin_ia32_scattersiv2di:
3459   case X86::BI__builtin_ia32_scattersiv4df:
3460   case X86::BI__builtin_ia32_scattersiv4di:
3461   case X86::BI__builtin_ia32_scattersiv4sf:
3462   case X86::BI__builtin_ia32_scattersiv4si:
3463   case X86::BI__builtin_ia32_scattersiv8sf:
3464   case X86::BI__builtin_ia32_scattersiv8si:
3465   case X86::BI__builtin_ia32_scattersiv8df:
3466   case X86::BI__builtin_ia32_scattersiv16sf:
3467   case X86::BI__builtin_ia32_scatterdiv8df:
3468   case X86::BI__builtin_ia32_scatterdiv16sf:
3469   case X86::BI__builtin_ia32_scattersiv8di:
3470   case X86::BI__builtin_ia32_scattersiv16si:
3471   case X86::BI__builtin_ia32_scatterdiv8di:
3472   case X86::BI__builtin_ia32_scatterdiv16si:
3473     ArgNum = 4;
3474     break;
3475   }
3476 
3477   llvm::APSInt Result;
3478 
3479   // We can't check the value of a dependent argument.
3480   Expr *Arg = TheCall->getArg(ArgNum);
3481   if (Arg->isTypeDependent() || Arg->isValueDependent())
3482     return false;
3483 
3484   // Check constant-ness first.
3485   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3486     return true;
3487 
3488   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
3489     return false;
3490 
3491   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
3492          << Arg->getSourceRange();
3493 }
3494 
3495 static bool isX86_32Builtin(unsigned BuiltinID) {
3496   // These builtins only work on x86-32 targets.
3497   switch (BuiltinID) {
3498   case X86::BI__builtin_ia32_readeflags_u32:
3499   case X86::BI__builtin_ia32_writeeflags_u32:
3500     return true;
3501   }
3502 
3503   return false;
3504 }
3505 
3506 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3507   if (BuiltinID == X86::BI__builtin_cpu_supports)
3508     return SemaBuiltinCpuSupports(*this, TheCall);
3509 
3510   if (BuiltinID == X86::BI__builtin_cpu_is)
3511     return SemaBuiltinCpuIs(*this, TheCall);
3512 
3513   // Check for 32-bit only builtins on a 64-bit target.
3514   const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3515   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
3516     return Diag(TheCall->getCallee()->getBeginLoc(),
3517                 diag::err_32_bit_builtin_64_bit_tgt);
3518 
3519   // If the intrinsic has rounding or SAE make sure its valid.
3520   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
3521     return true;
3522 
3523   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
3524   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
3525     return true;
3526 
3527   // For intrinsics which take an immediate value as part of the instruction,
3528   // range check them here.
3529   int i = 0, l = 0, u = 0;
3530   switch (BuiltinID) {
3531   default:
3532     return false;
3533   case X86::BI__builtin_ia32_vec_ext_v2si:
3534   case X86::BI__builtin_ia32_vec_ext_v2di:
3535   case X86::BI__builtin_ia32_vextractf128_pd256:
3536   case X86::BI__builtin_ia32_vextractf128_ps256:
3537   case X86::BI__builtin_ia32_vextractf128_si256:
3538   case X86::BI__builtin_ia32_extract128i256:
3539   case X86::BI__builtin_ia32_extractf64x4_mask:
3540   case X86::BI__builtin_ia32_extracti64x4_mask:
3541   case X86::BI__builtin_ia32_extractf32x8_mask:
3542   case X86::BI__builtin_ia32_extracti32x8_mask:
3543   case X86::BI__builtin_ia32_extractf64x2_256_mask:
3544   case X86::BI__builtin_ia32_extracti64x2_256_mask:
3545   case X86::BI__builtin_ia32_extractf32x4_256_mask:
3546   case X86::BI__builtin_ia32_extracti32x4_256_mask:
3547     i = 1; l = 0; u = 1;
3548     break;
3549   case X86::BI__builtin_ia32_vec_set_v2di:
3550   case X86::BI__builtin_ia32_vinsertf128_pd256:
3551   case X86::BI__builtin_ia32_vinsertf128_ps256:
3552   case X86::BI__builtin_ia32_vinsertf128_si256:
3553   case X86::BI__builtin_ia32_insert128i256:
3554   case X86::BI__builtin_ia32_insertf32x8:
3555   case X86::BI__builtin_ia32_inserti32x8:
3556   case X86::BI__builtin_ia32_insertf64x4:
3557   case X86::BI__builtin_ia32_inserti64x4:
3558   case X86::BI__builtin_ia32_insertf64x2_256:
3559   case X86::BI__builtin_ia32_inserti64x2_256:
3560   case X86::BI__builtin_ia32_insertf32x4_256:
3561   case X86::BI__builtin_ia32_inserti32x4_256:
3562     i = 2; l = 0; u = 1;
3563     break;
3564   case X86::BI__builtin_ia32_vpermilpd:
3565   case X86::BI__builtin_ia32_vec_ext_v4hi:
3566   case X86::BI__builtin_ia32_vec_ext_v4si:
3567   case X86::BI__builtin_ia32_vec_ext_v4sf:
3568   case X86::BI__builtin_ia32_vec_ext_v4di:
3569   case X86::BI__builtin_ia32_extractf32x4_mask:
3570   case X86::BI__builtin_ia32_extracti32x4_mask:
3571   case X86::BI__builtin_ia32_extractf64x2_512_mask:
3572   case X86::BI__builtin_ia32_extracti64x2_512_mask:
3573     i = 1; l = 0; u = 3;
3574     break;
3575   case X86::BI_mm_prefetch:
3576   case X86::BI__builtin_ia32_vec_ext_v8hi:
3577   case X86::BI__builtin_ia32_vec_ext_v8si:
3578     i = 1; l = 0; u = 7;
3579     break;
3580   case X86::BI__builtin_ia32_sha1rnds4:
3581   case X86::BI__builtin_ia32_blendpd:
3582   case X86::BI__builtin_ia32_shufpd:
3583   case X86::BI__builtin_ia32_vec_set_v4hi:
3584   case X86::BI__builtin_ia32_vec_set_v4si:
3585   case X86::BI__builtin_ia32_vec_set_v4di:
3586   case X86::BI__builtin_ia32_shuf_f32x4_256:
3587   case X86::BI__builtin_ia32_shuf_f64x2_256:
3588   case X86::BI__builtin_ia32_shuf_i32x4_256:
3589   case X86::BI__builtin_ia32_shuf_i64x2_256:
3590   case X86::BI__builtin_ia32_insertf64x2_512:
3591   case X86::BI__builtin_ia32_inserti64x2_512:
3592   case X86::BI__builtin_ia32_insertf32x4:
3593   case X86::BI__builtin_ia32_inserti32x4:
3594     i = 2; l = 0; u = 3;
3595     break;
3596   case X86::BI__builtin_ia32_vpermil2pd:
3597   case X86::BI__builtin_ia32_vpermil2pd256:
3598   case X86::BI__builtin_ia32_vpermil2ps:
3599   case X86::BI__builtin_ia32_vpermil2ps256:
3600     i = 3; l = 0; u = 3;
3601     break;
3602   case X86::BI__builtin_ia32_cmpb128_mask:
3603   case X86::BI__builtin_ia32_cmpw128_mask:
3604   case X86::BI__builtin_ia32_cmpd128_mask:
3605   case X86::BI__builtin_ia32_cmpq128_mask:
3606   case X86::BI__builtin_ia32_cmpb256_mask:
3607   case X86::BI__builtin_ia32_cmpw256_mask:
3608   case X86::BI__builtin_ia32_cmpd256_mask:
3609   case X86::BI__builtin_ia32_cmpq256_mask:
3610   case X86::BI__builtin_ia32_cmpb512_mask:
3611   case X86::BI__builtin_ia32_cmpw512_mask:
3612   case X86::BI__builtin_ia32_cmpd512_mask:
3613   case X86::BI__builtin_ia32_cmpq512_mask:
3614   case X86::BI__builtin_ia32_ucmpb128_mask:
3615   case X86::BI__builtin_ia32_ucmpw128_mask:
3616   case X86::BI__builtin_ia32_ucmpd128_mask:
3617   case X86::BI__builtin_ia32_ucmpq128_mask:
3618   case X86::BI__builtin_ia32_ucmpb256_mask:
3619   case X86::BI__builtin_ia32_ucmpw256_mask:
3620   case X86::BI__builtin_ia32_ucmpd256_mask:
3621   case X86::BI__builtin_ia32_ucmpq256_mask:
3622   case X86::BI__builtin_ia32_ucmpb512_mask:
3623   case X86::BI__builtin_ia32_ucmpw512_mask:
3624   case X86::BI__builtin_ia32_ucmpd512_mask:
3625   case X86::BI__builtin_ia32_ucmpq512_mask:
3626   case X86::BI__builtin_ia32_vpcomub:
3627   case X86::BI__builtin_ia32_vpcomuw:
3628   case X86::BI__builtin_ia32_vpcomud:
3629   case X86::BI__builtin_ia32_vpcomuq:
3630   case X86::BI__builtin_ia32_vpcomb:
3631   case X86::BI__builtin_ia32_vpcomw:
3632   case X86::BI__builtin_ia32_vpcomd:
3633   case X86::BI__builtin_ia32_vpcomq:
3634   case X86::BI__builtin_ia32_vec_set_v8hi:
3635   case X86::BI__builtin_ia32_vec_set_v8si:
3636     i = 2; l = 0; u = 7;
3637     break;
3638   case X86::BI__builtin_ia32_vpermilpd256:
3639   case X86::BI__builtin_ia32_roundps:
3640   case X86::BI__builtin_ia32_roundpd:
3641   case X86::BI__builtin_ia32_roundps256:
3642   case X86::BI__builtin_ia32_roundpd256:
3643   case X86::BI__builtin_ia32_getmantpd128_mask:
3644   case X86::BI__builtin_ia32_getmantpd256_mask:
3645   case X86::BI__builtin_ia32_getmantps128_mask:
3646   case X86::BI__builtin_ia32_getmantps256_mask:
3647   case X86::BI__builtin_ia32_getmantpd512_mask:
3648   case X86::BI__builtin_ia32_getmantps512_mask:
3649   case X86::BI__builtin_ia32_vec_ext_v16qi:
3650   case X86::BI__builtin_ia32_vec_ext_v16hi:
3651     i = 1; l = 0; u = 15;
3652     break;
3653   case X86::BI__builtin_ia32_pblendd128:
3654   case X86::BI__builtin_ia32_blendps:
3655   case X86::BI__builtin_ia32_blendpd256:
3656   case X86::BI__builtin_ia32_shufpd256:
3657   case X86::BI__builtin_ia32_roundss:
3658   case X86::BI__builtin_ia32_roundsd:
3659   case X86::BI__builtin_ia32_rangepd128_mask:
3660   case X86::BI__builtin_ia32_rangepd256_mask:
3661   case X86::BI__builtin_ia32_rangepd512_mask:
3662   case X86::BI__builtin_ia32_rangeps128_mask:
3663   case X86::BI__builtin_ia32_rangeps256_mask:
3664   case X86::BI__builtin_ia32_rangeps512_mask:
3665   case X86::BI__builtin_ia32_getmantsd_round_mask:
3666   case X86::BI__builtin_ia32_getmantss_round_mask:
3667   case X86::BI__builtin_ia32_vec_set_v16qi:
3668   case X86::BI__builtin_ia32_vec_set_v16hi:
3669     i = 2; l = 0; u = 15;
3670     break;
3671   case X86::BI__builtin_ia32_vec_ext_v32qi:
3672     i = 1; l = 0; u = 31;
3673     break;
3674   case X86::BI__builtin_ia32_cmpps:
3675   case X86::BI__builtin_ia32_cmpss:
3676   case X86::BI__builtin_ia32_cmppd:
3677   case X86::BI__builtin_ia32_cmpsd:
3678   case X86::BI__builtin_ia32_cmpps256:
3679   case X86::BI__builtin_ia32_cmppd256:
3680   case X86::BI__builtin_ia32_cmpps128_mask:
3681   case X86::BI__builtin_ia32_cmppd128_mask:
3682   case X86::BI__builtin_ia32_cmpps256_mask:
3683   case X86::BI__builtin_ia32_cmppd256_mask:
3684   case X86::BI__builtin_ia32_cmpps512_mask:
3685   case X86::BI__builtin_ia32_cmppd512_mask:
3686   case X86::BI__builtin_ia32_cmpsd_mask:
3687   case X86::BI__builtin_ia32_cmpss_mask:
3688   case X86::BI__builtin_ia32_vec_set_v32qi:
3689     i = 2; l = 0; u = 31;
3690     break;
3691   case X86::BI__builtin_ia32_permdf256:
3692   case X86::BI__builtin_ia32_permdi256:
3693   case X86::BI__builtin_ia32_permdf512:
3694   case X86::BI__builtin_ia32_permdi512:
3695   case X86::BI__builtin_ia32_vpermilps:
3696   case X86::BI__builtin_ia32_vpermilps256:
3697   case X86::BI__builtin_ia32_vpermilpd512:
3698   case X86::BI__builtin_ia32_vpermilps512:
3699   case X86::BI__builtin_ia32_pshufd:
3700   case X86::BI__builtin_ia32_pshufd256:
3701   case X86::BI__builtin_ia32_pshufd512:
3702   case X86::BI__builtin_ia32_pshufhw:
3703   case X86::BI__builtin_ia32_pshufhw256:
3704   case X86::BI__builtin_ia32_pshufhw512:
3705   case X86::BI__builtin_ia32_pshuflw:
3706   case X86::BI__builtin_ia32_pshuflw256:
3707   case X86::BI__builtin_ia32_pshuflw512:
3708   case X86::BI__builtin_ia32_vcvtps2ph:
3709   case X86::BI__builtin_ia32_vcvtps2ph_mask:
3710   case X86::BI__builtin_ia32_vcvtps2ph256:
3711   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
3712   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
3713   case X86::BI__builtin_ia32_rndscaleps_128_mask:
3714   case X86::BI__builtin_ia32_rndscalepd_128_mask:
3715   case X86::BI__builtin_ia32_rndscaleps_256_mask:
3716   case X86::BI__builtin_ia32_rndscalepd_256_mask:
3717   case X86::BI__builtin_ia32_rndscaleps_mask:
3718   case X86::BI__builtin_ia32_rndscalepd_mask:
3719   case X86::BI__builtin_ia32_reducepd128_mask:
3720   case X86::BI__builtin_ia32_reducepd256_mask:
3721   case X86::BI__builtin_ia32_reducepd512_mask:
3722   case X86::BI__builtin_ia32_reduceps128_mask:
3723   case X86::BI__builtin_ia32_reduceps256_mask:
3724   case X86::BI__builtin_ia32_reduceps512_mask:
3725   case X86::BI__builtin_ia32_prold512:
3726   case X86::BI__builtin_ia32_prolq512:
3727   case X86::BI__builtin_ia32_prold128:
3728   case X86::BI__builtin_ia32_prold256:
3729   case X86::BI__builtin_ia32_prolq128:
3730   case X86::BI__builtin_ia32_prolq256:
3731   case X86::BI__builtin_ia32_prord512:
3732   case X86::BI__builtin_ia32_prorq512:
3733   case X86::BI__builtin_ia32_prord128:
3734   case X86::BI__builtin_ia32_prord256:
3735   case X86::BI__builtin_ia32_prorq128:
3736   case X86::BI__builtin_ia32_prorq256:
3737   case X86::BI__builtin_ia32_fpclasspd128_mask:
3738   case X86::BI__builtin_ia32_fpclasspd256_mask:
3739   case X86::BI__builtin_ia32_fpclassps128_mask:
3740   case X86::BI__builtin_ia32_fpclassps256_mask:
3741   case X86::BI__builtin_ia32_fpclassps512_mask:
3742   case X86::BI__builtin_ia32_fpclasspd512_mask:
3743   case X86::BI__builtin_ia32_fpclasssd_mask:
3744   case X86::BI__builtin_ia32_fpclassss_mask:
3745   case X86::BI__builtin_ia32_pslldqi128_byteshift:
3746   case X86::BI__builtin_ia32_pslldqi256_byteshift:
3747   case X86::BI__builtin_ia32_pslldqi512_byteshift:
3748   case X86::BI__builtin_ia32_psrldqi128_byteshift:
3749   case X86::BI__builtin_ia32_psrldqi256_byteshift:
3750   case X86::BI__builtin_ia32_psrldqi512_byteshift:
3751   case X86::BI__builtin_ia32_kshiftliqi:
3752   case X86::BI__builtin_ia32_kshiftlihi:
3753   case X86::BI__builtin_ia32_kshiftlisi:
3754   case X86::BI__builtin_ia32_kshiftlidi:
3755   case X86::BI__builtin_ia32_kshiftriqi:
3756   case X86::BI__builtin_ia32_kshiftrihi:
3757   case X86::BI__builtin_ia32_kshiftrisi:
3758   case X86::BI__builtin_ia32_kshiftridi:
3759     i = 1; l = 0; u = 255;
3760     break;
3761   case X86::BI__builtin_ia32_vperm2f128_pd256:
3762   case X86::BI__builtin_ia32_vperm2f128_ps256:
3763   case X86::BI__builtin_ia32_vperm2f128_si256:
3764   case X86::BI__builtin_ia32_permti256:
3765   case X86::BI__builtin_ia32_pblendw128:
3766   case X86::BI__builtin_ia32_pblendw256:
3767   case X86::BI__builtin_ia32_blendps256:
3768   case X86::BI__builtin_ia32_pblendd256:
3769   case X86::BI__builtin_ia32_palignr128:
3770   case X86::BI__builtin_ia32_palignr256:
3771   case X86::BI__builtin_ia32_palignr512:
3772   case X86::BI__builtin_ia32_alignq512:
3773   case X86::BI__builtin_ia32_alignd512:
3774   case X86::BI__builtin_ia32_alignd128:
3775   case X86::BI__builtin_ia32_alignd256:
3776   case X86::BI__builtin_ia32_alignq128:
3777   case X86::BI__builtin_ia32_alignq256:
3778   case X86::BI__builtin_ia32_vcomisd:
3779   case X86::BI__builtin_ia32_vcomiss:
3780   case X86::BI__builtin_ia32_shuf_f32x4:
3781   case X86::BI__builtin_ia32_shuf_f64x2:
3782   case X86::BI__builtin_ia32_shuf_i32x4:
3783   case X86::BI__builtin_ia32_shuf_i64x2:
3784   case X86::BI__builtin_ia32_shufpd512:
3785   case X86::BI__builtin_ia32_shufps:
3786   case X86::BI__builtin_ia32_shufps256:
3787   case X86::BI__builtin_ia32_shufps512:
3788   case X86::BI__builtin_ia32_dbpsadbw128:
3789   case X86::BI__builtin_ia32_dbpsadbw256:
3790   case X86::BI__builtin_ia32_dbpsadbw512:
3791   case X86::BI__builtin_ia32_vpshldd128:
3792   case X86::BI__builtin_ia32_vpshldd256:
3793   case X86::BI__builtin_ia32_vpshldd512:
3794   case X86::BI__builtin_ia32_vpshldq128:
3795   case X86::BI__builtin_ia32_vpshldq256:
3796   case X86::BI__builtin_ia32_vpshldq512:
3797   case X86::BI__builtin_ia32_vpshldw128:
3798   case X86::BI__builtin_ia32_vpshldw256:
3799   case X86::BI__builtin_ia32_vpshldw512:
3800   case X86::BI__builtin_ia32_vpshrdd128:
3801   case X86::BI__builtin_ia32_vpshrdd256:
3802   case X86::BI__builtin_ia32_vpshrdd512:
3803   case X86::BI__builtin_ia32_vpshrdq128:
3804   case X86::BI__builtin_ia32_vpshrdq256:
3805   case X86::BI__builtin_ia32_vpshrdq512:
3806   case X86::BI__builtin_ia32_vpshrdw128:
3807   case X86::BI__builtin_ia32_vpshrdw256:
3808   case X86::BI__builtin_ia32_vpshrdw512:
3809     i = 2; l = 0; u = 255;
3810     break;
3811   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3812   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3813   case X86::BI__builtin_ia32_fixupimmps512_mask:
3814   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3815   case X86::BI__builtin_ia32_fixupimmsd_mask:
3816   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3817   case X86::BI__builtin_ia32_fixupimmss_mask:
3818   case X86::BI__builtin_ia32_fixupimmss_maskz:
3819   case X86::BI__builtin_ia32_fixupimmpd128_mask:
3820   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
3821   case X86::BI__builtin_ia32_fixupimmpd256_mask:
3822   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
3823   case X86::BI__builtin_ia32_fixupimmps128_mask:
3824   case X86::BI__builtin_ia32_fixupimmps128_maskz:
3825   case X86::BI__builtin_ia32_fixupimmps256_mask:
3826   case X86::BI__builtin_ia32_fixupimmps256_maskz:
3827   case X86::BI__builtin_ia32_pternlogd512_mask:
3828   case X86::BI__builtin_ia32_pternlogd512_maskz:
3829   case X86::BI__builtin_ia32_pternlogq512_mask:
3830   case X86::BI__builtin_ia32_pternlogq512_maskz:
3831   case X86::BI__builtin_ia32_pternlogd128_mask:
3832   case X86::BI__builtin_ia32_pternlogd128_maskz:
3833   case X86::BI__builtin_ia32_pternlogd256_mask:
3834   case X86::BI__builtin_ia32_pternlogd256_maskz:
3835   case X86::BI__builtin_ia32_pternlogq128_mask:
3836   case X86::BI__builtin_ia32_pternlogq128_maskz:
3837   case X86::BI__builtin_ia32_pternlogq256_mask:
3838   case X86::BI__builtin_ia32_pternlogq256_maskz:
3839     i = 3; l = 0; u = 255;
3840     break;
3841   case X86::BI__builtin_ia32_gatherpfdpd:
3842   case X86::BI__builtin_ia32_gatherpfdps:
3843   case X86::BI__builtin_ia32_gatherpfqpd:
3844   case X86::BI__builtin_ia32_gatherpfqps:
3845   case X86::BI__builtin_ia32_scatterpfdpd:
3846   case X86::BI__builtin_ia32_scatterpfdps:
3847   case X86::BI__builtin_ia32_scatterpfqpd:
3848   case X86::BI__builtin_ia32_scatterpfqps:
3849     i = 4; l = 2; u = 3;
3850     break;
3851   case X86::BI__builtin_ia32_reducesd_mask:
3852   case X86::BI__builtin_ia32_reducess_mask:
3853   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3854   case X86::BI__builtin_ia32_rndscaless_round_mask:
3855     i = 4; l = 0; u = 255;
3856     break;
3857   }
3858 
3859   // Note that we don't force a hard error on the range check here, allowing
3860   // template-generated or macro-generated dead code to potentially have out-of-
3861   // range values. These need to code generate, but don't need to necessarily
3862   // make any sense. We use a warning that defaults to an error.
3863   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
3864 }
3865 
3866 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
3867 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
3868 /// Returns true when the format fits the function and the FormatStringInfo has
3869 /// been populated.
3870 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
3871                                FormatStringInfo *FSI) {
3872   FSI->HasVAListArg = Format->getFirstArg() == 0;
3873   FSI->FormatIdx = Format->getFormatIdx() - 1;
3874   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
3875 
3876   // The way the format attribute works in GCC, the implicit this argument
3877   // of member functions is counted. However, it doesn't appear in our own
3878   // lists, so decrement format_idx in that case.
3879   if (IsCXXMember) {
3880     if(FSI->FormatIdx == 0)
3881       return false;
3882     --FSI->FormatIdx;
3883     if (FSI->FirstDataArg != 0)
3884       --FSI->FirstDataArg;
3885   }
3886   return true;
3887 }
3888 
3889 /// Checks if a the given expression evaluates to null.
3890 ///
3891 /// Returns true if the value evaluates to null.
3892 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
3893   // If the expression has non-null type, it doesn't evaluate to null.
3894   if (auto nullability
3895         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
3896     if (*nullability == NullabilityKind::NonNull)
3897       return false;
3898   }
3899 
3900   // As a special case, transparent unions initialized with zero are
3901   // considered null for the purposes of the nonnull attribute.
3902   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
3903     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
3904       if (const CompoundLiteralExpr *CLE =
3905           dyn_cast<CompoundLiteralExpr>(Expr))
3906         if (const InitListExpr *ILE =
3907             dyn_cast<InitListExpr>(CLE->getInitializer()))
3908           Expr = ILE->getInit(0);
3909   }
3910 
3911   bool Result;
3912   return (!Expr->isValueDependent() &&
3913           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
3914           !Result);
3915 }
3916 
3917 static void CheckNonNullArgument(Sema &S,
3918                                  const Expr *ArgExpr,
3919                                  SourceLocation CallSiteLoc) {
3920   if (CheckNonNullExpr(S, ArgExpr))
3921     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
3922                           S.PDiag(diag::warn_null_arg)
3923                               << ArgExpr->getSourceRange());
3924 }
3925 
3926 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
3927   FormatStringInfo FSI;
3928   if ((GetFormatStringType(Format) == FST_NSString) &&
3929       getFormatStringInfo(Format, false, &FSI)) {
3930     Idx = FSI.FormatIdx;
3931     return true;
3932   }
3933   return false;
3934 }
3935 
3936 /// Diagnose use of %s directive in an NSString which is being passed
3937 /// as formatting string to formatting method.
3938 static void
3939 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
3940                                         const NamedDecl *FDecl,
3941                                         Expr **Args,
3942                                         unsigned NumArgs) {
3943   unsigned Idx = 0;
3944   bool Format = false;
3945   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
3946   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
3947     Idx = 2;
3948     Format = true;
3949   }
3950   else
3951     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
3952       if (S.GetFormatNSStringIdx(I, Idx)) {
3953         Format = true;
3954         break;
3955       }
3956     }
3957   if (!Format || NumArgs <= Idx)
3958     return;
3959   const Expr *FormatExpr = Args[Idx];
3960   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
3961     FormatExpr = CSCE->getSubExpr();
3962   const StringLiteral *FormatString;
3963   if (const ObjCStringLiteral *OSL =
3964       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
3965     FormatString = OSL->getString();
3966   else
3967     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
3968   if (!FormatString)
3969     return;
3970   if (S.FormatStringHasSArg(FormatString)) {
3971     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
3972       << "%s" << 1 << 1;
3973     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
3974       << FDecl->getDeclName();
3975   }
3976 }
3977 
3978 /// Determine whether the given type has a non-null nullability annotation.
3979 static bool isNonNullType(ASTContext &ctx, QualType type) {
3980   if (auto nullability = type->getNullability(ctx))
3981     return *nullability == NullabilityKind::NonNull;
3982 
3983   return false;
3984 }
3985 
3986 static void CheckNonNullArguments(Sema &S,
3987                                   const NamedDecl *FDecl,
3988                                   const FunctionProtoType *Proto,
3989                                   ArrayRef<const Expr *> Args,
3990                                   SourceLocation CallSiteLoc) {
3991   assert((FDecl || Proto) && "Need a function declaration or prototype");
3992 
3993   // Already checked by by constant evaluator.
3994   if (S.isConstantEvaluated())
3995     return;
3996   // Check the attributes attached to the method/function itself.
3997   llvm::SmallBitVector NonNullArgs;
3998   if (FDecl) {
3999     // Handle the nonnull attribute on the function/method declaration itself.
4000     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4001       if (!NonNull->args_size()) {
4002         // Easy case: all pointer arguments are nonnull.
4003         for (const auto *Arg : Args)
4004           if (S.isValidPointerAttrType(Arg->getType()))
4005             CheckNonNullArgument(S, Arg, CallSiteLoc);
4006         return;
4007       }
4008 
4009       for (const ParamIdx &Idx : NonNull->args()) {
4010         unsigned IdxAST = Idx.getASTIndex();
4011         if (IdxAST >= Args.size())
4012           continue;
4013         if (NonNullArgs.empty())
4014           NonNullArgs.resize(Args.size());
4015         NonNullArgs.set(IdxAST);
4016       }
4017     }
4018   }
4019 
4020   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4021     // Handle the nonnull attribute on the parameters of the
4022     // function/method.
4023     ArrayRef<ParmVarDecl*> parms;
4024     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4025       parms = FD->parameters();
4026     else
4027       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4028 
4029     unsigned ParamIndex = 0;
4030     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4031          I != E; ++I, ++ParamIndex) {
4032       const ParmVarDecl *PVD = *I;
4033       if (PVD->hasAttr<NonNullAttr>() ||
4034           isNonNullType(S.Context, PVD->getType())) {
4035         if (NonNullArgs.empty())
4036           NonNullArgs.resize(Args.size());
4037 
4038         NonNullArgs.set(ParamIndex);
4039       }
4040     }
4041   } else {
4042     // If we have a non-function, non-method declaration but no
4043     // function prototype, try to dig out the function prototype.
4044     if (!Proto) {
4045       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4046         QualType type = VD->getType().getNonReferenceType();
4047         if (auto pointerType = type->getAs<PointerType>())
4048           type = pointerType->getPointeeType();
4049         else if (auto blockType = type->getAs<BlockPointerType>())
4050           type = blockType->getPointeeType();
4051         // FIXME: data member pointers?
4052 
4053         // Dig out the function prototype, if there is one.
4054         Proto = type->getAs<FunctionProtoType>();
4055       }
4056     }
4057 
4058     // Fill in non-null argument information from the nullability
4059     // information on the parameter types (if we have them).
4060     if (Proto) {
4061       unsigned Index = 0;
4062       for (auto paramType : Proto->getParamTypes()) {
4063         if (isNonNullType(S.Context, paramType)) {
4064           if (NonNullArgs.empty())
4065             NonNullArgs.resize(Args.size());
4066 
4067           NonNullArgs.set(Index);
4068         }
4069 
4070         ++Index;
4071       }
4072     }
4073   }
4074 
4075   // Check for non-null arguments.
4076   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4077        ArgIndex != ArgIndexEnd; ++ArgIndex) {
4078     if (NonNullArgs[ArgIndex])
4079       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4080   }
4081 }
4082 
4083 /// Handles the checks for format strings, non-POD arguments to vararg
4084 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4085 /// attributes.
4086 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4087                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
4088                      bool IsMemberFunction, SourceLocation Loc,
4089                      SourceRange Range, VariadicCallType CallType) {
4090   // FIXME: We should check as much as we can in the template definition.
4091   if (CurContext->isDependentContext())
4092     return;
4093 
4094   // Printf and scanf checking.
4095   llvm::SmallBitVector CheckedVarArgs;
4096   if (FDecl) {
4097     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4098       // Only create vector if there are format attributes.
4099       CheckedVarArgs.resize(Args.size());
4100 
4101       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4102                            CheckedVarArgs);
4103     }
4104   }
4105 
4106   // Refuse POD arguments that weren't caught by the format string
4107   // checks above.
4108   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4109   if (CallType != VariadicDoesNotApply &&
4110       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4111     unsigned NumParams = Proto ? Proto->getNumParams()
4112                        : FDecl && isa<FunctionDecl>(FDecl)
4113                            ? cast<FunctionDecl>(FDecl)->getNumParams()
4114                        : FDecl && isa<ObjCMethodDecl>(FDecl)
4115                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
4116                        : 0;
4117 
4118     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4119       // Args[ArgIdx] can be null in malformed code.
4120       if (const Expr *Arg = Args[ArgIdx]) {
4121         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4122           checkVariadicArgument(Arg, CallType);
4123       }
4124     }
4125   }
4126 
4127   if (FDecl || Proto) {
4128     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4129 
4130     // Type safety checking.
4131     if (FDecl) {
4132       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4133         CheckArgumentWithTypeTag(I, Args, Loc);
4134     }
4135   }
4136 
4137   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4138     auto *AA = FDecl->getAttr<AllocAlignAttr>();
4139     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4140     if (!Arg->isValueDependent()) {
4141       Expr::EvalResult Align;
4142       if (Arg->EvaluateAsInt(Align, Context)) {
4143         const llvm::APSInt &I = Align.Val.getInt();
4144         if (!I.isPowerOf2())
4145           Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
4146               << Arg->getSourceRange();
4147 
4148         if (I > Sema::MaximumAlignment)
4149           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
4150               << Arg->getSourceRange() << Sema::MaximumAlignment;
4151       }
4152     }
4153   }
4154 
4155   if (FD)
4156     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4157 }
4158 
4159 /// CheckConstructorCall - Check a constructor call for correctness and safety
4160 /// properties not enforced by the C type system.
4161 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
4162                                 ArrayRef<const Expr *> Args,
4163                                 const FunctionProtoType *Proto,
4164                                 SourceLocation Loc) {
4165   VariadicCallType CallType =
4166     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4167   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4168             Loc, SourceRange(), CallType);
4169 }
4170 
4171 /// CheckFunctionCall - Check a direct function call for various correctness
4172 /// and safety properties not strictly enforced by the C type system.
4173 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4174                              const FunctionProtoType *Proto) {
4175   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4176                               isa<CXXMethodDecl>(FDecl);
4177   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4178                           IsMemberOperatorCall;
4179   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4180                                                   TheCall->getCallee());
4181   Expr** Args = TheCall->getArgs();
4182   unsigned NumArgs = TheCall->getNumArgs();
4183 
4184   Expr *ImplicitThis = nullptr;
4185   if (IsMemberOperatorCall) {
4186     // If this is a call to a member operator, hide the first argument
4187     // from checkCall.
4188     // FIXME: Our choice of AST representation here is less than ideal.
4189     ImplicitThis = Args[0];
4190     ++Args;
4191     --NumArgs;
4192   } else if (IsMemberFunction)
4193     ImplicitThis =
4194         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4195 
4196   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
4197             IsMemberFunction, TheCall->getRParenLoc(),
4198             TheCall->getCallee()->getSourceRange(), CallType);
4199 
4200   IdentifierInfo *FnInfo = FDecl->getIdentifier();
4201   // None of the checks below are needed for functions that don't have
4202   // simple names (e.g., C++ conversion functions).
4203   if (!FnInfo)
4204     return false;
4205 
4206   CheckAbsoluteValueFunction(TheCall, FDecl);
4207   CheckMaxUnsignedZero(TheCall, FDecl);
4208 
4209   if (getLangOpts().ObjC)
4210     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
4211 
4212   unsigned CMId = FDecl->getMemoryFunctionKind();
4213   if (CMId == 0)
4214     return false;
4215 
4216   // Handle memory setting and copying functions.
4217   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
4218     CheckStrlcpycatArguments(TheCall, FnInfo);
4219   else if (CMId == Builtin::BIstrncat)
4220     CheckStrncatArguments(TheCall, FnInfo);
4221   else
4222     CheckMemaccessArguments(TheCall, CMId, FnInfo);
4223 
4224   return false;
4225 }
4226 
4227 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
4228                                ArrayRef<const Expr *> Args) {
4229   VariadicCallType CallType =
4230       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
4231 
4232   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
4233             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
4234             CallType);
4235 
4236   return false;
4237 }
4238 
4239 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4240                             const FunctionProtoType *Proto) {
4241   QualType Ty;
4242   if (const auto *V = dyn_cast<VarDecl>(NDecl))
4243     Ty = V->getType().getNonReferenceType();
4244   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4245     Ty = F->getType().getNonReferenceType();
4246   else
4247     return false;
4248 
4249   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4250       !Ty->isFunctionProtoType())
4251     return false;
4252 
4253   VariadicCallType CallType;
4254   if (!Proto || !Proto->isVariadic()) {
4255     CallType = VariadicDoesNotApply;
4256   } else if (Ty->isBlockPointerType()) {
4257     CallType = VariadicBlock;
4258   } else { // Ty->isFunctionPointerType()
4259     CallType = VariadicFunction;
4260   }
4261 
4262   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4263             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4264             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4265             TheCall->getCallee()->getSourceRange(), CallType);
4266 
4267   return false;
4268 }
4269 
4270 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
4271 /// such as function pointers returned from functions.
4272 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4273   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4274                                                   TheCall->getCallee());
4275   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4276             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4277             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4278             TheCall->getCallee()->getSourceRange(), CallType);
4279 
4280   return false;
4281 }
4282 
4283 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4284   if (!llvm::isValidAtomicOrderingCABI(Ordering))
4285     return false;
4286 
4287   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4288   switch (Op) {
4289   case AtomicExpr::AO__c11_atomic_init:
4290   case AtomicExpr::AO__opencl_atomic_init:
4291     llvm_unreachable("There is no ordering argument for an init");
4292 
4293   case AtomicExpr::AO__c11_atomic_load:
4294   case AtomicExpr::AO__opencl_atomic_load:
4295   case AtomicExpr::AO__atomic_load_n:
4296   case AtomicExpr::AO__atomic_load:
4297     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4298            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4299 
4300   case AtomicExpr::AO__c11_atomic_store:
4301   case AtomicExpr::AO__opencl_atomic_store:
4302   case AtomicExpr::AO__atomic_store:
4303   case AtomicExpr::AO__atomic_store_n:
4304     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4305            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4306            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4307 
4308   default:
4309     return true;
4310   }
4311 }
4312 
4313 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
4314                                          AtomicExpr::AtomicOp Op) {
4315   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4316   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4317   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4318   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
4319                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
4320                          Op);
4321 }
4322 
4323 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
4324                                  SourceLocation RParenLoc, MultiExprArg Args,
4325                                  AtomicExpr::AtomicOp Op,
4326                                  AtomicArgumentOrder ArgOrder) {
4327   // All the non-OpenCL operations take one of the following forms.
4328   // The OpenCL operations take the __c11 forms with one extra argument for
4329   // synchronization scope.
4330   enum {
4331     // C    __c11_atomic_init(A *, C)
4332     Init,
4333 
4334     // C    __c11_atomic_load(A *, int)
4335     Load,
4336 
4337     // void __atomic_load(A *, CP, int)
4338     LoadCopy,
4339 
4340     // void __atomic_store(A *, CP, int)
4341     Copy,
4342 
4343     // C    __c11_atomic_add(A *, M, int)
4344     Arithmetic,
4345 
4346     // C    __atomic_exchange_n(A *, CP, int)
4347     Xchg,
4348 
4349     // void __atomic_exchange(A *, C *, CP, int)
4350     GNUXchg,
4351 
4352     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4353     C11CmpXchg,
4354 
4355     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4356     GNUCmpXchg
4357   } Form = Init;
4358 
4359   const unsigned NumForm = GNUCmpXchg + 1;
4360   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
4361   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
4362   // where:
4363   //   C is an appropriate type,
4364   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4365   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4366   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4367   //   the int parameters are for orderings.
4368 
4369   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4370       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4371       "need to update code for modified forms");
4372   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
4373                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
4374                         AtomicExpr::AO__atomic_load,
4375                 "need to update code for modified C11 atomics");
4376   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
4377                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
4378   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
4379                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
4380                IsOpenCL;
4381   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4382              Op == AtomicExpr::AO__atomic_store_n ||
4383              Op == AtomicExpr::AO__atomic_exchange_n ||
4384              Op == AtomicExpr::AO__atomic_compare_exchange_n;
4385   bool IsAddSub = false;
4386 
4387   switch (Op) {
4388   case AtomicExpr::AO__c11_atomic_init:
4389   case AtomicExpr::AO__opencl_atomic_init:
4390     Form = Init;
4391     break;
4392 
4393   case AtomicExpr::AO__c11_atomic_load:
4394   case AtomicExpr::AO__opencl_atomic_load:
4395   case AtomicExpr::AO__atomic_load_n:
4396     Form = Load;
4397     break;
4398 
4399   case AtomicExpr::AO__atomic_load:
4400     Form = LoadCopy;
4401     break;
4402 
4403   case AtomicExpr::AO__c11_atomic_store:
4404   case AtomicExpr::AO__opencl_atomic_store:
4405   case AtomicExpr::AO__atomic_store:
4406   case AtomicExpr::AO__atomic_store_n:
4407     Form = Copy;
4408     break;
4409 
4410   case AtomicExpr::AO__c11_atomic_fetch_add:
4411   case AtomicExpr::AO__c11_atomic_fetch_sub:
4412   case AtomicExpr::AO__opencl_atomic_fetch_add:
4413   case AtomicExpr::AO__opencl_atomic_fetch_sub:
4414   case AtomicExpr::AO__atomic_fetch_add:
4415   case AtomicExpr::AO__atomic_fetch_sub:
4416   case AtomicExpr::AO__atomic_add_fetch:
4417   case AtomicExpr::AO__atomic_sub_fetch:
4418     IsAddSub = true;
4419     LLVM_FALLTHROUGH;
4420   case AtomicExpr::AO__c11_atomic_fetch_and:
4421   case AtomicExpr::AO__c11_atomic_fetch_or:
4422   case AtomicExpr::AO__c11_atomic_fetch_xor:
4423   case AtomicExpr::AO__opencl_atomic_fetch_and:
4424   case AtomicExpr::AO__opencl_atomic_fetch_or:
4425   case AtomicExpr::AO__opencl_atomic_fetch_xor:
4426   case AtomicExpr::AO__atomic_fetch_and:
4427   case AtomicExpr::AO__atomic_fetch_or:
4428   case AtomicExpr::AO__atomic_fetch_xor:
4429   case AtomicExpr::AO__atomic_fetch_nand:
4430   case AtomicExpr::AO__atomic_and_fetch:
4431   case AtomicExpr::AO__atomic_or_fetch:
4432   case AtomicExpr::AO__atomic_xor_fetch:
4433   case AtomicExpr::AO__atomic_nand_fetch:
4434   case AtomicExpr::AO__c11_atomic_fetch_min:
4435   case AtomicExpr::AO__c11_atomic_fetch_max:
4436   case AtomicExpr::AO__opencl_atomic_fetch_min:
4437   case AtomicExpr::AO__opencl_atomic_fetch_max:
4438   case AtomicExpr::AO__atomic_min_fetch:
4439   case AtomicExpr::AO__atomic_max_fetch:
4440   case AtomicExpr::AO__atomic_fetch_min:
4441   case AtomicExpr::AO__atomic_fetch_max:
4442     Form = Arithmetic;
4443     break;
4444 
4445   case AtomicExpr::AO__c11_atomic_exchange:
4446   case AtomicExpr::AO__opencl_atomic_exchange:
4447   case AtomicExpr::AO__atomic_exchange_n:
4448     Form = Xchg;
4449     break;
4450 
4451   case AtomicExpr::AO__atomic_exchange:
4452     Form = GNUXchg;
4453     break;
4454 
4455   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4456   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4457   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4458   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4459     Form = C11CmpXchg;
4460     break;
4461 
4462   case AtomicExpr::AO__atomic_compare_exchange:
4463   case AtomicExpr::AO__atomic_compare_exchange_n:
4464     Form = GNUCmpXchg;
4465     break;
4466   }
4467 
4468   unsigned AdjustedNumArgs = NumArgs[Form];
4469   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
4470     ++AdjustedNumArgs;
4471   // Check we have the right number of arguments.
4472   if (Args.size() < AdjustedNumArgs) {
4473     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
4474         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4475         << ExprRange;
4476     return ExprError();
4477   } else if (Args.size() > AdjustedNumArgs) {
4478     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
4479          diag::err_typecheck_call_too_many_args)
4480         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4481         << ExprRange;
4482     return ExprError();
4483   }
4484 
4485   // Inspect the first argument of the atomic operation.
4486   Expr *Ptr = Args[0];
4487   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
4488   if (ConvertedPtr.isInvalid())
4489     return ExprError();
4490 
4491   Ptr = ConvertedPtr.get();
4492   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4493   if (!pointerType) {
4494     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
4495         << Ptr->getType() << Ptr->getSourceRange();
4496     return ExprError();
4497   }
4498 
4499   // For a __c11 builtin, this should be a pointer to an _Atomic type.
4500   QualType AtomTy = pointerType->getPointeeType(); // 'A'
4501   QualType ValType = AtomTy; // 'C'
4502   if (IsC11) {
4503     if (!AtomTy->isAtomicType()) {
4504       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
4505           << Ptr->getType() << Ptr->getSourceRange();
4506       return ExprError();
4507     }
4508     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
4509         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
4510       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
4511           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4512           << Ptr->getSourceRange();
4513       return ExprError();
4514     }
4515     ValType = AtomTy->castAs<AtomicType>()->getValueType();
4516   } else if (Form != Load && Form != LoadCopy) {
4517     if (ValType.isConstQualified()) {
4518       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
4519           << Ptr->getType() << Ptr->getSourceRange();
4520       return ExprError();
4521     }
4522   }
4523 
4524   // For an arithmetic operation, the implied arithmetic must be well-formed.
4525   if (Form == Arithmetic) {
4526     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
4527     if (IsAddSub && !ValType->isIntegerType()
4528         && !ValType->isPointerType()) {
4529       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4530           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4531       return ExprError();
4532     }
4533     if (!IsAddSub && !ValType->isIntegerType()) {
4534       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
4535           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4536       return ExprError();
4537     }
4538     if (IsC11 && ValType->isPointerType() &&
4539         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
4540                             diag::err_incomplete_type)) {
4541       return ExprError();
4542     }
4543   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
4544     // For __atomic_*_n operations, the value type must be a scalar integral or
4545     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
4546     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4547         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4548     return ExprError();
4549   }
4550 
4551   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4552       !AtomTy->isScalarType()) {
4553     // For GNU atomics, require a trivially-copyable type. This is not part of
4554     // the GNU atomics specification, but we enforce it for sanity.
4555     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
4556         << Ptr->getType() << Ptr->getSourceRange();
4557     return ExprError();
4558   }
4559 
4560   switch (ValType.getObjCLifetime()) {
4561   case Qualifiers::OCL_None:
4562   case Qualifiers::OCL_ExplicitNone:
4563     // okay
4564     break;
4565 
4566   case Qualifiers::OCL_Weak:
4567   case Qualifiers::OCL_Strong:
4568   case Qualifiers::OCL_Autoreleasing:
4569     // FIXME: Can this happen? By this point, ValType should be known
4570     // to be trivially copyable.
4571     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
4572         << ValType << Ptr->getSourceRange();
4573     return ExprError();
4574   }
4575 
4576   // All atomic operations have an overload which takes a pointer to a volatile
4577   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
4578   // into the result or the other operands. Similarly atomic_load takes a
4579   // pointer to a const 'A'.
4580   ValType.removeLocalVolatile();
4581   ValType.removeLocalConst();
4582   QualType ResultType = ValType;
4583   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
4584       Form == Init)
4585     ResultType = Context.VoidTy;
4586   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
4587     ResultType = Context.BoolTy;
4588 
4589   // The type of a parameter passed 'by value'. In the GNU atomics, such
4590   // arguments are actually passed as pointers.
4591   QualType ByValType = ValType; // 'CP'
4592   bool IsPassedByAddress = false;
4593   if (!IsC11 && !IsN) {
4594     ByValType = Ptr->getType();
4595     IsPassedByAddress = true;
4596   }
4597 
4598   SmallVector<Expr *, 5> APIOrderedArgs;
4599   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
4600     APIOrderedArgs.push_back(Args[0]);
4601     switch (Form) {
4602     case Init:
4603     case Load:
4604       APIOrderedArgs.push_back(Args[1]); // Val1/Order
4605       break;
4606     case LoadCopy:
4607     case Copy:
4608     case Arithmetic:
4609     case Xchg:
4610       APIOrderedArgs.push_back(Args[2]); // Val1
4611       APIOrderedArgs.push_back(Args[1]); // Order
4612       break;
4613     case GNUXchg:
4614       APIOrderedArgs.push_back(Args[2]); // Val1
4615       APIOrderedArgs.push_back(Args[3]); // Val2
4616       APIOrderedArgs.push_back(Args[1]); // Order
4617       break;
4618     case C11CmpXchg:
4619       APIOrderedArgs.push_back(Args[2]); // Val1
4620       APIOrderedArgs.push_back(Args[4]); // Val2
4621       APIOrderedArgs.push_back(Args[1]); // Order
4622       APIOrderedArgs.push_back(Args[3]); // OrderFail
4623       break;
4624     case GNUCmpXchg:
4625       APIOrderedArgs.push_back(Args[2]); // Val1
4626       APIOrderedArgs.push_back(Args[4]); // Val2
4627       APIOrderedArgs.push_back(Args[5]); // Weak
4628       APIOrderedArgs.push_back(Args[1]); // Order
4629       APIOrderedArgs.push_back(Args[3]); // OrderFail
4630       break;
4631     }
4632   } else
4633     APIOrderedArgs.append(Args.begin(), Args.end());
4634 
4635   // The first argument's non-CV pointer type is used to deduce the type of
4636   // subsequent arguments, except for:
4637   //  - weak flag (always converted to bool)
4638   //  - memory order (always converted to int)
4639   //  - scope  (always converted to int)
4640   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
4641     QualType Ty;
4642     if (i < NumVals[Form] + 1) {
4643       switch (i) {
4644       case 0:
4645         // The first argument is always a pointer. It has a fixed type.
4646         // It is always dereferenced, a nullptr is undefined.
4647         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4648         // Nothing else to do: we already know all we want about this pointer.
4649         continue;
4650       case 1:
4651         // The second argument is the non-atomic operand. For arithmetic, this
4652         // is always passed by value, and for a compare_exchange it is always
4653         // passed by address. For the rest, GNU uses by-address and C11 uses
4654         // by-value.
4655         assert(Form != Load);
4656         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
4657           Ty = ValType;
4658         else if (Form == Copy || Form == Xchg) {
4659           if (IsPassedByAddress) {
4660             // The value pointer is always dereferenced, a nullptr is undefined.
4661             CheckNonNullArgument(*this, APIOrderedArgs[i],
4662                                  ExprRange.getBegin());
4663           }
4664           Ty = ByValType;
4665         } else if (Form == Arithmetic)
4666           Ty = Context.getPointerDiffType();
4667         else {
4668           Expr *ValArg = APIOrderedArgs[i];
4669           // The value pointer is always dereferenced, a nullptr is undefined.
4670           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
4671           LangAS AS = LangAS::Default;
4672           // Keep address space of non-atomic pointer type.
4673           if (const PointerType *PtrTy =
4674                   ValArg->getType()->getAs<PointerType>()) {
4675             AS = PtrTy->getPointeeType().getAddressSpace();
4676           }
4677           Ty = Context.getPointerType(
4678               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
4679         }
4680         break;
4681       case 2:
4682         // The third argument to compare_exchange / GNU exchange is the desired
4683         // value, either by-value (for the C11 and *_n variant) or as a pointer.
4684         if (IsPassedByAddress)
4685           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4686         Ty = ByValType;
4687         break;
4688       case 3:
4689         // The fourth argument to GNU compare_exchange is a 'weak' flag.
4690         Ty = Context.BoolTy;
4691         break;
4692       }
4693     } else {
4694       // The order(s) and scope are always converted to int.
4695       Ty = Context.IntTy;
4696     }
4697 
4698     InitializedEntity Entity =
4699         InitializedEntity::InitializeParameter(Context, Ty, false);
4700     ExprResult Arg = APIOrderedArgs[i];
4701     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4702     if (Arg.isInvalid())
4703       return true;
4704     APIOrderedArgs[i] = Arg.get();
4705   }
4706 
4707   // Permute the arguments into a 'consistent' order.
4708   SmallVector<Expr*, 5> SubExprs;
4709   SubExprs.push_back(Ptr);
4710   switch (Form) {
4711   case Init:
4712     // Note, AtomicExpr::getVal1() has a special case for this atomic.
4713     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4714     break;
4715   case Load:
4716     SubExprs.push_back(APIOrderedArgs[1]); // Order
4717     break;
4718   case LoadCopy:
4719   case Copy:
4720   case Arithmetic:
4721   case Xchg:
4722     SubExprs.push_back(APIOrderedArgs[2]); // Order
4723     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4724     break;
4725   case GNUXchg:
4726     // Note, AtomicExpr::getVal2() has a special case for this atomic.
4727     SubExprs.push_back(APIOrderedArgs[3]); // Order
4728     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4729     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4730     break;
4731   case C11CmpXchg:
4732     SubExprs.push_back(APIOrderedArgs[3]); // Order
4733     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4734     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
4735     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4736     break;
4737   case GNUCmpXchg:
4738     SubExprs.push_back(APIOrderedArgs[4]); // Order
4739     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4740     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
4741     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4742     SubExprs.push_back(APIOrderedArgs[3]); // Weak
4743     break;
4744   }
4745 
4746   if (SubExprs.size() >= 2 && Form != Init) {
4747     llvm::APSInt Result(32);
4748     if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
4749         !isValidOrderingForOp(Result.getSExtValue(), Op))
4750       Diag(SubExprs[1]->getBeginLoc(),
4751            diag::warn_atomic_op_has_invalid_memory_order)
4752           << SubExprs[1]->getSourceRange();
4753   }
4754 
4755   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
4756     auto *Scope = Args[Args.size() - 1];
4757     llvm::APSInt Result(32);
4758     if (Scope->isIntegerConstantExpr(Result, Context) &&
4759         !ScopeModel->isValid(Result.getZExtValue())) {
4760       Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
4761           << Scope->getSourceRange();
4762     }
4763     SubExprs.push_back(Scope);
4764   }
4765 
4766   AtomicExpr *AE = new (Context)
4767       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
4768 
4769   if ((Op == AtomicExpr::AO__c11_atomic_load ||
4770        Op == AtomicExpr::AO__c11_atomic_store ||
4771        Op == AtomicExpr::AO__opencl_atomic_load ||
4772        Op == AtomicExpr::AO__opencl_atomic_store ) &&
4773       Context.AtomicUsesUnsupportedLibcall(AE))
4774     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
4775         << ((Op == AtomicExpr::AO__c11_atomic_load ||
4776              Op == AtomicExpr::AO__opencl_atomic_load)
4777                 ? 0
4778                 : 1);
4779 
4780   return AE;
4781 }
4782 
4783 /// checkBuiltinArgument - Given a call to a builtin function, perform
4784 /// normal type-checking on the given argument, updating the call in
4785 /// place.  This is useful when a builtin function requires custom
4786 /// type-checking for some of its arguments but not necessarily all of
4787 /// them.
4788 ///
4789 /// Returns true on error.
4790 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
4791   FunctionDecl *Fn = E->getDirectCallee();
4792   assert(Fn && "builtin call without direct callee!");
4793 
4794   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
4795   InitializedEntity Entity =
4796     InitializedEntity::InitializeParameter(S.Context, Param);
4797 
4798   ExprResult Arg = E->getArg(0);
4799   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
4800   if (Arg.isInvalid())
4801     return true;
4802 
4803   E->setArg(ArgIndex, Arg.get());
4804   return false;
4805 }
4806 
4807 /// We have a call to a function like __sync_fetch_and_add, which is an
4808 /// overloaded function based on the pointer type of its first argument.
4809 /// The main BuildCallExpr routines have already promoted the types of
4810 /// arguments because all of these calls are prototyped as void(...).
4811 ///
4812 /// This function goes through and does final semantic checking for these
4813 /// builtins, as well as generating any warnings.
4814 ExprResult
4815 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
4816   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
4817   Expr *Callee = TheCall->getCallee();
4818   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
4819   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4820 
4821   // Ensure that we have at least one argument to do type inference from.
4822   if (TheCall->getNumArgs() < 1) {
4823     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
4824         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
4825     return ExprError();
4826   }
4827 
4828   // Inspect the first argument of the atomic builtin.  This should always be
4829   // a pointer type, whose element is an integral scalar or pointer type.
4830   // Because it is a pointer type, we don't have to worry about any implicit
4831   // casts here.
4832   // FIXME: We don't allow floating point scalars as input.
4833   Expr *FirstArg = TheCall->getArg(0);
4834   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
4835   if (FirstArgResult.isInvalid())
4836     return ExprError();
4837   FirstArg = FirstArgResult.get();
4838   TheCall->setArg(0, FirstArg);
4839 
4840   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
4841   if (!pointerType) {
4842     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
4843         << FirstArg->getType() << FirstArg->getSourceRange();
4844     return ExprError();
4845   }
4846 
4847   QualType ValType = pointerType->getPointeeType();
4848   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
4849       !ValType->isBlockPointerType()) {
4850     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
4851         << FirstArg->getType() << FirstArg->getSourceRange();
4852     return ExprError();
4853   }
4854 
4855   if (ValType.isConstQualified()) {
4856     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
4857         << FirstArg->getType() << FirstArg->getSourceRange();
4858     return ExprError();
4859   }
4860 
4861   switch (ValType.getObjCLifetime()) {
4862   case Qualifiers::OCL_None:
4863   case Qualifiers::OCL_ExplicitNone:
4864     // okay
4865     break;
4866 
4867   case Qualifiers::OCL_Weak:
4868   case Qualifiers::OCL_Strong:
4869   case Qualifiers::OCL_Autoreleasing:
4870     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
4871         << ValType << FirstArg->getSourceRange();
4872     return ExprError();
4873   }
4874 
4875   // Strip any qualifiers off ValType.
4876   ValType = ValType.getUnqualifiedType();
4877 
4878   // The majority of builtins return a value, but a few have special return
4879   // types, so allow them to override appropriately below.
4880   QualType ResultType = ValType;
4881 
4882   // We need to figure out which concrete builtin this maps onto.  For example,
4883   // __sync_fetch_and_add with a 2 byte object turns into
4884   // __sync_fetch_and_add_2.
4885 #define BUILTIN_ROW(x) \
4886   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
4887     Builtin::BI##x##_8, Builtin::BI##x##_16 }
4888 
4889   static const unsigned BuiltinIndices[][5] = {
4890     BUILTIN_ROW(__sync_fetch_and_add),
4891     BUILTIN_ROW(__sync_fetch_and_sub),
4892     BUILTIN_ROW(__sync_fetch_and_or),
4893     BUILTIN_ROW(__sync_fetch_and_and),
4894     BUILTIN_ROW(__sync_fetch_and_xor),
4895     BUILTIN_ROW(__sync_fetch_and_nand),
4896 
4897     BUILTIN_ROW(__sync_add_and_fetch),
4898     BUILTIN_ROW(__sync_sub_and_fetch),
4899     BUILTIN_ROW(__sync_and_and_fetch),
4900     BUILTIN_ROW(__sync_or_and_fetch),
4901     BUILTIN_ROW(__sync_xor_and_fetch),
4902     BUILTIN_ROW(__sync_nand_and_fetch),
4903 
4904     BUILTIN_ROW(__sync_val_compare_and_swap),
4905     BUILTIN_ROW(__sync_bool_compare_and_swap),
4906     BUILTIN_ROW(__sync_lock_test_and_set),
4907     BUILTIN_ROW(__sync_lock_release),
4908     BUILTIN_ROW(__sync_swap)
4909   };
4910 #undef BUILTIN_ROW
4911 
4912   // Determine the index of the size.
4913   unsigned SizeIndex;
4914   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
4915   case 1: SizeIndex = 0; break;
4916   case 2: SizeIndex = 1; break;
4917   case 4: SizeIndex = 2; break;
4918   case 8: SizeIndex = 3; break;
4919   case 16: SizeIndex = 4; break;
4920   default:
4921     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
4922         << FirstArg->getType() << FirstArg->getSourceRange();
4923     return ExprError();
4924   }
4925 
4926   // Each of these builtins has one pointer argument, followed by some number of
4927   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
4928   // that we ignore.  Find out which row of BuiltinIndices to read from as well
4929   // as the number of fixed args.
4930   unsigned BuiltinID = FDecl->getBuiltinID();
4931   unsigned BuiltinIndex, NumFixed = 1;
4932   bool WarnAboutSemanticsChange = false;
4933   switch (BuiltinID) {
4934   default: llvm_unreachable("Unknown overloaded atomic builtin!");
4935   case Builtin::BI__sync_fetch_and_add:
4936   case Builtin::BI__sync_fetch_and_add_1:
4937   case Builtin::BI__sync_fetch_and_add_2:
4938   case Builtin::BI__sync_fetch_and_add_4:
4939   case Builtin::BI__sync_fetch_and_add_8:
4940   case Builtin::BI__sync_fetch_and_add_16:
4941     BuiltinIndex = 0;
4942     break;
4943 
4944   case Builtin::BI__sync_fetch_and_sub:
4945   case Builtin::BI__sync_fetch_and_sub_1:
4946   case Builtin::BI__sync_fetch_and_sub_2:
4947   case Builtin::BI__sync_fetch_and_sub_4:
4948   case Builtin::BI__sync_fetch_and_sub_8:
4949   case Builtin::BI__sync_fetch_and_sub_16:
4950     BuiltinIndex = 1;
4951     break;
4952 
4953   case Builtin::BI__sync_fetch_and_or:
4954   case Builtin::BI__sync_fetch_and_or_1:
4955   case Builtin::BI__sync_fetch_and_or_2:
4956   case Builtin::BI__sync_fetch_and_or_4:
4957   case Builtin::BI__sync_fetch_and_or_8:
4958   case Builtin::BI__sync_fetch_and_or_16:
4959     BuiltinIndex = 2;
4960     break;
4961 
4962   case Builtin::BI__sync_fetch_and_and:
4963   case Builtin::BI__sync_fetch_and_and_1:
4964   case Builtin::BI__sync_fetch_and_and_2:
4965   case Builtin::BI__sync_fetch_and_and_4:
4966   case Builtin::BI__sync_fetch_and_and_8:
4967   case Builtin::BI__sync_fetch_and_and_16:
4968     BuiltinIndex = 3;
4969     break;
4970 
4971   case Builtin::BI__sync_fetch_and_xor:
4972   case Builtin::BI__sync_fetch_and_xor_1:
4973   case Builtin::BI__sync_fetch_and_xor_2:
4974   case Builtin::BI__sync_fetch_and_xor_4:
4975   case Builtin::BI__sync_fetch_and_xor_8:
4976   case Builtin::BI__sync_fetch_and_xor_16:
4977     BuiltinIndex = 4;
4978     break;
4979 
4980   case Builtin::BI__sync_fetch_and_nand:
4981   case Builtin::BI__sync_fetch_and_nand_1:
4982   case Builtin::BI__sync_fetch_and_nand_2:
4983   case Builtin::BI__sync_fetch_and_nand_4:
4984   case Builtin::BI__sync_fetch_and_nand_8:
4985   case Builtin::BI__sync_fetch_and_nand_16:
4986     BuiltinIndex = 5;
4987     WarnAboutSemanticsChange = true;
4988     break;
4989 
4990   case Builtin::BI__sync_add_and_fetch:
4991   case Builtin::BI__sync_add_and_fetch_1:
4992   case Builtin::BI__sync_add_and_fetch_2:
4993   case Builtin::BI__sync_add_and_fetch_4:
4994   case Builtin::BI__sync_add_and_fetch_8:
4995   case Builtin::BI__sync_add_and_fetch_16:
4996     BuiltinIndex = 6;
4997     break;
4998 
4999   case Builtin::BI__sync_sub_and_fetch:
5000   case Builtin::BI__sync_sub_and_fetch_1:
5001   case Builtin::BI__sync_sub_and_fetch_2:
5002   case Builtin::BI__sync_sub_and_fetch_4:
5003   case Builtin::BI__sync_sub_and_fetch_8:
5004   case Builtin::BI__sync_sub_and_fetch_16:
5005     BuiltinIndex = 7;
5006     break;
5007 
5008   case Builtin::BI__sync_and_and_fetch:
5009   case Builtin::BI__sync_and_and_fetch_1:
5010   case Builtin::BI__sync_and_and_fetch_2:
5011   case Builtin::BI__sync_and_and_fetch_4:
5012   case Builtin::BI__sync_and_and_fetch_8:
5013   case Builtin::BI__sync_and_and_fetch_16:
5014     BuiltinIndex = 8;
5015     break;
5016 
5017   case Builtin::BI__sync_or_and_fetch:
5018   case Builtin::BI__sync_or_and_fetch_1:
5019   case Builtin::BI__sync_or_and_fetch_2:
5020   case Builtin::BI__sync_or_and_fetch_4:
5021   case Builtin::BI__sync_or_and_fetch_8:
5022   case Builtin::BI__sync_or_and_fetch_16:
5023     BuiltinIndex = 9;
5024     break;
5025 
5026   case Builtin::BI__sync_xor_and_fetch:
5027   case Builtin::BI__sync_xor_and_fetch_1:
5028   case Builtin::BI__sync_xor_and_fetch_2:
5029   case Builtin::BI__sync_xor_and_fetch_4:
5030   case Builtin::BI__sync_xor_and_fetch_8:
5031   case Builtin::BI__sync_xor_and_fetch_16:
5032     BuiltinIndex = 10;
5033     break;
5034 
5035   case Builtin::BI__sync_nand_and_fetch:
5036   case Builtin::BI__sync_nand_and_fetch_1:
5037   case Builtin::BI__sync_nand_and_fetch_2:
5038   case Builtin::BI__sync_nand_and_fetch_4:
5039   case Builtin::BI__sync_nand_and_fetch_8:
5040   case Builtin::BI__sync_nand_and_fetch_16:
5041     BuiltinIndex = 11;
5042     WarnAboutSemanticsChange = true;
5043     break;
5044 
5045   case Builtin::BI__sync_val_compare_and_swap:
5046   case Builtin::BI__sync_val_compare_and_swap_1:
5047   case Builtin::BI__sync_val_compare_and_swap_2:
5048   case Builtin::BI__sync_val_compare_and_swap_4:
5049   case Builtin::BI__sync_val_compare_and_swap_8:
5050   case Builtin::BI__sync_val_compare_and_swap_16:
5051     BuiltinIndex = 12;
5052     NumFixed = 2;
5053     break;
5054 
5055   case Builtin::BI__sync_bool_compare_and_swap:
5056   case Builtin::BI__sync_bool_compare_and_swap_1:
5057   case Builtin::BI__sync_bool_compare_and_swap_2:
5058   case Builtin::BI__sync_bool_compare_and_swap_4:
5059   case Builtin::BI__sync_bool_compare_and_swap_8:
5060   case Builtin::BI__sync_bool_compare_and_swap_16:
5061     BuiltinIndex = 13;
5062     NumFixed = 2;
5063     ResultType = Context.BoolTy;
5064     break;
5065 
5066   case Builtin::BI__sync_lock_test_and_set:
5067   case Builtin::BI__sync_lock_test_and_set_1:
5068   case Builtin::BI__sync_lock_test_and_set_2:
5069   case Builtin::BI__sync_lock_test_and_set_4:
5070   case Builtin::BI__sync_lock_test_and_set_8:
5071   case Builtin::BI__sync_lock_test_and_set_16:
5072     BuiltinIndex = 14;
5073     break;
5074 
5075   case Builtin::BI__sync_lock_release:
5076   case Builtin::BI__sync_lock_release_1:
5077   case Builtin::BI__sync_lock_release_2:
5078   case Builtin::BI__sync_lock_release_4:
5079   case Builtin::BI__sync_lock_release_8:
5080   case Builtin::BI__sync_lock_release_16:
5081     BuiltinIndex = 15;
5082     NumFixed = 0;
5083     ResultType = Context.VoidTy;
5084     break;
5085 
5086   case Builtin::BI__sync_swap:
5087   case Builtin::BI__sync_swap_1:
5088   case Builtin::BI__sync_swap_2:
5089   case Builtin::BI__sync_swap_4:
5090   case Builtin::BI__sync_swap_8:
5091   case Builtin::BI__sync_swap_16:
5092     BuiltinIndex = 16;
5093     break;
5094   }
5095 
5096   // Now that we know how many fixed arguments we expect, first check that we
5097   // have at least that many.
5098   if (TheCall->getNumArgs() < 1+NumFixed) {
5099     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5100         << 0 << 1 + NumFixed << TheCall->getNumArgs()
5101         << Callee->getSourceRange();
5102     return ExprError();
5103   }
5104 
5105   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5106       << Callee->getSourceRange();
5107 
5108   if (WarnAboutSemanticsChange) {
5109     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5110         << Callee->getSourceRange();
5111   }
5112 
5113   // Get the decl for the concrete builtin from this, we can tell what the
5114   // concrete integer type we should convert to is.
5115   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5116   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5117   FunctionDecl *NewBuiltinDecl;
5118   if (NewBuiltinID == BuiltinID)
5119     NewBuiltinDecl = FDecl;
5120   else {
5121     // Perform builtin lookup to avoid redeclaring it.
5122     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5123     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5124     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5125     assert(Res.getFoundDecl());
5126     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5127     if (!NewBuiltinDecl)
5128       return ExprError();
5129   }
5130 
5131   // The first argument --- the pointer --- has a fixed type; we
5132   // deduce the types of the rest of the arguments accordingly.  Walk
5133   // the remaining arguments, converting them to the deduced value type.
5134   for (unsigned i = 0; i != NumFixed; ++i) {
5135     ExprResult Arg = TheCall->getArg(i+1);
5136 
5137     // GCC does an implicit conversion to the pointer or integer ValType.  This
5138     // can fail in some cases (1i -> int**), check for this error case now.
5139     // Initialize the argument.
5140     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5141                                                    ValType, /*consume*/ false);
5142     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5143     if (Arg.isInvalid())
5144       return ExprError();
5145 
5146     // Okay, we have something that *can* be converted to the right type.  Check
5147     // to see if there is a potentially weird extension going on here.  This can
5148     // happen when you do an atomic operation on something like an char* and
5149     // pass in 42.  The 42 gets converted to char.  This is even more strange
5150     // for things like 45.123 -> char, etc.
5151     // FIXME: Do this check.
5152     TheCall->setArg(i+1, Arg.get());
5153   }
5154 
5155   // Create a new DeclRefExpr to refer to the new decl.
5156   DeclRefExpr *NewDRE = DeclRefExpr::Create(
5157       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5158       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5159       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
5160 
5161   // Set the callee in the CallExpr.
5162   // FIXME: This loses syntactic information.
5163   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5164   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5165                                               CK_BuiltinFnToFnPtr);
5166   TheCall->setCallee(PromotedCall.get());
5167 
5168   // Change the result type of the call to match the original value type. This
5169   // is arbitrary, but the codegen for these builtins ins design to handle it
5170   // gracefully.
5171   TheCall->setType(ResultType);
5172 
5173   return TheCallResult;
5174 }
5175 
5176 /// SemaBuiltinNontemporalOverloaded - We have a call to
5177 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
5178 /// overloaded function based on the pointer type of its last argument.
5179 ///
5180 /// This function goes through and does final semantic checking for these
5181 /// builtins.
5182 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5183   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5184   DeclRefExpr *DRE =
5185       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5186   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5187   unsigned BuiltinID = FDecl->getBuiltinID();
5188   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5189           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5190          "Unexpected nontemporal load/store builtin!");
5191   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5192   unsigned numArgs = isStore ? 2 : 1;
5193 
5194   // Ensure that we have the proper number of arguments.
5195   if (checkArgCount(*this, TheCall, numArgs))
5196     return ExprError();
5197 
5198   // Inspect the last argument of the nontemporal builtin.  This should always
5199   // be a pointer type, from which we imply the type of the memory access.
5200   // Because it is a pointer type, we don't have to worry about any implicit
5201   // casts here.
5202   Expr *PointerArg = TheCall->getArg(numArgs - 1);
5203   ExprResult PointerArgResult =
5204       DefaultFunctionArrayLvalueConversion(PointerArg);
5205 
5206   if (PointerArgResult.isInvalid())
5207     return ExprError();
5208   PointerArg = PointerArgResult.get();
5209   TheCall->setArg(numArgs - 1, PointerArg);
5210 
5211   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5212   if (!pointerType) {
5213     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5214         << PointerArg->getType() << PointerArg->getSourceRange();
5215     return ExprError();
5216   }
5217 
5218   QualType ValType = pointerType->getPointeeType();
5219 
5220   // Strip any qualifiers off ValType.
5221   ValType = ValType.getUnqualifiedType();
5222   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5223       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5224       !ValType->isVectorType()) {
5225     Diag(DRE->getBeginLoc(),
5226          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5227         << PointerArg->getType() << PointerArg->getSourceRange();
5228     return ExprError();
5229   }
5230 
5231   if (!isStore) {
5232     TheCall->setType(ValType);
5233     return TheCallResult;
5234   }
5235 
5236   ExprResult ValArg = TheCall->getArg(0);
5237   InitializedEntity Entity = InitializedEntity::InitializeParameter(
5238       Context, ValType, /*consume*/ false);
5239   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5240   if (ValArg.isInvalid())
5241     return ExprError();
5242 
5243   TheCall->setArg(0, ValArg.get());
5244   TheCall->setType(Context.VoidTy);
5245   return TheCallResult;
5246 }
5247 
5248 /// CheckObjCString - Checks that the argument to the builtin
5249 /// CFString constructor is correct
5250 /// Note: It might also make sense to do the UTF-16 conversion here (would
5251 /// simplify the backend).
5252 bool Sema::CheckObjCString(Expr *Arg) {
5253   Arg = Arg->IgnoreParenCasts();
5254   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
5255 
5256   if (!Literal || !Literal->isAscii()) {
5257     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
5258         << Arg->getSourceRange();
5259     return true;
5260   }
5261 
5262   if (Literal->containsNonAsciiOrNull()) {
5263     StringRef String = Literal->getString();
5264     unsigned NumBytes = String.size();
5265     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
5266     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5267     llvm::UTF16 *ToPtr = &ToBuf[0];
5268 
5269     llvm::ConversionResult Result =
5270         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5271                                  ToPtr + NumBytes, llvm::strictConversion);
5272     // Check for conversion failure.
5273     if (Result != llvm::conversionOK)
5274       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
5275           << Arg->getSourceRange();
5276   }
5277   return false;
5278 }
5279 
5280 /// CheckObjCString - Checks that the format string argument to the os_log()
5281 /// and os_trace() functions is correct, and converts it to const char *.
5282 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5283   Arg = Arg->IgnoreParenCasts();
5284   auto *Literal = dyn_cast<StringLiteral>(Arg);
5285   if (!Literal) {
5286     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5287       Literal = ObjcLiteral->getString();
5288     }
5289   }
5290 
5291   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
5292     return ExprError(
5293         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5294         << Arg->getSourceRange());
5295   }
5296 
5297   ExprResult Result(Literal);
5298   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5299   InitializedEntity Entity =
5300       InitializedEntity::InitializeParameter(Context, ResultTy, false);
5301   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5302   return Result;
5303 }
5304 
5305 /// Check that the user is calling the appropriate va_start builtin for the
5306 /// target and calling convention.
5307 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5308   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5309   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5310   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
5311                     TT.getArch() == llvm::Triple::aarch64_32);
5312   bool IsWindows = TT.isOSWindows();
5313   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5314   if (IsX64 || IsAArch64) {
5315     CallingConv CC = CC_C;
5316     if (const FunctionDecl *FD = S.getCurFunctionDecl())
5317       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
5318     if (IsMSVAStart) {
5319       // Don't allow this in System V ABI functions.
5320       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
5321         return S.Diag(Fn->getBeginLoc(),
5322                       diag::err_ms_va_start_used_in_sysv_function);
5323     } else {
5324       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5325       // On x64 Windows, don't allow this in System V ABI functions.
5326       // (Yes, that means there's no corresponding way to support variadic
5327       // System V ABI functions on Windows.)
5328       if ((IsWindows && CC == CC_X86_64SysV) ||
5329           (!IsWindows && CC == CC_Win64))
5330         return S.Diag(Fn->getBeginLoc(),
5331                       diag::err_va_start_used_in_wrong_abi_function)
5332                << !IsWindows;
5333     }
5334     return false;
5335   }
5336 
5337   if (IsMSVAStart)
5338     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5339   return false;
5340 }
5341 
5342 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
5343                                              ParmVarDecl **LastParam = nullptr) {
5344   // Determine whether the current function, block, or obj-c method is variadic
5345   // and get its parameter list.
5346   bool IsVariadic = false;
5347   ArrayRef<ParmVarDecl *> Params;
5348   DeclContext *Caller = S.CurContext;
5349   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5350     IsVariadic = Block->isVariadic();
5351     Params = Block->parameters();
5352   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5353     IsVariadic = FD->isVariadic();
5354     Params = FD->parameters();
5355   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5356     IsVariadic = MD->isVariadic();
5357     // FIXME: This isn't correct for methods (results in bogus warning).
5358     Params = MD->parameters();
5359   } else if (isa<CapturedDecl>(Caller)) {
5360     // We don't support va_start in a CapturedDecl.
5361     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5362     return true;
5363   } else {
5364     // This must be some other declcontext that parses exprs.
5365     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5366     return true;
5367   }
5368 
5369   if (!IsVariadic) {
5370     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
5371     return true;
5372   }
5373 
5374   if (LastParam)
5375     *LastParam = Params.empty() ? nullptr : Params.back();
5376 
5377   return false;
5378 }
5379 
5380 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
5381 /// for validity.  Emit an error and return true on failure; return false
5382 /// on success.
5383 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5384   Expr *Fn = TheCall->getCallee();
5385 
5386   if (checkVAStartABI(*this, BuiltinID, Fn))
5387     return true;
5388 
5389   if (TheCall->getNumArgs() > 2) {
5390     Diag(TheCall->getArg(2)->getBeginLoc(),
5391          diag::err_typecheck_call_too_many_args)
5392         << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5393         << Fn->getSourceRange()
5394         << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5395                        (*(TheCall->arg_end() - 1))->getEndLoc());
5396     return true;
5397   }
5398 
5399   if (TheCall->getNumArgs() < 2) {
5400     return Diag(TheCall->getEndLoc(),
5401                 diag::err_typecheck_call_too_few_args_at_least)
5402            << 0 /*function call*/ << 2 << TheCall->getNumArgs();
5403   }
5404 
5405   // Type-check the first argument normally.
5406   if (checkBuiltinArgument(*this, TheCall, 0))
5407     return true;
5408 
5409   // Check that the current function is variadic, and get its last parameter.
5410   ParmVarDecl *LastParam;
5411   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5412     return true;
5413 
5414   // Verify that the second argument to the builtin is the last argument of the
5415   // current function or method.
5416   bool SecondArgIsLastNamedArgument = false;
5417   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5418 
5419   // These are valid if SecondArgIsLastNamedArgument is false after the next
5420   // block.
5421   QualType Type;
5422   SourceLocation ParamLoc;
5423   bool IsCRegister = false;
5424 
5425   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5426     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5427       SecondArgIsLastNamedArgument = PV == LastParam;
5428 
5429       Type = PV->getType();
5430       ParamLoc = PV->getLocation();
5431       IsCRegister =
5432           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5433     }
5434   }
5435 
5436   if (!SecondArgIsLastNamedArgument)
5437     Diag(TheCall->getArg(1)->getBeginLoc(),
5438          diag::warn_second_arg_of_va_start_not_last_named_param);
5439   else if (IsCRegister || Type->isReferenceType() ||
5440            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5441              // Promotable integers are UB, but enumerations need a bit of
5442              // extra checking to see what their promotable type actually is.
5443              if (!Type->isPromotableIntegerType())
5444                return false;
5445              if (!Type->isEnumeralType())
5446                return true;
5447              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
5448              return !(ED &&
5449                       Context.typesAreCompatible(ED->getPromotionType(), Type));
5450            }()) {
5451     unsigned Reason = 0;
5452     if (Type->isReferenceType())  Reason = 1;
5453     else if (IsCRegister)         Reason = 2;
5454     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
5455     Diag(ParamLoc, diag::note_parameter_type) << Type;
5456   }
5457 
5458   TheCall->setType(Context.VoidTy);
5459   return false;
5460 }
5461 
5462 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
5463   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5464   //                 const char *named_addr);
5465 
5466   Expr *Func = Call->getCallee();
5467 
5468   if (Call->getNumArgs() < 3)
5469     return Diag(Call->getEndLoc(),
5470                 diag::err_typecheck_call_too_few_args_at_least)
5471            << 0 /*function call*/ << 3 << Call->getNumArgs();
5472 
5473   // Type-check the first argument normally.
5474   if (checkBuiltinArgument(*this, Call, 0))
5475     return true;
5476 
5477   // Check that the current function is variadic.
5478   if (checkVAStartIsInVariadicFunction(*this, Func))
5479     return true;
5480 
5481   // __va_start on Windows does not validate the parameter qualifiers
5482 
5483   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5484   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5485 
5486   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5487   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5488 
5489   const QualType &ConstCharPtrTy =
5490       Context.getPointerType(Context.CharTy.withConst());
5491   if (!Arg1Ty->isPointerType() ||
5492       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
5493     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5494         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5495         << 0                                      /* qualifier difference */
5496         << 3                                      /* parameter mismatch */
5497         << 2 << Arg1->getType() << ConstCharPtrTy;
5498 
5499   const QualType SizeTy = Context.getSizeType();
5500   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
5501     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5502         << Arg2->getType() << SizeTy << 1 /* different class */
5503         << 0                              /* qualifier difference */
5504         << 3                              /* parameter mismatch */
5505         << 3 << Arg2->getType() << SizeTy;
5506 
5507   return false;
5508 }
5509 
5510 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
5511 /// friends.  This is declared to take (...), so we have to check everything.
5512 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
5513   if (TheCall->getNumArgs() < 2)
5514     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5515            << 0 << 2 << TheCall->getNumArgs() /*function call*/;
5516   if (TheCall->getNumArgs() > 2)
5517     return Diag(TheCall->getArg(2)->getBeginLoc(),
5518                 diag::err_typecheck_call_too_many_args)
5519            << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5520            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5521                           (*(TheCall->arg_end() - 1))->getEndLoc());
5522 
5523   ExprResult OrigArg0 = TheCall->getArg(0);
5524   ExprResult OrigArg1 = TheCall->getArg(1);
5525 
5526   // Do standard promotions between the two arguments, returning their common
5527   // type.
5528   QualType Res = UsualArithmeticConversions(
5529       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
5530   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5531     return true;
5532 
5533   // Make sure any conversions are pushed back into the call; this is
5534   // type safe since unordered compare builtins are declared as "_Bool
5535   // foo(...)".
5536   TheCall->setArg(0, OrigArg0.get());
5537   TheCall->setArg(1, OrigArg1.get());
5538 
5539   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5540     return false;
5541 
5542   // If the common type isn't a real floating type, then the arguments were
5543   // invalid for this operation.
5544   if (Res.isNull() || !Res->isRealFloatingType())
5545     return Diag(OrigArg0.get()->getBeginLoc(),
5546                 diag::err_typecheck_call_invalid_ordered_compare)
5547            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5548            << SourceRange(OrigArg0.get()->getBeginLoc(),
5549                           OrigArg1.get()->getEndLoc());
5550 
5551   return false;
5552 }
5553 
5554 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
5555 /// __builtin_isnan and friends.  This is declared to take (...), so we have
5556 /// to check everything. We expect the last argument to be a floating point
5557 /// value.
5558 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
5559   if (TheCall->getNumArgs() < NumArgs)
5560     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5561            << 0 << NumArgs << TheCall->getNumArgs() /*function call*/;
5562   if (TheCall->getNumArgs() > NumArgs)
5563     return Diag(TheCall->getArg(NumArgs)->getBeginLoc(),
5564                 diag::err_typecheck_call_too_many_args)
5565            << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
5566            << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(),
5567                           (*(TheCall->arg_end() - 1))->getEndLoc());
5568 
5569   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
5570   // on all preceding parameters just being int.  Try all of those.
5571   for (unsigned i = 0; i < NumArgs - 1; ++i) {
5572     Expr *Arg = TheCall->getArg(i);
5573 
5574     if (Arg->isTypeDependent())
5575       return false;
5576 
5577     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
5578 
5579     if (Res.isInvalid())
5580       return true;
5581     TheCall->setArg(i, Res.get());
5582   }
5583 
5584   Expr *OrigArg = TheCall->getArg(NumArgs-1);
5585 
5586   if (OrigArg->isTypeDependent())
5587     return false;
5588 
5589   // Usual Unary Conversions will convert half to float, which we want for
5590   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
5591   // type how it is, but do normal L->Rvalue conversions.
5592   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
5593     OrigArg = UsualUnaryConversions(OrigArg).get();
5594   else
5595     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
5596   TheCall->setArg(NumArgs - 1, OrigArg);
5597 
5598   // This operation requires a non-_Complex floating-point number.
5599   if (!OrigArg->getType()->isRealFloatingType())
5600     return Diag(OrigArg->getBeginLoc(),
5601                 diag::err_typecheck_call_invalid_unary_fp)
5602            << OrigArg->getType() << OrigArg->getSourceRange();
5603 
5604   return false;
5605 }
5606 
5607 // Customized Sema Checking for VSX builtins that have the following signature:
5608 // vector [...] builtinName(vector [...], vector [...], const int);
5609 // Which takes the same type of vectors (any legal vector type) for the first
5610 // two arguments and takes compile time constant for the third argument.
5611 // Example builtins are :
5612 // vector double vec_xxpermdi(vector double, vector double, int);
5613 // vector short vec_xxsldwi(vector short, vector short, int);
5614 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
5615   unsigned ExpectedNumArgs = 3;
5616   if (TheCall->getNumArgs() < ExpectedNumArgs)
5617     return Diag(TheCall->getEndLoc(),
5618                 diag::err_typecheck_call_too_few_args_at_least)
5619            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5620            << TheCall->getSourceRange();
5621 
5622   if (TheCall->getNumArgs() > ExpectedNumArgs)
5623     return Diag(TheCall->getEndLoc(),
5624                 diag::err_typecheck_call_too_many_args_at_most)
5625            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5626            << TheCall->getSourceRange();
5627 
5628   // Check the third argument is a compile time constant
5629   llvm::APSInt Value;
5630   if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
5631     return Diag(TheCall->getBeginLoc(),
5632                 diag::err_vsx_builtin_nonconstant_argument)
5633            << 3 /* argument index */ << TheCall->getDirectCallee()
5634            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5635                           TheCall->getArg(2)->getEndLoc());
5636 
5637   QualType Arg1Ty = TheCall->getArg(0)->getType();
5638   QualType Arg2Ty = TheCall->getArg(1)->getType();
5639 
5640   // Check the type of argument 1 and argument 2 are vectors.
5641   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
5642   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
5643       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
5644     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
5645            << TheCall->getDirectCallee()
5646            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5647                           TheCall->getArg(1)->getEndLoc());
5648   }
5649 
5650   // Check the first two arguments are the same type.
5651   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
5652     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
5653            << TheCall->getDirectCallee()
5654            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5655                           TheCall->getArg(1)->getEndLoc());
5656   }
5657 
5658   // When default clang type checking is turned off and the customized type
5659   // checking is used, the returning type of the function must be explicitly
5660   // set. Otherwise it is _Bool by default.
5661   TheCall->setType(Arg1Ty);
5662 
5663   return false;
5664 }
5665 
5666 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
5667 // This is declared to take (...), so we have to check everything.
5668 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
5669   if (TheCall->getNumArgs() < 2)
5670     return ExprError(Diag(TheCall->getEndLoc(),
5671                           diag::err_typecheck_call_too_few_args_at_least)
5672                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5673                      << TheCall->getSourceRange());
5674 
5675   // Determine which of the following types of shufflevector we're checking:
5676   // 1) unary, vector mask: (lhs, mask)
5677   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
5678   QualType resType = TheCall->getArg(0)->getType();
5679   unsigned numElements = 0;
5680 
5681   if (!TheCall->getArg(0)->isTypeDependent() &&
5682       !TheCall->getArg(1)->isTypeDependent()) {
5683     QualType LHSType = TheCall->getArg(0)->getType();
5684     QualType RHSType = TheCall->getArg(1)->getType();
5685 
5686     if (!LHSType->isVectorType() || !RHSType->isVectorType())
5687       return ExprError(
5688           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
5689           << TheCall->getDirectCallee()
5690           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5691                          TheCall->getArg(1)->getEndLoc()));
5692 
5693     numElements = LHSType->castAs<VectorType>()->getNumElements();
5694     unsigned numResElements = TheCall->getNumArgs() - 2;
5695 
5696     // Check to see if we have a call with 2 vector arguments, the unary shuffle
5697     // with mask.  If so, verify that RHS is an integer vector type with the
5698     // same number of elts as lhs.
5699     if (TheCall->getNumArgs() == 2) {
5700       if (!RHSType->hasIntegerRepresentation() ||
5701           RHSType->castAs<VectorType>()->getNumElements() != numElements)
5702         return ExprError(Diag(TheCall->getBeginLoc(),
5703                               diag::err_vec_builtin_incompatible_vector)
5704                          << TheCall->getDirectCallee()
5705                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
5706                                         TheCall->getArg(1)->getEndLoc()));
5707     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
5708       return ExprError(Diag(TheCall->getBeginLoc(),
5709                             diag::err_vec_builtin_incompatible_vector)
5710                        << TheCall->getDirectCallee()
5711                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5712                                       TheCall->getArg(1)->getEndLoc()));
5713     } else if (numElements != numResElements) {
5714       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
5715       resType = Context.getVectorType(eltType, numResElements,
5716                                       VectorType::GenericVector);
5717     }
5718   }
5719 
5720   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
5721     if (TheCall->getArg(i)->isTypeDependent() ||
5722         TheCall->getArg(i)->isValueDependent())
5723       continue;
5724 
5725     llvm::APSInt Result(32);
5726     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
5727       return ExprError(Diag(TheCall->getBeginLoc(),
5728                             diag::err_shufflevector_nonconstant_argument)
5729                        << TheCall->getArg(i)->getSourceRange());
5730 
5731     // Allow -1 which will be translated to undef in the IR.
5732     if (Result.isSigned() && Result.isAllOnesValue())
5733       continue;
5734 
5735     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
5736       return ExprError(Diag(TheCall->getBeginLoc(),
5737                             diag::err_shufflevector_argument_too_large)
5738                        << TheCall->getArg(i)->getSourceRange());
5739   }
5740 
5741   SmallVector<Expr*, 32> exprs;
5742 
5743   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
5744     exprs.push_back(TheCall->getArg(i));
5745     TheCall->setArg(i, nullptr);
5746   }
5747 
5748   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
5749                                          TheCall->getCallee()->getBeginLoc(),
5750                                          TheCall->getRParenLoc());
5751 }
5752 
5753 /// SemaConvertVectorExpr - Handle __builtin_convertvector
5754 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
5755                                        SourceLocation BuiltinLoc,
5756                                        SourceLocation RParenLoc) {
5757   ExprValueKind VK = VK_RValue;
5758   ExprObjectKind OK = OK_Ordinary;
5759   QualType DstTy = TInfo->getType();
5760   QualType SrcTy = E->getType();
5761 
5762   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
5763     return ExprError(Diag(BuiltinLoc,
5764                           diag::err_convertvector_non_vector)
5765                      << E->getSourceRange());
5766   if (!DstTy->isVectorType() && !DstTy->isDependentType())
5767     return ExprError(Diag(BuiltinLoc,
5768                           diag::err_convertvector_non_vector_type));
5769 
5770   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
5771     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
5772     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
5773     if (SrcElts != DstElts)
5774       return ExprError(Diag(BuiltinLoc,
5775                             diag::err_convertvector_incompatible_vector)
5776                        << E->getSourceRange());
5777   }
5778 
5779   return new (Context)
5780       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5781 }
5782 
5783 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
5784 // This is declared to take (const void*, ...) and can take two
5785 // optional constant int args.
5786 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
5787   unsigned NumArgs = TheCall->getNumArgs();
5788 
5789   if (NumArgs > 3)
5790     return Diag(TheCall->getEndLoc(),
5791                 diag::err_typecheck_call_too_many_args_at_most)
5792            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
5793 
5794   // Argument 0 is checked for us and the remaining arguments must be
5795   // constant integers.
5796   for (unsigned i = 1; i != NumArgs; ++i)
5797     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
5798       return true;
5799 
5800   return false;
5801 }
5802 
5803 /// SemaBuiltinAssume - Handle __assume (MS Extension).
5804 // __assume does not evaluate its arguments, and should warn if its argument
5805 // has side effects.
5806 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
5807   Expr *Arg = TheCall->getArg(0);
5808   if (Arg->isInstantiationDependent()) return false;
5809 
5810   if (Arg->HasSideEffects(Context))
5811     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
5812         << Arg->getSourceRange()
5813         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
5814 
5815   return false;
5816 }
5817 
5818 /// Handle __builtin_alloca_with_align. This is declared
5819 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
5820 /// than 8.
5821 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
5822   // The alignment must be a constant integer.
5823   Expr *Arg = TheCall->getArg(1);
5824 
5825   // We can't check the value of a dependent argument.
5826   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5827     if (const auto *UE =
5828             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
5829       if (UE->getKind() == UETT_AlignOf ||
5830           UE->getKind() == UETT_PreferredAlignOf)
5831         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
5832             << Arg->getSourceRange();
5833 
5834     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
5835 
5836     if (!Result.isPowerOf2())
5837       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5838              << Arg->getSourceRange();
5839 
5840     if (Result < Context.getCharWidth())
5841       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
5842              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
5843 
5844     if (Result > std::numeric_limits<int32_t>::max())
5845       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
5846              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
5847   }
5848 
5849   return false;
5850 }
5851 
5852 /// Handle __builtin_assume_aligned. This is declared
5853 /// as (const void*, size_t, ...) and can take one optional constant int arg.
5854 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
5855   unsigned NumArgs = TheCall->getNumArgs();
5856 
5857   if (NumArgs > 3)
5858     return Diag(TheCall->getEndLoc(),
5859                 diag::err_typecheck_call_too_many_args_at_most)
5860            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
5861 
5862   // The alignment must be a constant integer.
5863   Expr *Arg = TheCall->getArg(1);
5864 
5865   // We can't check the value of a dependent argument.
5866   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5867     llvm::APSInt Result;
5868     if (SemaBuiltinConstantArg(TheCall, 1, Result))
5869       return true;
5870 
5871     if (!Result.isPowerOf2())
5872       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5873              << Arg->getSourceRange();
5874 
5875     if (Result > Sema::MaximumAlignment)
5876       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
5877           << Arg->getSourceRange() << Sema::MaximumAlignment;
5878   }
5879 
5880   if (NumArgs > 2) {
5881     ExprResult Arg(TheCall->getArg(2));
5882     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5883       Context.getSizeType(), false);
5884     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5885     if (Arg.isInvalid()) return true;
5886     TheCall->setArg(2, Arg.get());
5887   }
5888 
5889   return false;
5890 }
5891 
5892 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
5893   unsigned BuiltinID =
5894       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
5895   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
5896 
5897   unsigned NumArgs = TheCall->getNumArgs();
5898   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
5899   if (NumArgs < NumRequiredArgs) {
5900     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5901            << 0 /* function call */ << NumRequiredArgs << NumArgs
5902            << TheCall->getSourceRange();
5903   }
5904   if (NumArgs >= NumRequiredArgs + 0x100) {
5905     return Diag(TheCall->getEndLoc(),
5906                 diag::err_typecheck_call_too_many_args_at_most)
5907            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
5908            << TheCall->getSourceRange();
5909   }
5910   unsigned i = 0;
5911 
5912   // For formatting call, check buffer arg.
5913   if (!IsSizeCall) {
5914     ExprResult Arg(TheCall->getArg(i));
5915     InitializedEntity Entity = InitializedEntity::InitializeParameter(
5916         Context, Context.VoidPtrTy, false);
5917     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5918     if (Arg.isInvalid())
5919       return true;
5920     TheCall->setArg(i, Arg.get());
5921     i++;
5922   }
5923 
5924   // Check string literal arg.
5925   unsigned FormatIdx = i;
5926   {
5927     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
5928     if (Arg.isInvalid())
5929       return true;
5930     TheCall->setArg(i, Arg.get());
5931     i++;
5932   }
5933 
5934   // Make sure variadic args are scalar.
5935   unsigned FirstDataArg = i;
5936   while (i < NumArgs) {
5937     ExprResult Arg = DefaultVariadicArgumentPromotion(
5938         TheCall->getArg(i), VariadicFunction, nullptr);
5939     if (Arg.isInvalid())
5940       return true;
5941     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
5942     if (ArgSize.getQuantity() >= 0x100) {
5943       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
5944              << i << (int)ArgSize.getQuantity() << 0xff
5945              << TheCall->getSourceRange();
5946     }
5947     TheCall->setArg(i, Arg.get());
5948     i++;
5949   }
5950 
5951   // Check formatting specifiers. NOTE: We're only doing this for the non-size
5952   // call to avoid duplicate diagnostics.
5953   if (!IsSizeCall) {
5954     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
5955     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
5956     bool Success = CheckFormatArguments(
5957         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
5958         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
5959         CheckedVarArgs);
5960     if (!Success)
5961       return true;
5962   }
5963 
5964   if (IsSizeCall) {
5965     TheCall->setType(Context.getSizeType());
5966   } else {
5967     TheCall->setType(Context.VoidPtrTy);
5968   }
5969   return false;
5970 }
5971 
5972 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
5973 /// TheCall is a constant expression.
5974 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
5975                                   llvm::APSInt &Result) {
5976   Expr *Arg = TheCall->getArg(ArgNum);
5977   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5978   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5979 
5980   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
5981 
5982   if (!Arg->isIntegerConstantExpr(Result, Context))
5983     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
5984            << FDecl->getDeclName() << Arg->getSourceRange();
5985 
5986   return false;
5987 }
5988 
5989 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
5990 /// TheCall is a constant expression in the range [Low, High].
5991 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
5992                                        int Low, int High, bool RangeIsError) {
5993   if (isConstantEvaluated())
5994     return false;
5995   llvm::APSInt Result;
5996 
5997   // We can't check the value of a dependent argument.
5998   Expr *Arg = TheCall->getArg(ArgNum);
5999   if (Arg->isTypeDependent() || Arg->isValueDependent())
6000     return false;
6001 
6002   // Check constant-ness first.
6003   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6004     return true;
6005 
6006   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6007     if (RangeIsError)
6008       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6009              << Result.toString(10) << Low << High << Arg->getSourceRange();
6010     else
6011       // Defer the warning until we know if the code will be emitted so that
6012       // dead code can ignore this.
6013       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6014                           PDiag(diag::warn_argument_invalid_range)
6015                               << Result.toString(10) << Low << High
6016                               << Arg->getSourceRange());
6017   }
6018 
6019   return false;
6020 }
6021 
6022 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
6023 /// TheCall is a constant expression is a multiple of Num..
6024 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
6025                                           unsigned Num) {
6026   llvm::APSInt Result;
6027 
6028   // We can't check the value of a dependent argument.
6029   Expr *Arg = TheCall->getArg(ArgNum);
6030   if (Arg->isTypeDependent() || Arg->isValueDependent())
6031     return false;
6032 
6033   // Check constant-ness first.
6034   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6035     return true;
6036 
6037   if (Result.getSExtValue() % Num != 0)
6038     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6039            << Num << Arg->getSourceRange();
6040 
6041   return false;
6042 }
6043 
6044 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
6045 /// constant expression representing a power of 2.
6046 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
6047   llvm::APSInt Result;
6048 
6049   // We can't check the value of a dependent argument.
6050   Expr *Arg = TheCall->getArg(ArgNum);
6051   if (Arg->isTypeDependent() || Arg->isValueDependent())
6052     return false;
6053 
6054   // Check constant-ness first.
6055   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6056     return true;
6057 
6058   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
6059   // and only if x is a power of 2.
6060   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
6061     return false;
6062 
6063   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
6064          << Arg->getSourceRange();
6065 }
6066 
6067 static bool IsShiftedByte(llvm::APSInt Value) {
6068   if (Value.isNegative())
6069     return false;
6070 
6071   // Check if it's a shifted byte, by shifting it down
6072   while (true) {
6073     // If the value fits in the bottom byte, the check passes.
6074     if (Value < 0x100)
6075       return true;
6076 
6077     // Otherwise, if the value has _any_ bits in the bottom byte, the check
6078     // fails.
6079     if ((Value & 0xFF) != 0)
6080       return false;
6081 
6082     // If the bottom 8 bits are all 0, but something above that is nonzero,
6083     // then shifting the value right by 8 bits won't affect whether it's a
6084     // shifted byte or not. So do that, and go round again.
6085     Value >>= 8;
6086   }
6087 }
6088 
6089 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
6090 /// a constant expression representing an arbitrary byte value shifted left by
6091 /// a multiple of 8 bits.
6092 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
6093                                              unsigned ArgBits) {
6094   llvm::APSInt Result;
6095 
6096   // We can't check the value of a dependent argument.
6097   Expr *Arg = TheCall->getArg(ArgNum);
6098   if (Arg->isTypeDependent() || Arg->isValueDependent())
6099     return false;
6100 
6101   // Check constant-ness first.
6102   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6103     return true;
6104 
6105   // Truncate to the given size.
6106   Result = Result.getLoBits(ArgBits);
6107   Result.setIsUnsigned(true);
6108 
6109   if (IsShiftedByte(Result))
6110     return false;
6111 
6112   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
6113          << Arg->getSourceRange();
6114 }
6115 
6116 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
6117 /// TheCall is a constant expression representing either a shifted byte value,
6118 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
6119 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
6120 /// Arm MVE intrinsics.
6121 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
6122                                                    int ArgNum,
6123                                                    unsigned ArgBits) {
6124   llvm::APSInt Result;
6125 
6126   // We can't check the value of a dependent argument.
6127   Expr *Arg = TheCall->getArg(ArgNum);
6128   if (Arg->isTypeDependent() || Arg->isValueDependent())
6129     return false;
6130 
6131   // Check constant-ness first.
6132   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6133     return true;
6134 
6135   // Truncate to the given size.
6136   Result = Result.getLoBits(ArgBits);
6137   Result.setIsUnsigned(true);
6138 
6139   // Check to see if it's in either of the required forms.
6140   if (IsShiftedByte(Result) ||
6141       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
6142     return false;
6143 
6144   return Diag(TheCall->getBeginLoc(),
6145               diag::err_argument_not_shifted_byte_or_xxff)
6146          << Arg->getSourceRange();
6147 }
6148 
6149 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
6150 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
6151   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
6152     if (checkArgCount(*this, TheCall, 2))
6153       return true;
6154     Expr *Arg0 = TheCall->getArg(0);
6155     Expr *Arg1 = TheCall->getArg(1);
6156 
6157     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6158     if (FirstArg.isInvalid())
6159       return true;
6160     QualType FirstArgType = FirstArg.get()->getType();
6161     if (!FirstArgType->isAnyPointerType())
6162       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6163                << "first" << FirstArgType << Arg0->getSourceRange();
6164     TheCall->setArg(0, FirstArg.get());
6165 
6166     ExprResult SecArg = DefaultLvalueConversion(Arg1);
6167     if (SecArg.isInvalid())
6168       return true;
6169     QualType SecArgType = SecArg.get()->getType();
6170     if (!SecArgType->isIntegerType())
6171       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6172                << "second" << SecArgType << Arg1->getSourceRange();
6173 
6174     // Derive the return type from the pointer argument.
6175     TheCall->setType(FirstArgType);
6176     return false;
6177   }
6178 
6179   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
6180     if (checkArgCount(*this, TheCall, 2))
6181       return true;
6182 
6183     Expr *Arg0 = TheCall->getArg(0);
6184     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6185     if (FirstArg.isInvalid())
6186       return true;
6187     QualType FirstArgType = FirstArg.get()->getType();
6188     if (!FirstArgType->isAnyPointerType())
6189       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6190                << "first" << FirstArgType << Arg0->getSourceRange();
6191     TheCall->setArg(0, FirstArg.get());
6192 
6193     // Derive the return type from the pointer argument.
6194     TheCall->setType(FirstArgType);
6195 
6196     // Second arg must be an constant in range [0,15]
6197     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6198   }
6199 
6200   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
6201     if (checkArgCount(*this, TheCall, 2))
6202       return true;
6203     Expr *Arg0 = TheCall->getArg(0);
6204     Expr *Arg1 = TheCall->getArg(1);
6205 
6206     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6207     if (FirstArg.isInvalid())
6208       return true;
6209     QualType FirstArgType = FirstArg.get()->getType();
6210     if (!FirstArgType->isAnyPointerType())
6211       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6212                << "first" << FirstArgType << Arg0->getSourceRange();
6213 
6214     QualType SecArgType = Arg1->getType();
6215     if (!SecArgType->isIntegerType())
6216       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6217                << "second" << SecArgType << Arg1->getSourceRange();
6218     TheCall->setType(Context.IntTy);
6219     return false;
6220   }
6221 
6222   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
6223       BuiltinID == AArch64::BI__builtin_arm_stg) {
6224     if (checkArgCount(*this, TheCall, 1))
6225       return true;
6226     Expr *Arg0 = TheCall->getArg(0);
6227     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6228     if (FirstArg.isInvalid())
6229       return true;
6230 
6231     QualType FirstArgType = FirstArg.get()->getType();
6232     if (!FirstArgType->isAnyPointerType())
6233       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6234                << "first" << FirstArgType << Arg0->getSourceRange();
6235     TheCall->setArg(0, FirstArg.get());
6236 
6237     // Derive the return type from the pointer argument.
6238     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
6239       TheCall->setType(FirstArgType);
6240     return false;
6241   }
6242 
6243   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
6244     Expr *ArgA = TheCall->getArg(0);
6245     Expr *ArgB = TheCall->getArg(1);
6246 
6247     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
6248     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
6249 
6250     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
6251       return true;
6252 
6253     QualType ArgTypeA = ArgExprA.get()->getType();
6254     QualType ArgTypeB = ArgExprB.get()->getType();
6255 
6256     auto isNull = [&] (Expr *E) -> bool {
6257       return E->isNullPointerConstant(
6258                         Context, Expr::NPC_ValueDependentIsNotNull); };
6259 
6260     // argument should be either a pointer or null
6261     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
6262       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6263         << "first" << ArgTypeA << ArgA->getSourceRange();
6264 
6265     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
6266       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6267         << "second" << ArgTypeB << ArgB->getSourceRange();
6268 
6269     // Ensure Pointee types are compatible
6270     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
6271         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
6272       QualType pointeeA = ArgTypeA->getPointeeType();
6273       QualType pointeeB = ArgTypeB->getPointeeType();
6274       if (!Context.typesAreCompatible(
6275              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
6276              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
6277         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
6278           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
6279           << ArgB->getSourceRange();
6280       }
6281     }
6282 
6283     // at least one argument should be pointer type
6284     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
6285       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
6286         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
6287 
6288     if (isNull(ArgA)) // adopt type of the other pointer
6289       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
6290 
6291     if (isNull(ArgB))
6292       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
6293 
6294     TheCall->setArg(0, ArgExprA.get());
6295     TheCall->setArg(1, ArgExprB.get());
6296     TheCall->setType(Context.LongLongTy);
6297     return false;
6298   }
6299   assert(false && "Unhandled ARM MTE intrinsic");
6300   return true;
6301 }
6302 
6303 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
6304 /// TheCall is an ARM/AArch64 special register string literal.
6305 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
6306                                     int ArgNum, unsigned ExpectedFieldNum,
6307                                     bool AllowName) {
6308   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
6309                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
6310                       BuiltinID == ARM::BI__builtin_arm_rsr ||
6311                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
6312                       BuiltinID == ARM::BI__builtin_arm_wsr ||
6313                       BuiltinID == ARM::BI__builtin_arm_wsrp;
6314   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
6315                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
6316                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
6317                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
6318                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
6319                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
6320   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
6321 
6322   // We can't check the value of a dependent argument.
6323   Expr *Arg = TheCall->getArg(ArgNum);
6324   if (Arg->isTypeDependent() || Arg->isValueDependent())
6325     return false;
6326 
6327   // Check if the argument is a string literal.
6328   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
6329     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
6330            << Arg->getSourceRange();
6331 
6332   // Check the type of special register given.
6333   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
6334   SmallVector<StringRef, 6> Fields;
6335   Reg.split(Fields, ":");
6336 
6337   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
6338     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6339            << Arg->getSourceRange();
6340 
6341   // If the string is the name of a register then we cannot check that it is
6342   // valid here but if the string is of one the forms described in ACLE then we
6343   // can check that the supplied fields are integers and within the valid
6344   // ranges.
6345   if (Fields.size() > 1) {
6346     bool FiveFields = Fields.size() == 5;
6347 
6348     bool ValidString = true;
6349     if (IsARMBuiltin) {
6350       ValidString &= Fields[0].startswith_lower("cp") ||
6351                      Fields[0].startswith_lower("p");
6352       if (ValidString)
6353         Fields[0] =
6354           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
6355 
6356       ValidString &= Fields[2].startswith_lower("c");
6357       if (ValidString)
6358         Fields[2] = Fields[2].drop_front(1);
6359 
6360       if (FiveFields) {
6361         ValidString &= Fields[3].startswith_lower("c");
6362         if (ValidString)
6363           Fields[3] = Fields[3].drop_front(1);
6364       }
6365     }
6366 
6367     SmallVector<int, 5> Ranges;
6368     if (FiveFields)
6369       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
6370     else
6371       Ranges.append({15, 7, 15});
6372 
6373     for (unsigned i=0; i<Fields.size(); ++i) {
6374       int IntField;
6375       ValidString &= !Fields[i].getAsInteger(10, IntField);
6376       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
6377     }
6378 
6379     if (!ValidString)
6380       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6381              << Arg->getSourceRange();
6382   } else if (IsAArch64Builtin && Fields.size() == 1) {
6383     // If the register name is one of those that appear in the condition below
6384     // and the special register builtin being used is one of the write builtins,
6385     // then we require that the argument provided for writing to the register
6386     // is an integer constant expression. This is because it will be lowered to
6387     // an MSR (immediate) instruction, so we need to know the immediate at
6388     // compile time.
6389     if (TheCall->getNumArgs() != 2)
6390       return false;
6391 
6392     std::string RegLower = Reg.lower();
6393     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
6394         RegLower != "pan" && RegLower != "uao")
6395       return false;
6396 
6397     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6398   }
6399 
6400   return false;
6401 }
6402 
6403 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
6404 /// This checks that the target supports __builtin_longjmp and
6405 /// that val is a constant 1.
6406 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
6407   if (!Context.getTargetInfo().hasSjLjLowering())
6408     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
6409            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6410 
6411   Expr *Arg = TheCall->getArg(1);
6412   llvm::APSInt Result;
6413 
6414   // TODO: This is less than ideal. Overload this to take a value.
6415   if (SemaBuiltinConstantArg(TheCall, 1, Result))
6416     return true;
6417 
6418   if (Result != 1)
6419     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
6420            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6421 
6422   return false;
6423 }
6424 
6425 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
6426 /// This checks that the target supports __builtin_setjmp.
6427 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
6428   if (!Context.getTargetInfo().hasSjLjLowering())
6429     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
6430            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6431   return false;
6432 }
6433 
6434 namespace {
6435 
6436 class UncoveredArgHandler {
6437   enum { Unknown = -1, AllCovered = -2 };
6438 
6439   signed FirstUncoveredArg = Unknown;
6440   SmallVector<const Expr *, 4> DiagnosticExprs;
6441 
6442 public:
6443   UncoveredArgHandler() = default;
6444 
6445   bool hasUncoveredArg() const {
6446     return (FirstUncoveredArg >= 0);
6447   }
6448 
6449   unsigned getUncoveredArg() const {
6450     assert(hasUncoveredArg() && "no uncovered argument");
6451     return FirstUncoveredArg;
6452   }
6453 
6454   void setAllCovered() {
6455     // A string has been found with all arguments covered, so clear out
6456     // the diagnostics.
6457     DiagnosticExprs.clear();
6458     FirstUncoveredArg = AllCovered;
6459   }
6460 
6461   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6462     assert(NewFirstUncoveredArg >= 0 && "Outside range");
6463 
6464     // Don't update if a previous string covers all arguments.
6465     if (FirstUncoveredArg == AllCovered)
6466       return;
6467 
6468     // UncoveredArgHandler tracks the highest uncovered argument index
6469     // and with it all the strings that match this index.
6470     if (NewFirstUncoveredArg == FirstUncoveredArg)
6471       DiagnosticExprs.push_back(StrExpr);
6472     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6473       DiagnosticExprs.clear();
6474       DiagnosticExprs.push_back(StrExpr);
6475       FirstUncoveredArg = NewFirstUncoveredArg;
6476     }
6477   }
6478 
6479   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6480 };
6481 
6482 enum StringLiteralCheckType {
6483   SLCT_NotALiteral,
6484   SLCT_UncheckedLiteral,
6485   SLCT_CheckedLiteral
6486 };
6487 
6488 } // namespace
6489 
6490 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6491                                      BinaryOperatorKind BinOpKind,
6492                                      bool AddendIsRight) {
6493   unsigned BitWidth = Offset.getBitWidth();
6494   unsigned AddendBitWidth = Addend.getBitWidth();
6495   // There might be negative interim results.
6496   if (Addend.isUnsigned()) {
6497     Addend = Addend.zext(++AddendBitWidth);
6498     Addend.setIsSigned(true);
6499   }
6500   // Adjust the bit width of the APSInts.
6501   if (AddendBitWidth > BitWidth) {
6502     Offset = Offset.sext(AddendBitWidth);
6503     BitWidth = AddendBitWidth;
6504   } else if (BitWidth > AddendBitWidth) {
6505     Addend = Addend.sext(BitWidth);
6506   }
6507 
6508   bool Ov = false;
6509   llvm::APSInt ResOffset = Offset;
6510   if (BinOpKind == BO_Add)
6511     ResOffset = Offset.sadd_ov(Addend, Ov);
6512   else {
6513     assert(AddendIsRight && BinOpKind == BO_Sub &&
6514            "operator must be add or sub with addend on the right");
6515     ResOffset = Offset.ssub_ov(Addend, Ov);
6516   }
6517 
6518   // We add an offset to a pointer here so we should support an offset as big as
6519   // possible.
6520   if (Ov) {
6521     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6522            "index (intermediate) result too big");
6523     Offset = Offset.sext(2 * BitWidth);
6524     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6525     return;
6526   }
6527 
6528   Offset = ResOffset;
6529 }
6530 
6531 namespace {
6532 
6533 // This is a wrapper class around StringLiteral to support offsetted string
6534 // literals as format strings. It takes the offset into account when returning
6535 // the string and its length or the source locations to display notes correctly.
6536 class FormatStringLiteral {
6537   const StringLiteral *FExpr;
6538   int64_t Offset;
6539 
6540  public:
6541   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
6542       : FExpr(fexpr), Offset(Offset) {}
6543 
6544   StringRef getString() const {
6545     return FExpr->getString().drop_front(Offset);
6546   }
6547 
6548   unsigned getByteLength() const {
6549     return FExpr->getByteLength() - getCharByteWidth() * Offset;
6550   }
6551 
6552   unsigned getLength() const { return FExpr->getLength() - Offset; }
6553   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
6554 
6555   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
6556 
6557   QualType getType() const { return FExpr->getType(); }
6558 
6559   bool isAscii() const { return FExpr->isAscii(); }
6560   bool isWide() const { return FExpr->isWide(); }
6561   bool isUTF8() const { return FExpr->isUTF8(); }
6562   bool isUTF16() const { return FExpr->isUTF16(); }
6563   bool isUTF32() const { return FExpr->isUTF32(); }
6564   bool isPascal() const { return FExpr->isPascal(); }
6565 
6566   SourceLocation getLocationOfByte(
6567       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
6568       const TargetInfo &Target, unsigned *StartToken = nullptr,
6569       unsigned *StartTokenByteOffset = nullptr) const {
6570     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
6571                                     StartToken, StartTokenByteOffset);
6572   }
6573 
6574   SourceLocation getBeginLoc() const LLVM_READONLY {
6575     return FExpr->getBeginLoc().getLocWithOffset(Offset);
6576   }
6577 
6578   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
6579 };
6580 
6581 }  // namespace
6582 
6583 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
6584                               const Expr *OrigFormatExpr,
6585                               ArrayRef<const Expr *> Args,
6586                               bool HasVAListArg, unsigned format_idx,
6587                               unsigned firstDataArg,
6588                               Sema::FormatStringType Type,
6589                               bool inFunctionCall,
6590                               Sema::VariadicCallType CallType,
6591                               llvm::SmallBitVector &CheckedVarArgs,
6592                               UncoveredArgHandler &UncoveredArg,
6593                               bool IgnoreStringsWithoutSpecifiers);
6594 
6595 // Determine if an expression is a string literal or constant string.
6596 // If this function returns false on the arguments to a function expecting a
6597 // format string, we will usually need to emit a warning.
6598 // True string literals are then checked by CheckFormatString.
6599 static StringLiteralCheckType
6600 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
6601                       bool HasVAListArg, unsigned format_idx,
6602                       unsigned firstDataArg, Sema::FormatStringType Type,
6603                       Sema::VariadicCallType CallType, bool InFunctionCall,
6604                       llvm::SmallBitVector &CheckedVarArgs,
6605                       UncoveredArgHandler &UncoveredArg,
6606                       llvm::APSInt Offset,
6607                       bool IgnoreStringsWithoutSpecifiers = false) {
6608   if (S.isConstantEvaluated())
6609     return SLCT_NotALiteral;
6610  tryAgain:
6611   assert(Offset.isSigned() && "invalid offset");
6612 
6613   if (E->isTypeDependent() || E->isValueDependent())
6614     return SLCT_NotALiteral;
6615 
6616   E = E->IgnoreParenCasts();
6617 
6618   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
6619     // Technically -Wformat-nonliteral does not warn about this case.
6620     // The behavior of printf and friends in this case is implementation
6621     // dependent.  Ideally if the format string cannot be null then
6622     // it should have a 'nonnull' attribute in the function prototype.
6623     return SLCT_UncheckedLiteral;
6624 
6625   switch (E->getStmtClass()) {
6626   case Stmt::BinaryConditionalOperatorClass:
6627   case Stmt::ConditionalOperatorClass: {
6628     // The expression is a literal if both sub-expressions were, and it was
6629     // completely checked only if both sub-expressions were checked.
6630     const AbstractConditionalOperator *C =
6631         cast<AbstractConditionalOperator>(E);
6632 
6633     // Determine whether it is necessary to check both sub-expressions, for
6634     // example, because the condition expression is a constant that can be
6635     // evaluated at compile time.
6636     bool CheckLeft = true, CheckRight = true;
6637 
6638     bool Cond;
6639     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
6640                                                  S.isConstantEvaluated())) {
6641       if (Cond)
6642         CheckRight = false;
6643       else
6644         CheckLeft = false;
6645     }
6646 
6647     // We need to maintain the offsets for the right and the left hand side
6648     // separately to check if every possible indexed expression is a valid
6649     // string literal. They might have different offsets for different string
6650     // literals in the end.
6651     StringLiteralCheckType Left;
6652     if (!CheckLeft)
6653       Left = SLCT_UncheckedLiteral;
6654     else {
6655       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
6656                                    HasVAListArg, format_idx, firstDataArg,
6657                                    Type, CallType, InFunctionCall,
6658                                    CheckedVarArgs, UncoveredArg, Offset,
6659                                    IgnoreStringsWithoutSpecifiers);
6660       if (Left == SLCT_NotALiteral || !CheckRight) {
6661         return Left;
6662       }
6663     }
6664 
6665     StringLiteralCheckType Right = checkFormatStringExpr(
6666         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
6667         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6668         IgnoreStringsWithoutSpecifiers);
6669 
6670     return (CheckLeft && Left < Right) ? Left : Right;
6671   }
6672 
6673   case Stmt::ImplicitCastExprClass:
6674     E = cast<ImplicitCastExpr>(E)->getSubExpr();
6675     goto tryAgain;
6676 
6677   case Stmt::OpaqueValueExprClass:
6678     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
6679       E = src;
6680       goto tryAgain;
6681     }
6682     return SLCT_NotALiteral;
6683 
6684   case Stmt::PredefinedExprClass:
6685     // While __func__, etc., are technically not string literals, they
6686     // cannot contain format specifiers and thus are not a security
6687     // liability.
6688     return SLCT_UncheckedLiteral;
6689 
6690   case Stmt::DeclRefExprClass: {
6691     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6692 
6693     // As an exception, do not flag errors for variables binding to
6694     // const string literals.
6695     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
6696       bool isConstant = false;
6697       QualType T = DR->getType();
6698 
6699       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
6700         isConstant = AT->getElementType().isConstant(S.Context);
6701       } else if (const PointerType *PT = T->getAs<PointerType>()) {
6702         isConstant = T.isConstant(S.Context) &&
6703                      PT->getPointeeType().isConstant(S.Context);
6704       } else if (T->isObjCObjectPointerType()) {
6705         // In ObjC, there is usually no "const ObjectPointer" type,
6706         // so don't check if the pointee type is constant.
6707         isConstant = T.isConstant(S.Context);
6708       }
6709 
6710       if (isConstant) {
6711         if (const Expr *Init = VD->getAnyInitializer()) {
6712           // Look through initializers like const char c[] = { "foo" }
6713           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
6714             if (InitList->isStringLiteralInit())
6715               Init = InitList->getInit(0)->IgnoreParenImpCasts();
6716           }
6717           return checkFormatStringExpr(S, Init, Args,
6718                                        HasVAListArg, format_idx,
6719                                        firstDataArg, Type, CallType,
6720                                        /*InFunctionCall*/ false, CheckedVarArgs,
6721                                        UncoveredArg, Offset);
6722         }
6723       }
6724 
6725       // For vprintf* functions (i.e., HasVAListArg==true), we add a
6726       // special check to see if the format string is a function parameter
6727       // of the function calling the printf function.  If the function
6728       // has an attribute indicating it is a printf-like function, then we
6729       // should suppress warnings concerning non-literals being used in a call
6730       // to a vprintf function.  For example:
6731       //
6732       // void
6733       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
6734       //      va_list ap;
6735       //      va_start(ap, fmt);
6736       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
6737       //      ...
6738       // }
6739       if (HasVAListArg) {
6740         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
6741           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
6742             int PVIndex = PV->getFunctionScopeIndex() + 1;
6743             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
6744               // adjust for implicit parameter
6745               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6746                 if (MD->isInstance())
6747                   ++PVIndex;
6748               // We also check if the formats are compatible.
6749               // We can't pass a 'scanf' string to a 'printf' function.
6750               if (PVIndex == PVFormat->getFormatIdx() &&
6751                   Type == S.GetFormatStringType(PVFormat))
6752                 return SLCT_UncheckedLiteral;
6753             }
6754           }
6755         }
6756       }
6757     }
6758 
6759     return SLCT_NotALiteral;
6760   }
6761 
6762   case Stmt::CallExprClass:
6763   case Stmt::CXXMemberCallExprClass: {
6764     const CallExpr *CE = cast<CallExpr>(E);
6765     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
6766       bool IsFirst = true;
6767       StringLiteralCheckType CommonResult;
6768       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
6769         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
6770         StringLiteralCheckType Result = checkFormatStringExpr(
6771             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6772             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6773             IgnoreStringsWithoutSpecifiers);
6774         if (IsFirst) {
6775           CommonResult = Result;
6776           IsFirst = false;
6777         }
6778       }
6779       if (!IsFirst)
6780         return CommonResult;
6781 
6782       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
6783         unsigned BuiltinID = FD->getBuiltinID();
6784         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
6785             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
6786           const Expr *Arg = CE->getArg(0);
6787           return checkFormatStringExpr(S, Arg, Args,
6788                                        HasVAListArg, format_idx,
6789                                        firstDataArg, Type, CallType,
6790                                        InFunctionCall, CheckedVarArgs,
6791                                        UncoveredArg, Offset,
6792                                        IgnoreStringsWithoutSpecifiers);
6793         }
6794       }
6795     }
6796 
6797     return SLCT_NotALiteral;
6798   }
6799   case Stmt::ObjCMessageExprClass: {
6800     const auto *ME = cast<ObjCMessageExpr>(E);
6801     if (const auto *MD = ME->getMethodDecl()) {
6802       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
6803         // As a special case heuristic, if we're using the method -[NSBundle
6804         // localizedStringForKey:value:table:], ignore any key strings that lack
6805         // format specifiers. The idea is that if the key doesn't have any
6806         // format specifiers then its probably just a key to map to the
6807         // localized strings. If it does have format specifiers though, then its
6808         // likely that the text of the key is the format string in the
6809         // programmer's language, and should be checked.
6810         const ObjCInterfaceDecl *IFace;
6811         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
6812             IFace->getIdentifier()->isStr("NSBundle") &&
6813             MD->getSelector().isKeywordSelector(
6814                 {"localizedStringForKey", "value", "table"})) {
6815           IgnoreStringsWithoutSpecifiers = true;
6816         }
6817 
6818         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
6819         return checkFormatStringExpr(
6820             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6821             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6822             IgnoreStringsWithoutSpecifiers);
6823       }
6824     }
6825 
6826     return SLCT_NotALiteral;
6827   }
6828   case Stmt::ObjCStringLiteralClass:
6829   case Stmt::StringLiteralClass: {
6830     const StringLiteral *StrE = nullptr;
6831 
6832     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
6833       StrE = ObjCFExpr->getString();
6834     else
6835       StrE = cast<StringLiteral>(E);
6836 
6837     if (StrE) {
6838       if (Offset.isNegative() || Offset > StrE->getLength()) {
6839         // TODO: It would be better to have an explicit warning for out of
6840         // bounds literals.
6841         return SLCT_NotALiteral;
6842       }
6843       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
6844       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
6845                         firstDataArg, Type, InFunctionCall, CallType,
6846                         CheckedVarArgs, UncoveredArg,
6847                         IgnoreStringsWithoutSpecifiers);
6848       return SLCT_CheckedLiteral;
6849     }
6850 
6851     return SLCT_NotALiteral;
6852   }
6853   case Stmt::BinaryOperatorClass: {
6854     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
6855 
6856     // A string literal + an int offset is still a string literal.
6857     if (BinOp->isAdditiveOp()) {
6858       Expr::EvalResult LResult, RResult;
6859 
6860       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
6861           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
6862       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
6863           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
6864 
6865       if (LIsInt != RIsInt) {
6866         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
6867 
6868         if (LIsInt) {
6869           if (BinOpKind == BO_Add) {
6870             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
6871             E = BinOp->getRHS();
6872             goto tryAgain;
6873           }
6874         } else {
6875           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
6876           E = BinOp->getLHS();
6877           goto tryAgain;
6878         }
6879       }
6880     }
6881 
6882     return SLCT_NotALiteral;
6883   }
6884   case Stmt::UnaryOperatorClass: {
6885     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
6886     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
6887     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
6888       Expr::EvalResult IndexResult;
6889       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
6890                                        Expr::SE_NoSideEffects,
6891                                        S.isConstantEvaluated())) {
6892         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
6893                    /*RHS is int*/ true);
6894         E = ASE->getBase();
6895         goto tryAgain;
6896       }
6897     }
6898 
6899     return SLCT_NotALiteral;
6900   }
6901 
6902   default:
6903     return SLCT_NotALiteral;
6904   }
6905 }
6906 
6907 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
6908   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
6909       .Case("scanf", FST_Scanf)
6910       .Cases("printf", "printf0", FST_Printf)
6911       .Cases("NSString", "CFString", FST_NSString)
6912       .Case("strftime", FST_Strftime)
6913       .Case("strfmon", FST_Strfmon)
6914       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
6915       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
6916       .Case("os_trace", FST_OSLog)
6917       .Case("os_log", FST_OSLog)
6918       .Default(FST_Unknown);
6919 }
6920 
6921 /// CheckFormatArguments - Check calls to printf and scanf (and similar
6922 /// functions) for correct use of format strings.
6923 /// Returns true if a format string has been fully checked.
6924 bool Sema::CheckFormatArguments(const FormatAttr *Format,
6925                                 ArrayRef<const Expr *> Args,
6926                                 bool IsCXXMember,
6927                                 VariadicCallType CallType,
6928                                 SourceLocation Loc, SourceRange Range,
6929                                 llvm::SmallBitVector &CheckedVarArgs) {
6930   FormatStringInfo FSI;
6931   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
6932     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
6933                                 FSI.FirstDataArg, GetFormatStringType(Format),
6934                                 CallType, Loc, Range, CheckedVarArgs);
6935   return false;
6936 }
6937 
6938 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
6939                                 bool HasVAListArg, unsigned format_idx,
6940                                 unsigned firstDataArg, FormatStringType Type,
6941                                 VariadicCallType CallType,
6942                                 SourceLocation Loc, SourceRange Range,
6943                                 llvm::SmallBitVector &CheckedVarArgs) {
6944   // CHECK: printf/scanf-like function is called with no format string.
6945   if (format_idx >= Args.size()) {
6946     Diag(Loc, diag::warn_missing_format_string) << Range;
6947     return false;
6948   }
6949 
6950   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
6951 
6952   // CHECK: format string is not a string literal.
6953   //
6954   // Dynamically generated format strings are difficult to
6955   // automatically vet at compile time.  Requiring that format strings
6956   // are string literals: (1) permits the checking of format strings by
6957   // the compiler and thereby (2) can practically remove the source of
6958   // many format string exploits.
6959 
6960   // Format string can be either ObjC string (e.g. @"%d") or
6961   // C string (e.g. "%d")
6962   // ObjC string uses the same format specifiers as C string, so we can use
6963   // the same format string checking logic for both ObjC and C strings.
6964   UncoveredArgHandler UncoveredArg;
6965   StringLiteralCheckType CT =
6966       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
6967                             format_idx, firstDataArg, Type, CallType,
6968                             /*IsFunctionCall*/ true, CheckedVarArgs,
6969                             UncoveredArg,
6970                             /*no string offset*/ llvm::APSInt(64, false) = 0);
6971 
6972   // Generate a diagnostic where an uncovered argument is detected.
6973   if (UncoveredArg.hasUncoveredArg()) {
6974     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
6975     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
6976     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
6977   }
6978 
6979   if (CT != SLCT_NotALiteral)
6980     // Literal format string found, check done!
6981     return CT == SLCT_CheckedLiteral;
6982 
6983   // Strftime is particular as it always uses a single 'time' argument,
6984   // so it is safe to pass a non-literal string.
6985   if (Type == FST_Strftime)
6986     return false;
6987 
6988   // Do not emit diag when the string param is a macro expansion and the
6989   // format is either NSString or CFString. This is a hack to prevent
6990   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
6991   // which are usually used in place of NS and CF string literals.
6992   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
6993   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
6994     return false;
6995 
6996   // If there are no arguments specified, warn with -Wformat-security, otherwise
6997   // warn only with -Wformat-nonliteral.
6998   if (Args.size() == firstDataArg) {
6999     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
7000       << OrigFormatExpr->getSourceRange();
7001     switch (Type) {
7002     default:
7003       break;
7004     case FST_Kprintf:
7005     case FST_FreeBSDKPrintf:
7006     case FST_Printf:
7007       Diag(FormatLoc, diag::note_format_security_fixit)
7008         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
7009       break;
7010     case FST_NSString:
7011       Diag(FormatLoc, diag::note_format_security_fixit)
7012         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
7013       break;
7014     }
7015   } else {
7016     Diag(FormatLoc, diag::warn_format_nonliteral)
7017       << OrigFormatExpr->getSourceRange();
7018   }
7019   return false;
7020 }
7021 
7022 namespace {
7023 
7024 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7025 protected:
7026   Sema &S;
7027   const FormatStringLiteral *FExpr;
7028   const Expr *OrigFormatExpr;
7029   const Sema::FormatStringType FSType;
7030   const unsigned FirstDataArg;
7031   const unsigned NumDataArgs;
7032   const char *Beg; // Start of format string.
7033   const bool HasVAListArg;
7034   ArrayRef<const Expr *> Args;
7035   unsigned FormatIdx;
7036   llvm::SmallBitVector CoveredArgs;
7037   bool usesPositionalArgs = false;
7038   bool atFirstArg = true;
7039   bool inFunctionCall;
7040   Sema::VariadicCallType CallType;
7041   llvm::SmallBitVector &CheckedVarArgs;
7042   UncoveredArgHandler &UncoveredArg;
7043 
7044 public:
7045   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
7046                      const Expr *origFormatExpr,
7047                      const Sema::FormatStringType type, unsigned firstDataArg,
7048                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
7049                      ArrayRef<const Expr *> Args, unsigned formatIdx,
7050                      bool inFunctionCall, Sema::VariadicCallType callType,
7051                      llvm::SmallBitVector &CheckedVarArgs,
7052                      UncoveredArgHandler &UncoveredArg)
7053       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7054         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7055         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
7056         inFunctionCall(inFunctionCall), CallType(callType),
7057         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
7058     CoveredArgs.resize(numDataArgs);
7059     CoveredArgs.reset();
7060   }
7061 
7062   void DoneProcessing();
7063 
7064   void HandleIncompleteSpecifier(const char *startSpecifier,
7065                                  unsigned specifierLen) override;
7066 
7067   void HandleInvalidLengthModifier(
7068                            const analyze_format_string::FormatSpecifier &FS,
7069                            const analyze_format_string::ConversionSpecifier &CS,
7070                            const char *startSpecifier, unsigned specifierLen,
7071                            unsigned DiagID);
7072 
7073   void HandleNonStandardLengthModifier(
7074                     const analyze_format_string::FormatSpecifier &FS,
7075                     const char *startSpecifier, unsigned specifierLen);
7076 
7077   void HandleNonStandardConversionSpecifier(
7078                     const analyze_format_string::ConversionSpecifier &CS,
7079                     const char *startSpecifier, unsigned specifierLen);
7080 
7081   void HandlePosition(const char *startPos, unsigned posLen) override;
7082 
7083   void HandleInvalidPosition(const char *startSpecifier,
7084                              unsigned specifierLen,
7085                              analyze_format_string::PositionContext p) override;
7086 
7087   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
7088 
7089   void HandleNullChar(const char *nullCharacter) override;
7090 
7091   template <typename Range>
7092   static void
7093   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
7094                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
7095                        bool IsStringLocation, Range StringRange,
7096                        ArrayRef<FixItHint> Fixit = None);
7097 
7098 protected:
7099   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
7100                                         const char *startSpec,
7101                                         unsigned specifierLen,
7102                                         const char *csStart, unsigned csLen);
7103 
7104   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7105                                          const char *startSpec,
7106                                          unsigned specifierLen);
7107 
7108   SourceRange getFormatStringRange();
7109   CharSourceRange getSpecifierRange(const char *startSpecifier,
7110                                     unsigned specifierLen);
7111   SourceLocation getLocationOfByte(const char *x);
7112 
7113   const Expr *getDataArg(unsigned i) const;
7114 
7115   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7116                     const analyze_format_string::ConversionSpecifier &CS,
7117                     const char *startSpecifier, unsigned specifierLen,
7118                     unsigned argIndex);
7119 
7120   template <typename Range>
7121   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7122                             bool IsStringLocation, Range StringRange,
7123                             ArrayRef<FixItHint> Fixit = None);
7124 };
7125 
7126 } // namespace
7127 
7128 SourceRange CheckFormatHandler::getFormatStringRange() {
7129   return OrigFormatExpr->getSourceRange();
7130 }
7131 
7132 CharSourceRange CheckFormatHandler::
7133 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
7134   SourceLocation Start = getLocationOfByte(startSpecifier);
7135   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
7136 
7137   // Advance the end SourceLocation by one due to half-open ranges.
7138   End = End.getLocWithOffset(1);
7139 
7140   return CharSourceRange::getCharRange(Start, End);
7141 }
7142 
7143 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
7144   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
7145                                   S.getLangOpts(), S.Context.getTargetInfo());
7146 }
7147 
7148 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7149                                                    unsigned specifierLen){
7150   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
7151                        getLocationOfByte(startSpecifier),
7152                        /*IsStringLocation*/true,
7153                        getSpecifierRange(startSpecifier, specifierLen));
7154 }
7155 
7156 void CheckFormatHandler::HandleInvalidLengthModifier(
7157     const analyze_format_string::FormatSpecifier &FS,
7158     const analyze_format_string::ConversionSpecifier &CS,
7159     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
7160   using namespace analyze_format_string;
7161 
7162   const LengthModifier &LM = FS.getLengthModifier();
7163   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7164 
7165   // See if we know how to fix this length modifier.
7166   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7167   if (FixedLM) {
7168     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7169                          getLocationOfByte(LM.getStart()),
7170                          /*IsStringLocation*/true,
7171                          getSpecifierRange(startSpecifier, specifierLen));
7172 
7173     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7174       << FixedLM->toString()
7175       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7176 
7177   } else {
7178     FixItHint Hint;
7179     if (DiagID == diag::warn_format_nonsensical_length)
7180       Hint = FixItHint::CreateRemoval(LMRange);
7181 
7182     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7183                          getLocationOfByte(LM.getStart()),
7184                          /*IsStringLocation*/true,
7185                          getSpecifierRange(startSpecifier, specifierLen),
7186                          Hint);
7187   }
7188 }
7189 
7190 void CheckFormatHandler::HandleNonStandardLengthModifier(
7191     const analyze_format_string::FormatSpecifier &FS,
7192     const char *startSpecifier, unsigned specifierLen) {
7193   using namespace analyze_format_string;
7194 
7195   const LengthModifier &LM = FS.getLengthModifier();
7196   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7197 
7198   // See if we know how to fix this length modifier.
7199   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7200   if (FixedLM) {
7201     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7202                            << LM.toString() << 0,
7203                          getLocationOfByte(LM.getStart()),
7204                          /*IsStringLocation*/true,
7205                          getSpecifierRange(startSpecifier, specifierLen));
7206 
7207     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7208       << FixedLM->toString()
7209       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7210 
7211   } else {
7212     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7213                            << LM.toString() << 0,
7214                          getLocationOfByte(LM.getStart()),
7215                          /*IsStringLocation*/true,
7216                          getSpecifierRange(startSpecifier, specifierLen));
7217   }
7218 }
7219 
7220 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
7221     const analyze_format_string::ConversionSpecifier &CS,
7222     const char *startSpecifier, unsigned specifierLen) {
7223   using namespace analyze_format_string;
7224 
7225   // See if we know how to fix this conversion specifier.
7226   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
7227   if (FixedCS) {
7228     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7229                           << CS.toString() << /*conversion specifier*/1,
7230                          getLocationOfByte(CS.getStart()),
7231                          /*IsStringLocation*/true,
7232                          getSpecifierRange(startSpecifier, specifierLen));
7233 
7234     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
7235     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
7236       << FixedCS->toString()
7237       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
7238   } else {
7239     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7240                           << CS.toString() << /*conversion specifier*/1,
7241                          getLocationOfByte(CS.getStart()),
7242                          /*IsStringLocation*/true,
7243                          getSpecifierRange(startSpecifier, specifierLen));
7244   }
7245 }
7246 
7247 void CheckFormatHandler::HandlePosition(const char *startPos,
7248                                         unsigned posLen) {
7249   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
7250                                getLocationOfByte(startPos),
7251                                /*IsStringLocation*/true,
7252                                getSpecifierRange(startPos, posLen));
7253 }
7254 
7255 void
7256 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
7257                                      analyze_format_string::PositionContext p) {
7258   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
7259                          << (unsigned) p,
7260                        getLocationOfByte(startPos), /*IsStringLocation*/true,
7261                        getSpecifierRange(startPos, posLen));
7262 }
7263 
7264 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
7265                                             unsigned posLen) {
7266   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
7267                                getLocationOfByte(startPos),
7268                                /*IsStringLocation*/true,
7269                                getSpecifierRange(startPos, posLen));
7270 }
7271 
7272 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
7273   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
7274     // The presence of a null character is likely an error.
7275     EmitFormatDiagnostic(
7276       S.PDiag(diag::warn_printf_format_string_contains_null_char),
7277       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
7278       getFormatStringRange());
7279   }
7280 }
7281 
7282 // Note that this may return NULL if there was an error parsing or building
7283 // one of the argument expressions.
7284 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
7285   return Args[FirstDataArg + i];
7286 }
7287 
7288 void CheckFormatHandler::DoneProcessing() {
7289   // Does the number of data arguments exceed the number of
7290   // format conversions in the format string?
7291   if (!HasVAListArg) {
7292       // Find any arguments that weren't covered.
7293     CoveredArgs.flip();
7294     signed notCoveredArg = CoveredArgs.find_first();
7295     if (notCoveredArg >= 0) {
7296       assert((unsigned)notCoveredArg < NumDataArgs);
7297       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
7298     } else {
7299       UncoveredArg.setAllCovered();
7300     }
7301   }
7302 }
7303 
7304 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7305                                    const Expr *ArgExpr) {
7306   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
7307          "Invalid state");
7308 
7309   if (!ArgExpr)
7310     return;
7311 
7312   SourceLocation Loc = ArgExpr->getBeginLoc();
7313 
7314   if (S.getSourceManager().isInSystemMacro(Loc))
7315     return;
7316 
7317   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
7318   for (auto E : DiagnosticExprs)
7319     PDiag << E->getSourceRange();
7320 
7321   CheckFormatHandler::EmitFormatDiagnostic(
7322                                   S, IsFunctionCall, DiagnosticExprs[0],
7323                                   PDiag, Loc, /*IsStringLocation*/false,
7324                                   DiagnosticExprs[0]->getSourceRange());
7325 }
7326 
7327 bool
7328 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7329                                                      SourceLocation Loc,
7330                                                      const char *startSpec,
7331                                                      unsigned specifierLen,
7332                                                      const char *csStart,
7333                                                      unsigned csLen) {
7334   bool keepGoing = true;
7335   if (argIndex < NumDataArgs) {
7336     // Consider the argument coverered, even though the specifier doesn't
7337     // make sense.
7338     CoveredArgs.set(argIndex);
7339   }
7340   else {
7341     // If argIndex exceeds the number of data arguments we
7342     // don't issue a warning because that is just a cascade of warnings (and
7343     // they may have intended '%%' anyway). We don't want to continue processing
7344     // the format string after this point, however, as we will like just get
7345     // gibberish when trying to match arguments.
7346     keepGoing = false;
7347   }
7348 
7349   StringRef Specifier(csStart, csLen);
7350 
7351   // If the specifier in non-printable, it could be the first byte of a UTF-8
7352   // sequence. In that case, print the UTF-8 code point. If not, print the byte
7353   // hex value.
7354   std::string CodePointStr;
7355   if (!llvm::sys::locale::isPrint(*csStart)) {
7356     llvm::UTF32 CodePoint;
7357     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7358     const llvm::UTF8 *E =
7359         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7360     llvm::ConversionResult Result =
7361         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
7362 
7363     if (Result != llvm::conversionOK) {
7364       unsigned char FirstChar = *csStart;
7365       CodePoint = (llvm::UTF32)FirstChar;
7366     }
7367 
7368     llvm::raw_string_ostream OS(CodePointStr);
7369     if (CodePoint < 256)
7370       OS << "\\x" << llvm::format("%02x", CodePoint);
7371     else if (CodePoint <= 0xFFFF)
7372       OS << "\\u" << llvm::format("%04x", CodePoint);
7373     else
7374       OS << "\\U" << llvm::format("%08x", CodePoint);
7375     OS.flush();
7376     Specifier = CodePointStr;
7377   }
7378 
7379   EmitFormatDiagnostic(
7380       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
7381       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
7382 
7383   return keepGoing;
7384 }
7385 
7386 void
7387 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7388                                                       const char *startSpec,
7389                                                       unsigned specifierLen) {
7390   EmitFormatDiagnostic(
7391     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
7392     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
7393 }
7394 
7395 bool
7396 CheckFormatHandler::CheckNumArgs(
7397   const analyze_format_string::FormatSpecifier &FS,
7398   const analyze_format_string::ConversionSpecifier &CS,
7399   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7400 
7401   if (argIndex >= NumDataArgs) {
7402     PartialDiagnostic PDiag = FS.usesPositionalArg()
7403       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
7404            << (argIndex+1) << NumDataArgs)
7405       : S.PDiag(diag::warn_printf_insufficient_data_args);
7406     EmitFormatDiagnostic(
7407       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
7408       getSpecifierRange(startSpecifier, specifierLen));
7409 
7410     // Since more arguments than conversion tokens are given, by extension
7411     // all arguments are covered, so mark this as so.
7412     UncoveredArg.setAllCovered();
7413     return false;
7414   }
7415   return true;
7416 }
7417 
7418 template<typename Range>
7419 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
7420                                               SourceLocation Loc,
7421                                               bool IsStringLocation,
7422                                               Range StringRange,
7423                                               ArrayRef<FixItHint> FixIt) {
7424   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
7425                        Loc, IsStringLocation, StringRange, FixIt);
7426 }
7427 
7428 /// If the format string is not within the function call, emit a note
7429 /// so that the function call and string are in diagnostic messages.
7430 ///
7431 /// \param InFunctionCall if true, the format string is within the function
7432 /// call and only one diagnostic message will be produced.  Otherwise, an
7433 /// extra note will be emitted pointing to location of the format string.
7434 ///
7435 /// \param ArgumentExpr the expression that is passed as the format string
7436 /// argument in the function call.  Used for getting locations when two
7437 /// diagnostics are emitted.
7438 ///
7439 /// \param PDiag the callee should already have provided any strings for the
7440 /// diagnostic message.  This function only adds locations and fixits
7441 /// to diagnostics.
7442 ///
7443 /// \param Loc primary location for diagnostic.  If two diagnostics are
7444 /// required, one will be at Loc and a new SourceLocation will be created for
7445 /// the other one.
7446 ///
7447 /// \param IsStringLocation if true, Loc points to the format string should be
7448 /// used for the note.  Otherwise, Loc points to the argument list and will
7449 /// be used with PDiag.
7450 ///
7451 /// \param StringRange some or all of the string to highlight.  This is
7452 /// templated so it can accept either a CharSourceRange or a SourceRange.
7453 ///
7454 /// \param FixIt optional fix it hint for the format string.
7455 template <typename Range>
7456 void CheckFormatHandler::EmitFormatDiagnostic(
7457     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
7458     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
7459     Range StringRange, ArrayRef<FixItHint> FixIt) {
7460   if (InFunctionCall) {
7461     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
7462     D << StringRange;
7463     D << FixIt;
7464   } else {
7465     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
7466       << ArgumentExpr->getSourceRange();
7467 
7468     const Sema::SemaDiagnosticBuilder &Note =
7469       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
7470              diag::note_format_string_defined);
7471 
7472     Note << StringRange;
7473     Note << FixIt;
7474   }
7475 }
7476 
7477 //===--- CHECK: Printf format string checking ------------------------------===//
7478 
7479 namespace {
7480 
7481 class CheckPrintfHandler : public CheckFormatHandler {
7482 public:
7483   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7484                      const Expr *origFormatExpr,
7485                      const Sema::FormatStringType type, unsigned firstDataArg,
7486                      unsigned numDataArgs, bool isObjC, const char *beg,
7487                      bool hasVAListArg, ArrayRef<const Expr *> Args,
7488                      unsigned formatIdx, bool inFunctionCall,
7489                      Sema::VariadicCallType CallType,
7490                      llvm::SmallBitVector &CheckedVarArgs,
7491                      UncoveredArgHandler &UncoveredArg)
7492       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7493                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
7494                            inFunctionCall, CallType, CheckedVarArgs,
7495                            UncoveredArg) {}
7496 
7497   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
7498 
7499   /// Returns true if '%@' specifiers are allowed in the format string.
7500   bool allowsObjCArg() const {
7501     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
7502            FSType == Sema::FST_OSTrace;
7503   }
7504 
7505   bool HandleInvalidPrintfConversionSpecifier(
7506                                       const analyze_printf::PrintfSpecifier &FS,
7507                                       const char *startSpecifier,
7508                                       unsigned specifierLen) override;
7509 
7510   void handleInvalidMaskType(StringRef MaskType) override;
7511 
7512   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7513                              const char *startSpecifier,
7514                              unsigned specifierLen) override;
7515   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7516                        const char *StartSpecifier,
7517                        unsigned SpecifierLen,
7518                        const Expr *E);
7519 
7520   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
7521                     const char *startSpecifier, unsigned specifierLen);
7522   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
7523                            const analyze_printf::OptionalAmount &Amt,
7524                            unsigned type,
7525                            const char *startSpecifier, unsigned specifierLen);
7526   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7527                   const analyze_printf::OptionalFlag &flag,
7528                   const char *startSpecifier, unsigned specifierLen);
7529   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
7530                          const analyze_printf::OptionalFlag &ignoredFlag,
7531                          const analyze_printf::OptionalFlag &flag,
7532                          const char *startSpecifier, unsigned specifierLen);
7533   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
7534                            const Expr *E);
7535 
7536   void HandleEmptyObjCModifierFlag(const char *startFlag,
7537                                    unsigned flagLen) override;
7538 
7539   void HandleInvalidObjCModifierFlag(const char *startFlag,
7540                                             unsigned flagLen) override;
7541 
7542   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
7543                                            const char *flagsEnd,
7544                                            const char *conversionPosition)
7545                                              override;
7546 };
7547 
7548 } // namespace
7549 
7550 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
7551                                       const analyze_printf::PrintfSpecifier &FS,
7552                                       const char *startSpecifier,
7553                                       unsigned specifierLen) {
7554   const analyze_printf::PrintfConversionSpecifier &CS =
7555     FS.getConversionSpecifier();
7556 
7557   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7558                                           getLocationOfByte(CS.getStart()),
7559                                           startSpecifier, specifierLen,
7560                                           CS.getStart(), CS.getLength());
7561 }
7562 
7563 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
7564   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
7565 }
7566 
7567 bool CheckPrintfHandler::HandleAmount(
7568                                const analyze_format_string::OptionalAmount &Amt,
7569                                unsigned k, const char *startSpecifier,
7570                                unsigned specifierLen) {
7571   if (Amt.hasDataArgument()) {
7572     if (!HasVAListArg) {
7573       unsigned argIndex = Amt.getArgIndex();
7574       if (argIndex >= NumDataArgs) {
7575         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
7576                                << k,
7577                              getLocationOfByte(Amt.getStart()),
7578                              /*IsStringLocation*/true,
7579                              getSpecifierRange(startSpecifier, specifierLen));
7580         // Don't do any more checking.  We will just emit
7581         // spurious errors.
7582         return false;
7583       }
7584 
7585       // Type check the data argument.  It should be an 'int'.
7586       // Although not in conformance with C99, we also allow the argument to be
7587       // an 'unsigned int' as that is a reasonably safe case.  GCC also
7588       // doesn't emit a warning for that case.
7589       CoveredArgs.set(argIndex);
7590       const Expr *Arg = getDataArg(argIndex);
7591       if (!Arg)
7592         return false;
7593 
7594       QualType T = Arg->getType();
7595 
7596       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
7597       assert(AT.isValid());
7598 
7599       if (!AT.matchesType(S.Context, T)) {
7600         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
7601                                << k << AT.getRepresentativeTypeName(S.Context)
7602                                << T << Arg->getSourceRange(),
7603                              getLocationOfByte(Amt.getStart()),
7604                              /*IsStringLocation*/true,
7605                              getSpecifierRange(startSpecifier, specifierLen));
7606         // Don't do any more checking.  We will just emit
7607         // spurious errors.
7608         return false;
7609       }
7610     }
7611   }
7612   return true;
7613 }
7614 
7615 void CheckPrintfHandler::HandleInvalidAmount(
7616                                       const analyze_printf::PrintfSpecifier &FS,
7617                                       const analyze_printf::OptionalAmount &Amt,
7618                                       unsigned type,
7619                                       const char *startSpecifier,
7620                                       unsigned specifierLen) {
7621   const analyze_printf::PrintfConversionSpecifier &CS =
7622     FS.getConversionSpecifier();
7623 
7624   FixItHint fixit =
7625     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
7626       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
7627                                  Amt.getConstantLength()))
7628       : FixItHint();
7629 
7630   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
7631                          << type << CS.toString(),
7632                        getLocationOfByte(Amt.getStart()),
7633                        /*IsStringLocation*/true,
7634                        getSpecifierRange(startSpecifier, specifierLen),
7635                        fixit);
7636 }
7637 
7638 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7639                                     const analyze_printf::OptionalFlag &flag,
7640                                     const char *startSpecifier,
7641                                     unsigned specifierLen) {
7642   // Warn about pointless flag with a fixit removal.
7643   const analyze_printf::PrintfConversionSpecifier &CS =
7644     FS.getConversionSpecifier();
7645   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
7646                          << flag.toString() << CS.toString(),
7647                        getLocationOfByte(flag.getPosition()),
7648                        /*IsStringLocation*/true,
7649                        getSpecifierRange(startSpecifier, specifierLen),
7650                        FixItHint::CreateRemoval(
7651                          getSpecifierRange(flag.getPosition(), 1)));
7652 }
7653 
7654 void CheckPrintfHandler::HandleIgnoredFlag(
7655                                 const analyze_printf::PrintfSpecifier &FS,
7656                                 const analyze_printf::OptionalFlag &ignoredFlag,
7657                                 const analyze_printf::OptionalFlag &flag,
7658                                 const char *startSpecifier,
7659                                 unsigned specifierLen) {
7660   // Warn about ignored flag with a fixit removal.
7661   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
7662                          << ignoredFlag.toString() << flag.toString(),
7663                        getLocationOfByte(ignoredFlag.getPosition()),
7664                        /*IsStringLocation*/true,
7665                        getSpecifierRange(startSpecifier, specifierLen),
7666                        FixItHint::CreateRemoval(
7667                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
7668 }
7669 
7670 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
7671                                                      unsigned flagLen) {
7672   // Warn about an empty flag.
7673   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
7674                        getLocationOfByte(startFlag),
7675                        /*IsStringLocation*/true,
7676                        getSpecifierRange(startFlag, flagLen));
7677 }
7678 
7679 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
7680                                                        unsigned flagLen) {
7681   // Warn about an invalid flag.
7682   auto Range = getSpecifierRange(startFlag, flagLen);
7683   StringRef flag(startFlag, flagLen);
7684   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
7685                       getLocationOfByte(startFlag),
7686                       /*IsStringLocation*/true,
7687                       Range, FixItHint::CreateRemoval(Range));
7688 }
7689 
7690 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
7691     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
7692     // Warn about using '[...]' without a '@' conversion.
7693     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
7694     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
7695     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
7696                          getLocationOfByte(conversionPosition),
7697                          /*IsStringLocation*/true,
7698                          Range, FixItHint::CreateRemoval(Range));
7699 }
7700 
7701 // Determines if the specified is a C++ class or struct containing
7702 // a member with the specified name and kind (e.g. a CXXMethodDecl named
7703 // "c_str()").
7704 template<typename MemberKind>
7705 static llvm::SmallPtrSet<MemberKind*, 1>
7706 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
7707   const RecordType *RT = Ty->getAs<RecordType>();
7708   llvm::SmallPtrSet<MemberKind*, 1> Results;
7709 
7710   if (!RT)
7711     return Results;
7712   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
7713   if (!RD || !RD->getDefinition())
7714     return Results;
7715 
7716   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
7717                  Sema::LookupMemberName);
7718   R.suppressDiagnostics();
7719 
7720   // We just need to include all members of the right kind turned up by the
7721   // filter, at this point.
7722   if (S.LookupQualifiedName(R, RT->getDecl()))
7723     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7724       NamedDecl *decl = (*I)->getUnderlyingDecl();
7725       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
7726         Results.insert(FK);
7727     }
7728   return Results;
7729 }
7730 
7731 /// Check if we could call '.c_str()' on an object.
7732 ///
7733 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
7734 /// allow the call, or if it would be ambiguous).
7735 bool Sema::hasCStrMethod(const Expr *E) {
7736   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7737 
7738   MethodSet Results =
7739       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
7740   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7741        MI != ME; ++MI)
7742     if ((*MI)->getMinRequiredArguments() == 0)
7743       return true;
7744   return false;
7745 }
7746 
7747 // Check if a (w)string was passed when a (w)char* was needed, and offer a
7748 // better diagnostic if so. AT is assumed to be valid.
7749 // Returns true when a c_str() conversion method is found.
7750 bool CheckPrintfHandler::checkForCStrMembers(
7751     const analyze_printf::ArgType &AT, const Expr *E) {
7752   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7753 
7754   MethodSet Results =
7755       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
7756 
7757   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7758        MI != ME; ++MI) {
7759     const CXXMethodDecl *Method = *MI;
7760     if (Method->getMinRequiredArguments() == 0 &&
7761         AT.matchesType(S.Context, Method->getReturnType())) {
7762       // FIXME: Suggest parens if the expression needs them.
7763       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
7764       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
7765           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
7766       return true;
7767     }
7768   }
7769 
7770   return false;
7771 }
7772 
7773 bool
7774 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
7775                                             &FS,
7776                                           const char *startSpecifier,
7777                                           unsigned specifierLen) {
7778   using namespace analyze_format_string;
7779   using namespace analyze_printf;
7780 
7781   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
7782 
7783   if (FS.consumesDataArgument()) {
7784     if (atFirstArg) {
7785         atFirstArg = false;
7786         usesPositionalArgs = FS.usesPositionalArg();
7787     }
7788     else if (usesPositionalArgs != FS.usesPositionalArg()) {
7789       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
7790                                         startSpecifier, specifierLen);
7791       return false;
7792     }
7793   }
7794 
7795   // First check if the field width, precision, and conversion specifier
7796   // have matching data arguments.
7797   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
7798                     startSpecifier, specifierLen)) {
7799     return false;
7800   }
7801 
7802   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
7803                     startSpecifier, specifierLen)) {
7804     return false;
7805   }
7806 
7807   if (!CS.consumesDataArgument()) {
7808     // FIXME: Technically specifying a precision or field width here
7809     // makes no sense.  Worth issuing a warning at some point.
7810     return true;
7811   }
7812 
7813   // Consume the argument.
7814   unsigned argIndex = FS.getArgIndex();
7815   if (argIndex < NumDataArgs) {
7816     // The check to see if the argIndex is valid will come later.
7817     // We set the bit here because we may exit early from this
7818     // function if we encounter some other error.
7819     CoveredArgs.set(argIndex);
7820   }
7821 
7822   // FreeBSD kernel extensions.
7823   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
7824       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
7825     // We need at least two arguments.
7826     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
7827       return false;
7828 
7829     // Claim the second argument.
7830     CoveredArgs.set(argIndex + 1);
7831 
7832     // Type check the first argument (int for %b, pointer for %D)
7833     const Expr *Ex = getDataArg(argIndex);
7834     const analyze_printf::ArgType &AT =
7835       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
7836         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
7837     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
7838       EmitFormatDiagnostic(
7839           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7840               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
7841               << false << Ex->getSourceRange(),
7842           Ex->getBeginLoc(), /*IsStringLocation*/ false,
7843           getSpecifierRange(startSpecifier, specifierLen));
7844 
7845     // Type check the second argument (char * for both %b and %D)
7846     Ex = getDataArg(argIndex + 1);
7847     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
7848     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
7849       EmitFormatDiagnostic(
7850           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7851               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
7852               << false << Ex->getSourceRange(),
7853           Ex->getBeginLoc(), /*IsStringLocation*/ false,
7854           getSpecifierRange(startSpecifier, specifierLen));
7855 
7856      return true;
7857   }
7858 
7859   // Check for using an Objective-C specific conversion specifier
7860   // in a non-ObjC literal.
7861   if (!allowsObjCArg() && CS.isObjCArg()) {
7862     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7863                                                   specifierLen);
7864   }
7865 
7866   // %P can only be used with os_log.
7867   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
7868     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7869                                                   specifierLen);
7870   }
7871 
7872   // %n is not allowed with os_log.
7873   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
7874     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
7875                          getLocationOfByte(CS.getStart()),
7876                          /*IsStringLocation*/ false,
7877                          getSpecifierRange(startSpecifier, specifierLen));
7878 
7879     return true;
7880   }
7881 
7882   // Only scalars are allowed for os_trace.
7883   if (FSType == Sema::FST_OSTrace &&
7884       (CS.getKind() == ConversionSpecifier::PArg ||
7885        CS.getKind() == ConversionSpecifier::sArg ||
7886        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
7887     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7888                                                   specifierLen);
7889   }
7890 
7891   // Check for use of public/private annotation outside of os_log().
7892   if (FSType != Sema::FST_OSLog) {
7893     if (FS.isPublic().isSet()) {
7894       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7895                                << "public",
7896                            getLocationOfByte(FS.isPublic().getPosition()),
7897                            /*IsStringLocation*/ false,
7898                            getSpecifierRange(startSpecifier, specifierLen));
7899     }
7900     if (FS.isPrivate().isSet()) {
7901       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7902                                << "private",
7903                            getLocationOfByte(FS.isPrivate().getPosition()),
7904                            /*IsStringLocation*/ false,
7905                            getSpecifierRange(startSpecifier, specifierLen));
7906     }
7907   }
7908 
7909   // Check for invalid use of field width
7910   if (!FS.hasValidFieldWidth()) {
7911     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
7912         startSpecifier, specifierLen);
7913   }
7914 
7915   // Check for invalid use of precision
7916   if (!FS.hasValidPrecision()) {
7917     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
7918         startSpecifier, specifierLen);
7919   }
7920 
7921   // Precision is mandatory for %P specifier.
7922   if (CS.getKind() == ConversionSpecifier::PArg &&
7923       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
7924     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
7925                          getLocationOfByte(startSpecifier),
7926                          /*IsStringLocation*/ false,
7927                          getSpecifierRange(startSpecifier, specifierLen));
7928   }
7929 
7930   // Check each flag does not conflict with any other component.
7931   if (!FS.hasValidThousandsGroupingPrefix())
7932     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
7933   if (!FS.hasValidLeadingZeros())
7934     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
7935   if (!FS.hasValidPlusPrefix())
7936     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
7937   if (!FS.hasValidSpacePrefix())
7938     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
7939   if (!FS.hasValidAlternativeForm())
7940     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
7941   if (!FS.hasValidLeftJustified())
7942     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
7943 
7944   // Check that flags are not ignored by another flag
7945   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
7946     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
7947         startSpecifier, specifierLen);
7948   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
7949     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
7950             startSpecifier, specifierLen);
7951 
7952   // Check the length modifier is valid with the given conversion specifier.
7953   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
7954                                  S.getLangOpts()))
7955     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7956                                 diag::warn_format_nonsensical_length);
7957   else if (!FS.hasStandardLengthModifier())
7958     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
7959   else if (!FS.hasStandardLengthConversionCombination())
7960     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7961                                 diag::warn_format_non_standard_conversion_spec);
7962 
7963   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
7964     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
7965 
7966   // The remaining checks depend on the data arguments.
7967   if (HasVAListArg)
7968     return true;
7969 
7970   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
7971     return false;
7972 
7973   const Expr *Arg = getDataArg(argIndex);
7974   if (!Arg)
7975     return true;
7976 
7977   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
7978 }
7979 
7980 static bool requiresParensToAddCast(const Expr *E) {
7981   // FIXME: We should have a general way to reason about operator
7982   // precedence and whether parens are actually needed here.
7983   // Take care of a few common cases where they aren't.
7984   const Expr *Inside = E->IgnoreImpCasts();
7985   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
7986     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
7987 
7988   switch (Inside->getStmtClass()) {
7989   case Stmt::ArraySubscriptExprClass:
7990   case Stmt::CallExprClass:
7991   case Stmt::CharacterLiteralClass:
7992   case Stmt::CXXBoolLiteralExprClass:
7993   case Stmt::DeclRefExprClass:
7994   case Stmt::FloatingLiteralClass:
7995   case Stmt::IntegerLiteralClass:
7996   case Stmt::MemberExprClass:
7997   case Stmt::ObjCArrayLiteralClass:
7998   case Stmt::ObjCBoolLiteralExprClass:
7999   case Stmt::ObjCBoxedExprClass:
8000   case Stmt::ObjCDictionaryLiteralClass:
8001   case Stmt::ObjCEncodeExprClass:
8002   case Stmt::ObjCIvarRefExprClass:
8003   case Stmt::ObjCMessageExprClass:
8004   case Stmt::ObjCPropertyRefExprClass:
8005   case Stmt::ObjCStringLiteralClass:
8006   case Stmt::ObjCSubscriptRefExprClass:
8007   case Stmt::ParenExprClass:
8008   case Stmt::StringLiteralClass:
8009   case Stmt::UnaryOperatorClass:
8010     return false;
8011   default:
8012     return true;
8013   }
8014 }
8015 
8016 static std::pair<QualType, StringRef>
8017 shouldNotPrintDirectly(const ASTContext &Context,
8018                        QualType IntendedTy,
8019                        const Expr *E) {
8020   // Use a 'while' to peel off layers of typedefs.
8021   QualType TyTy = IntendedTy;
8022   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
8023     StringRef Name = UserTy->getDecl()->getName();
8024     QualType CastTy = llvm::StringSwitch<QualType>(Name)
8025       .Case("CFIndex", Context.getNSIntegerType())
8026       .Case("NSInteger", Context.getNSIntegerType())
8027       .Case("NSUInteger", Context.getNSUIntegerType())
8028       .Case("SInt32", Context.IntTy)
8029       .Case("UInt32", Context.UnsignedIntTy)
8030       .Default(QualType());
8031 
8032     if (!CastTy.isNull())
8033       return std::make_pair(CastTy, Name);
8034 
8035     TyTy = UserTy->desugar();
8036   }
8037 
8038   // Strip parens if necessary.
8039   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
8040     return shouldNotPrintDirectly(Context,
8041                                   PE->getSubExpr()->getType(),
8042                                   PE->getSubExpr());
8043 
8044   // If this is a conditional expression, then its result type is constructed
8045   // via usual arithmetic conversions and thus there might be no necessary
8046   // typedef sugar there.  Recurse to operands to check for NSInteger &
8047   // Co. usage condition.
8048   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8049     QualType TrueTy, FalseTy;
8050     StringRef TrueName, FalseName;
8051 
8052     std::tie(TrueTy, TrueName) =
8053       shouldNotPrintDirectly(Context,
8054                              CO->getTrueExpr()->getType(),
8055                              CO->getTrueExpr());
8056     std::tie(FalseTy, FalseName) =
8057       shouldNotPrintDirectly(Context,
8058                              CO->getFalseExpr()->getType(),
8059                              CO->getFalseExpr());
8060 
8061     if (TrueTy == FalseTy)
8062       return std::make_pair(TrueTy, TrueName);
8063     else if (TrueTy.isNull())
8064       return std::make_pair(FalseTy, FalseName);
8065     else if (FalseTy.isNull())
8066       return std::make_pair(TrueTy, TrueName);
8067   }
8068 
8069   return std::make_pair(QualType(), StringRef());
8070 }
8071 
8072 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
8073 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
8074 /// type do not count.
8075 static bool
8076 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
8077   QualType From = ICE->getSubExpr()->getType();
8078   QualType To = ICE->getType();
8079   // It's an integer promotion if the destination type is the promoted
8080   // source type.
8081   if (ICE->getCastKind() == CK_IntegralCast &&
8082       From->isPromotableIntegerType() &&
8083       S.Context.getPromotedIntegerType(From) == To)
8084     return true;
8085   // Look through vector types, since we do default argument promotion for
8086   // those in OpenCL.
8087   if (const auto *VecTy = From->getAs<ExtVectorType>())
8088     From = VecTy->getElementType();
8089   if (const auto *VecTy = To->getAs<ExtVectorType>())
8090     To = VecTy->getElementType();
8091   // It's a floating promotion if the source type is a lower rank.
8092   return ICE->getCastKind() == CK_FloatingCast &&
8093          S.Context.getFloatingTypeOrder(From, To) < 0;
8094 }
8095 
8096 bool
8097 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8098                                     const char *StartSpecifier,
8099                                     unsigned SpecifierLen,
8100                                     const Expr *E) {
8101   using namespace analyze_format_string;
8102   using namespace analyze_printf;
8103 
8104   // Now type check the data expression that matches the
8105   // format specifier.
8106   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
8107   if (!AT.isValid())
8108     return true;
8109 
8110   QualType ExprTy = E->getType();
8111   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
8112     ExprTy = TET->getUnderlyingExpr()->getType();
8113   }
8114 
8115   // Diagnose attempts to print a boolean value as a character. Unlike other
8116   // -Wformat diagnostics, this is fine from a type perspective, but it still
8117   // doesn't make sense.
8118   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
8119       E->isKnownToHaveBooleanValue()) {
8120     const CharSourceRange &CSR =
8121         getSpecifierRange(StartSpecifier, SpecifierLen);
8122     SmallString<4> FSString;
8123     llvm::raw_svector_ostream os(FSString);
8124     FS.toString(os);
8125     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
8126                              << FSString,
8127                          E->getExprLoc(), false, CSR);
8128     return true;
8129   }
8130 
8131   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
8132   if (Match == analyze_printf::ArgType::Match)
8133     return true;
8134 
8135   // Look through argument promotions for our error message's reported type.
8136   // This includes the integral and floating promotions, but excludes array
8137   // and function pointer decay (seeing that an argument intended to be a
8138   // string has type 'char [6]' is probably more confusing than 'char *') and
8139   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
8140   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8141     if (isArithmeticArgumentPromotion(S, ICE)) {
8142       E = ICE->getSubExpr();
8143       ExprTy = E->getType();
8144 
8145       // Check if we didn't match because of an implicit cast from a 'char'
8146       // or 'short' to an 'int'.  This is done because printf is a varargs
8147       // function.
8148       if (ICE->getType() == S.Context.IntTy ||
8149           ICE->getType() == S.Context.UnsignedIntTy) {
8150         // All further checking is done on the subexpression
8151         const analyze_printf::ArgType::MatchKind ImplicitMatch =
8152             AT.matchesType(S.Context, ExprTy);
8153         if (ImplicitMatch == analyze_printf::ArgType::Match)
8154           return true;
8155         if (ImplicitMatch == ArgType::NoMatchPedantic ||
8156             ImplicitMatch == ArgType::NoMatchTypeConfusion)
8157           Match = ImplicitMatch;
8158       }
8159     }
8160   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
8161     // Special case for 'a', which has type 'int' in C.
8162     // Note, however, that we do /not/ want to treat multibyte constants like
8163     // 'MooV' as characters! This form is deprecated but still exists.
8164     if (ExprTy == S.Context.IntTy)
8165       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
8166         ExprTy = S.Context.CharTy;
8167   }
8168 
8169   // Look through enums to their underlying type.
8170   bool IsEnum = false;
8171   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
8172     ExprTy = EnumTy->getDecl()->getIntegerType();
8173     IsEnum = true;
8174   }
8175 
8176   // %C in an Objective-C context prints a unichar, not a wchar_t.
8177   // If the argument is an integer of some kind, believe the %C and suggest
8178   // a cast instead of changing the conversion specifier.
8179   QualType IntendedTy = ExprTy;
8180   if (isObjCContext() &&
8181       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
8182     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
8183         !ExprTy->isCharType()) {
8184       // 'unichar' is defined as a typedef of unsigned short, but we should
8185       // prefer using the typedef if it is visible.
8186       IntendedTy = S.Context.UnsignedShortTy;
8187 
8188       // While we are here, check if the value is an IntegerLiteral that happens
8189       // to be within the valid range.
8190       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
8191         const llvm::APInt &V = IL->getValue();
8192         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
8193           return true;
8194       }
8195 
8196       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
8197                           Sema::LookupOrdinaryName);
8198       if (S.LookupName(Result, S.getCurScope())) {
8199         NamedDecl *ND = Result.getFoundDecl();
8200         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
8201           if (TD->getUnderlyingType() == IntendedTy)
8202             IntendedTy = S.Context.getTypedefType(TD);
8203       }
8204     }
8205   }
8206 
8207   // Special-case some of Darwin's platform-independence types by suggesting
8208   // casts to primitive types that are known to be large enough.
8209   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
8210   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
8211     QualType CastTy;
8212     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
8213     if (!CastTy.isNull()) {
8214       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
8215       // (long in ASTContext). Only complain to pedants.
8216       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
8217           (AT.isSizeT() || AT.isPtrdiffT()) &&
8218           AT.matchesType(S.Context, CastTy))
8219         Match = ArgType::NoMatchPedantic;
8220       IntendedTy = CastTy;
8221       ShouldNotPrintDirectly = true;
8222     }
8223   }
8224 
8225   // We may be able to offer a FixItHint if it is a supported type.
8226   PrintfSpecifier fixedFS = FS;
8227   bool Success =
8228       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
8229 
8230   if (Success) {
8231     // Get the fix string from the fixed format specifier
8232     SmallString<16> buf;
8233     llvm::raw_svector_ostream os(buf);
8234     fixedFS.toString(os);
8235 
8236     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
8237 
8238     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
8239       unsigned Diag;
8240       switch (Match) {
8241       case ArgType::Match: llvm_unreachable("expected non-matching");
8242       case ArgType::NoMatchPedantic:
8243         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8244         break;
8245       case ArgType::NoMatchTypeConfusion:
8246         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8247         break;
8248       case ArgType::NoMatch:
8249         Diag = diag::warn_format_conversion_argument_type_mismatch;
8250         break;
8251       }
8252 
8253       // In this case, the specifier is wrong and should be changed to match
8254       // the argument.
8255       EmitFormatDiagnostic(S.PDiag(Diag)
8256                                << AT.getRepresentativeTypeName(S.Context)
8257                                << IntendedTy << IsEnum << E->getSourceRange(),
8258                            E->getBeginLoc(),
8259                            /*IsStringLocation*/ false, SpecRange,
8260                            FixItHint::CreateReplacement(SpecRange, os.str()));
8261     } else {
8262       // The canonical type for formatting this value is different from the
8263       // actual type of the expression. (This occurs, for example, with Darwin's
8264       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
8265       // should be printed as 'long' for 64-bit compatibility.)
8266       // Rather than emitting a normal format/argument mismatch, we want to
8267       // add a cast to the recommended type (and correct the format string
8268       // if necessary).
8269       SmallString<16> CastBuf;
8270       llvm::raw_svector_ostream CastFix(CastBuf);
8271       CastFix << "(";
8272       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
8273       CastFix << ")";
8274 
8275       SmallVector<FixItHint,4> Hints;
8276       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
8277         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
8278 
8279       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
8280         // If there's already a cast present, just replace it.
8281         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
8282         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
8283 
8284       } else if (!requiresParensToAddCast(E)) {
8285         // If the expression has high enough precedence,
8286         // just write the C-style cast.
8287         Hints.push_back(
8288             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8289       } else {
8290         // Otherwise, add parens around the expression as well as the cast.
8291         CastFix << "(";
8292         Hints.push_back(
8293             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8294 
8295         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
8296         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
8297       }
8298 
8299       if (ShouldNotPrintDirectly) {
8300         // The expression has a type that should not be printed directly.
8301         // We extract the name from the typedef because we don't want to show
8302         // the underlying type in the diagnostic.
8303         StringRef Name;
8304         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
8305           Name = TypedefTy->getDecl()->getName();
8306         else
8307           Name = CastTyName;
8308         unsigned Diag = Match == ArgType::NoMatchPedantic
8309                             ? diag::warn_format_argument_needs_cast_pedantic
8310                             : diag::warn_format_argument_needs_cast;
8311         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
8312                                            << E->getSourceRange(),
8313                              E->getBeginLoc(), /*IsStringLocation=*/false,
8314                              SpecRange, Hints);
8315       } else {
8316         // In this case, the expression could be printed using a different
8317         // specifier, but we've decided that the specifier is probably correct
8318         // and we should cast instead. Just use the normal warning message.
8319         EmitFormatDiagnostic(
8320             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8321                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
8322                 << E->getSourceRange(),
8323             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
8324       }
8325     }
8326   } else {
8327     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
8328                                                    SpecifierLen);
8329     // Since the warning for passing non-POD types to variadic functions
8330     // was deferred until now, we emit a warning for non-POD
8331     // arguments here.
8332     switch (S.isValidVarArgType(ExprTy)) {
8333     case Sema::VAK_Valid:
8334     case Sema::VAK_ValidInCXX11: {
8335       unsigned Diag;
8336       switch (Match) {
8337       case ArgType::Match: llvm_unreachable("expected non-matching");
8338       case ArgType::NoMatchPedantic:
8339         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8340         break;
8341       case ArgType::NoMatchTypeConfusion:
8342         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8343         break;
8344       case ArgType::NoMatch:
8345         Diag = diag::warn_format_conversion_argument_type_mismatch;
8346         break;
8347       }
8348 
8349       EmitFormatDiagnostic(
8350           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
8351                         << IsEnum << CSR << E->getSourceRange(),
8352           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8353       break;
8354     }
8355     case Sema::VAK_Undefined:
8356     case Sema::VAK_MSVCUndefined:
8357       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
8358                                << S.getLangOpts().CPlusPlus11 << ExprTy
8359                                << CallType
8360                                << AT.getRepresentativeTypeName(S.Context) << CSR
8361                                << E->getSourceRange(),
8362                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8363       checkForCStrMembers(AT, E);
8364       break;
8365 
8366     case Sema::VAK_Invalid:
8367       if (ExprTy->isObjCObjectType())
8368         EmitFormatDiagnostic(
8369             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
8370                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
8371                 << AT.getRepresentativeTypeName(S.Context) << CSR
8372                 << E->getSourceRange(),
8373             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8374       else
8375         // FIXME: If this is an initializer list, suggest removing the braces
8376         // or inserting a cast to the target type.
8377         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
8378             << isa<InitListExpr>(E) << ExprTy << CallType
8379             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
8380       break;
8381     }
8382 
8383     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
8384            "format string specifier index out of range");
8385     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
8386   }
8387 
8388   return true;
8389 }
8390 
8391 //===--- CHECK: Scanf format string checking ------------------------------===//
8392 
8393 namespace {
8394 
8395 class CheckScanfHandler : public CheckFormatHandler {
8396 public:
8397   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
8398                     const Expr *origFormatExpr, Sema::FormatStringType type,
8399                     unsigned firstDataArg, unsigned numDataArgs,
8400                     const char *beg, bool hasVAListArg,
8401                     ArrayRef<const Expr *> Args, unsigned formatIdx,
8402                     bool inFunctionCall, Sema::VariadicCallType CallType,
8403                     llvm::SmallBitVector &CheckedVarArgs,
8404                     UncoveredArgHandler &UncoveredArg)
8405       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8406                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8407                            inFunctionCall, CallType, CheckedVarArgs,
8408                            UncoveredArg) {}
8409 
8410   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
8411                             const char *startSpecifier,
8412                             unsigned specifierLen) override;
8413 
8414   bool HandleInvalidScanfConversionSpecifier(
8415           const analyze_scanf::ScanfSpecifier &FS,
8416           const char *startSpecifier,
8417           unsigned specifierLen) override;
8418 
8419   void HandleIncompleteScanList(const char *start, const char *end) override;
8420 };
8421 
8422 } // namespace
8423 
8424 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
8425                                                  const char *end) {
8426   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
8427                        getLocationOfByte(end), /*IsStringLocation*/true,
8428                        getSpecifierRange(start, end - start));
8429 }
8430 
8431 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
8432                                         const analyze_scanf::ScanfSpecifier &FS,
8433                                         const char *startSpecifier,
8434                                         unsigned specifierLen) {
8435   const analyze_scanf::ScanfConversionSpecifier &CS =
8436     FS.getConversionSpecifier();
8437 
8438   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8439                                           getLocationOfByte(CS.getStart()),
8440                                           startSpecifier, specifierLen,
8441                                           CS.getStart(), CS.getLength());
8442 }
8443 
8444 bool CheckScanfHandler::HandleScanfSpecifier(
8445                                        const analyze_scanf::ScanfSpecifier &FS,
8446                                        const char *startSpecifier,
8447                                        unsigned specifierLen) {
8448   using namespace analyze_scanf;
8449   using namespace analyze_format_string;
8450 
8451   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
8452 
8453   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
8454   // be used to decide if we are using positional arguments consistently.
8455   if (FS.consumesDataArgument()) {
8456     if (atFirstArg) {
8457       atFirstArg = false;
8458       usesPositionalArgs = FS.usesPositionalArg();
8459     }
8460     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8461       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8462                                         startSpecifier, specifierLen);
8463       return false;
8464     }
8465   }
8466 
8467   // Check if the field with is non-zero.
8468   const OptionalAmount &Amt = FS.getFieldWidth();
8469   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
8470     if (Amt.getConstantAmount() == 0) {
8471       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
8472                                                    Amt.getConstantLength());
8473       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
8474                            getLocationOfByte(Amt.getStart()),
8475                            /*IsStringLocation*/true, R,
8476                            FixItHint::CreateRemoval(R));
8477     }
8478   }
8479 
8480   if (!FS.consumesDataArgument()) {
8481     // FIXME: Technically specifying a precision or field width here
8482     // makes no sense.  Worth issuing a warning at some point.
8483     return true;
8484   }
8485 
8486   // Consume the argument.
8487   unsigned argIndex = FS.getArgIndex();
8488   if (argIndex < NumDataArgs) {
8489       // The check to see if the argIndex is valid will come later.
8490       // We set the bit here because we may exit early from this
8491       // function if we encounter some other error.
8492     CoveredArgs.set(argIndex);
8493   }
8494 
8495   // Check the length modifier is valid with the given conversion specifier.
8496   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8497                                  S.getLangOpts()))
8498     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8499                                 diag::warn_format_nonsensical_length);
8500   else if (!FS.hasStandardLengthModifier())
8501     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8502   else if (!FS.hasStandardLengthConversionCombination())
8503     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8504                                 diag::warn_format_non_standard_conversion_spec);
8505 
8506   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8507     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8508 
8509   // The remaining checks depend on the data arguments.
8510   if (HasVAListArg)
8511     return true;
8512 
8513   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8514     return false;
8515 
8516   // Check that the argument type matches the format specifier.
8517   const Expr *Ex = getDataArg(argIndex);
8518   if (!Ex)
8519     return true;
8520 
8521   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
8522 
8523   if (!AT.isValid()) {
8524     return true;
8525   }
8526 
8527   analyze_format_string::ArgType::MatchKind Match =
8528       AT.matchesType(S.Context, Ex->getType());
8529   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
8530   if (Match == analyze_format_string::ArgType::Match)
8531     return true;
8532 
8533   ScanfSpecifier fixedFS = FS;
8534   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
8535                                  S.getLangOpts(), S.Context);
8536 
8537   unsigned Diag =
8538       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8539                : diag::warn_format_conversion_argument_type_mismatch;
8540 
8541   if (Success) {
8542     // Get the fix string from the fixed format specifier.
8543     SmallString<128> buf;
8544     llvm::raw_svector_ostream os(buf);
8545     fixedFS.toString(os);
8546 
8547     EmitFormatDiagnostic(
8548         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
8549                       << Ex->getType() << false << Ex->getSourceRange(),
8550         Ex->getBeginLoc(),
8551         /*IsStringLocation*/ false,
8552         getSpecifierRange(startSpecifier, specifierLen),
8553         FixItHint::CreateReplacement(
8554             getSpecifierRange(startSpecifier, specifierLen), os.str()));
8555   } else {
8556     EmitFormatDiagnostic(S.PDiag(Diag)
8557                              << AT.getRepresentativeTypeName(S.Context)
8558                              << Ex->getType() << false << Ex->getSourceRange(),
8559                          Ex->getBeginLoc(),
8560                          /*IsStringLocation*/ false,
8561                          getSpecifierRange(startSpecifier, specifierLen));
8562   }
8563 
8564   return true;
8565 }
8566 
8567 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
8568                               const Expr *OrigFormatExpr,
8569                               ArrayRef<const Expr *> Args,
8570                               bool HasVAListArg, unsigned format_idx,
8571                               unsigned firstDataArg,
8572                               Sema::FormatStringType Type,
8573                               bool inFunctionCall,
8574                               Sema::VariadicCallType CallType,
8575                               llvm::SmallBitVector &CheckedVarArgs,
8576                               UncoveredArgHandler &UncoveredArg,
8577                               bool IgnoreStringsWithoutSpecifiers) {
8578   // CHECK: is the format string a wide literal?
8579   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
8580     CheckFormatHandler::EmitFormatDiagnostic(
8581         S, inFunctionCall, Args[format_idx],
8582         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
8583         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8584     return;
8585   }
8586 
8587   // Str - The format string.  NOTE: this is NOT null-terminated!
8588   StringRef StrRef = FExpr->getString();
8589   const char *Str = StrRef.data();
8590   // Account for cases where the string literal is truncated in a declaration.
8591   const ConstantArrayType *T =
8592     S.Context.getAsConstantArrayType(FExpr->getType());
8593   assert(T && "String literal not of constant array type!");
8594   size_t TypeSize = T->getSize().getZExtValue();
8595   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8596   const unsigned numDataArgs = Args.size() - firstDataArg;
8597 
8598   if (IgnoreStringsWithoutSpecifiers &&
8599       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
8600           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
8601     return;
8602 
8603   // Emit a warning if the string literal is truncated and does not contain an
8604   // embedded null character.
8605   if (TypeSize <= StrRef.size() &&
8606       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
8607     CheckFormatHandler::EmitFormatDiagnostic(
8608         S, inFunctionCall, Args[format_idx],
8609         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
8610         FExpr->getBeginLoc(),
8611         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
8612     return;
8613   }
8614 
8615   // CHECK: empty format string?
8616   if (StrLen == 0 && numDataArgs > 0) {
8617     CheckFormatHandler::EmitFormatDiagnostic(
8618         S, inFunctionCall, Args[format_idx],
8619         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
8620         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8621     return;
8622   }
8623 
8624   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
8625       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
8626       Type == Sema::FST_OSTrace) {
8627     CheckPrintfHandler H(
8628         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
8629         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
8630         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
8631         CheckedVarArgs, UncoveredArg);
8632 
8633     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
8634                                                   S.getLangOpts(),
8635                                                   S.Context.getTargetInfo(),
8636                                             Type == Sema::FST_FreeBSDKPrintf))
8637       H.DoneProcessing();
8638   } else if (Type == Sema::FST_Scanf) {
8639     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
8640                         numDataArgs, Str, HasVAListArg, Args, format_idx,
8641                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
8642 
8643     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
8644                                                  S.getLangOpts(),
8645                                                  S.Context.getTargetInfo()))
8646       H.DoneProcessing();
8647   } // TODO: handle other formats
8648 }
8649 
8650 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
8651   // Str - The format string.  NOTE: this is NOT null-terminated!
8652   StringRef StrRef = FExpr->getString();
8653   const char *Str = StrRef.data();
8654   // Account for cases where the string literal is truncated in a declaration.
8655   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
8656   assert(T && "String literal not of constant array type!");
8657   size_t TypeSize = T->getSize().getZExtValue();
8658   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8659   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
8660                                                          getLangOpts(),
8661                                                          Context.getTargetInfo());
8662 }
8663 
8664 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
8665 
8666 // Returns the related absolute value function that is larger, of 0 if one
8667 // does not exist.
8668 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
8669   switch (AbsFunction) {
8670   default:
8671     return 0;
8672 
8673   case Builtin::BI__builtin_abs:
8674     return Builtin::BI__builtin_labs;
8675   case Builtin::BI__builtin_labs:
8676     return Builtin::BI__builtin_llabs;
8677   case Builtin::BI__builtin_llabs:
8678     return 0;
8679 
8680   case Builtin::BI__builtin_fabsf:
8681     return Builtin::BI__builtin_fabs;
8682   case Builtin::BI__builtin_fabs:
8683     return Builtin::BI__builtin_fabsl;
8684   case Builtin::BI__builtin_fabsl:
8685     return 0;
8686 
8687   case Builtin::BI__builtin_cabsf:
8688     return Builtin::BI__builtin_cabs;
8689   case Builtin::BI__builtin_cabs:
8690     return Builtin::BI__builtin_cabsl;
8691   case Builtin::BI__builtin_cabsl:
8692     return 0;
8693 
8694   case Builtin::BIabs:
8695     return Builtin::BIlabs;
8696   case Builtin::BIlabs:
8697     return Builtin::BIllabs;
8698   case Builtin::BIllabs:
8699     return 0;
8700 
8701   case Builtin::BIfabsf:
8702     return Builtin::BIfabs;
8703   case Builtin::BIfabs:
8704     return Builtin::BIfabsl;
8705   case Builtin::BIfabsl:
8706     return 0;
8707 
8708   case Builtin::BIcabsf:
8709    return Builtin::BIcabs;
8710   case Builtin::BIcabs:
8711     return Builtin::BIcabsl;
8712   case Builtin::BIcabsl:
8713     return 0;
8714   }
8715 }
8716 
8717 // Returns the argument type of the absolute value function.
8718 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
8719                                              unsigned AbsType) {
8720   if (AbsType == 0)
8721     return QualType();
8722 
8723   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
8724   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
8725   if (Error != ASTContext::GE_None)
8726     return QualType();
8727 
8728   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
8729   if (!FT)
8730     return QualType();
8731 
8732   if (FT->getNumParams() != 1)
8733     return QualType();
8734 
8735   return FT->getParamType(0);
8736 }
8737 
8738 // Returns the best absolute value function, or zero, based on type and
8739 // current absolute value function.
8740 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
8741                                    unsigned AbsFunctionKind) {
8742   unsigned BestKind = 0;
8743   uint64_t ArgSize = Context.getTypeSize(ArgType);
8744   for (unsigned Kind = AbsFunctionKind; Kind != 0;
8745        Kind = getLargerAbsoluteValueFunction(Kind)) {
8746     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
8747     if (Context.getTypeSize(ParamType) >= ArgSize) {
8748       if (BestKind == 0)
8749         BestKind = Kind;
8750       else if (Context.hasSameType(ParamType, ArgType)) {
8751         BestKind = Kind;
8752         break;
8753       }
8754     }
8755   }
8756   return BestKind;
8757 }
8758 
8759 enum AbsoluteValueKind {
8760   AVK_Integer,
8761   AVK_Floating,
8762   AVK_Complex
8763 };
8764 
8765 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
8766   if (T->isIntegralOrEnumerationType())
8767     return AVK_Integer;
8768   if (T->isRealFloatingType())
8769     return AVK_Floating;
8770   if (T->isAnyComplexType())
8771     return AVK_Complex;
8772 
8773   llvm_unreachable("Type not integer, floating, or complex");
8774 }
8775 
8776 // Changes the absolute value function to a different type.  Preserves whether
8777 // the function is a builtin.
8778 static unsigned changeAbsFunction(unsigned AbsKind,
8779                                   AbsoluteValueKind ValueKind) {
8780   switch (ValueKind) {
8781   case AVK_Integer:
8782     switch (AbsKind) {
8783     default:
8784       return 0;
8785     case Builtin::BI__builtin_fabsf:
8786     case Builtin::BI__builtin_fabs:
8787     case Builtin::BI__builtin_fabsl:
8788     case Builtin::BI__builtin_cabsf:
8789     case Builtin::BI__builtin_cabs:
8790     case Builtin::BI__builtin_cabsl:
8791       return Builtin::BI__builtin_abs;
8792     case Builtin::BIfabsf:
8793     case Builtin::BIfabs:
8794     case Builtin::BIfabsl:
8795     case Builtin::BIcabsf:
8796     case Builtin::BIcabs:
8797     case Builtin::BIcabsl:
8798       return Builtin::BIabs;
8799     }
8800   case AVK_Floating:
8801     switch (AbsKind) {
8802     default:
8803       return 0;
8804     case Builtin::BI__builtin_abs:
8805     case Builtin::BI__builtin_labs:
8806     case Builtin::BI__builtin_llabs:
8807     case Builtin::BI__builtin_cabsf:
8808     case Builtin::BI__builtin_cabs:
8809     case Builtin::BI__builtin_cabsl:
8810       return Builtin::BI__builtin_fabsf;
8811     case Builtin::BIabs:
8812     case Builtin::BIlabs:
8813     case Builtin::BIllabs:
8814     case Builtin::BIcabsf:
8815     case Builtin::BIcabs:
8816     case Builtin::BIcabsl:
8817       return Builtin::BIfabsf;
8818     }
8819   case AVK_Complex:
8820     switch (AbsKind) {
8821     default:
8822       return 0;
8823     case Builtin::BI__builtin_abs:
8824     case Builtin::BI__builtin_labs:
8825     case Builtin::BI__builtin_llabs:
8826     case Builtin::BI__builtin_fabsf:
8827     case Builtin::BI__builtin_fabs:
8828     case Builtin::BI__builtin_fabsl:
8829       return Builtin::BI__builtin_cabsf;
8830     case Builtin::BIabs:
8831     case Builtin::BIlabs:
8832     case Builtin::BIllabs:
8833     case Builtin::BIfabsf:
8834     case Builtin::BIfabs:
8835     case Builtin::BIfabsl:
8836       return Builtin::BIcabsf;
8837     }
8838   }
8839   llvm_unreachable("Unable to convert function");
8840 }
8841 
8842 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
8843   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
8844   if (!FnInfo)
8845     return 0;
8846 
8847   switch (FDecl->getBuiltinID()) {
8848   default:
8849     return 0;
8850   case Builtin::BI__builtin_abs:
8851   case Builtin::BI__builtin_fabs:
8852   case Builtin::BI__builtin_fabsf:
8853   case Builtin::BI__builtin_fabsl:
8854   case Builtin::BI__builtin_labs:
8855   case Builtin::BI__builtin_llabs:
8856   case Builtin::BI__builtin_cabs:
8857   case Builtin::BI__builtin_cabsf:
8858   case Builtin::BI__builtin_cabsl:
8859   case Builtin::BIabs:
8860   case Builtin::BIlabs:
8861   case Builtin::BIllabs:
8862   case Builtin::BIfabs:
8863   case Builtin::BIfabsf:
8864   case Builtin::BIfabsl:
8865   case Builtin::BIcabs:
8866   case Builtin::BIcabsf:
8867   case Builtin::BIcabsl:
8868     return FDecl->getBuiltinID();
8869   }
8870   llvm_unreachable("Unknown Builtin type");
8871 }
8872 
8873 // If the replacement is valid, emit a note with replacement function.
8874 // Additionally, suggest including the proper header if not already included.
8875 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
8876                             unsigned AbsKind, QualType ArgType) {
8877   bool EmitHeaderHint = true;
8878   const char *HeaderName = nullptr;
8879   const char *FunctionName = nullptr;
8880   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
8881     FunctionName = "std::abs";
8882     if (ArgType->isIntegralOrEnumerationType()) {
8883       HeaderName = "cstdlib";
8884     } else if (ArgType->isRealFloatingType()) {
8885       HeaderName = "cmath";
8886     } else {
8887       llvm_unreachable("Invalid Type");
8888     }
8889 
8890     // Lookup all std::abs
8891     if (NamespaceDecl *Std = S.getStdNamespace()) {
8892       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
8893       R.suppressDiagnostics();
8894       S.LookupQualifiedName(R, Std);
8895 
8896       for (const auto *I : R) {
8897         const FunctionDecl *FDecl = nullptr;
8898         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
8899           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
8900         } else {
8901           FDecl = dyn_cast<FunctionDecl>(I);
8902         }
8903         if (!FDecl)
8904           continue;
8905 
8906         // Found std::abs(), check that they are the right ones.
8907         if (FDecl->getNumParams() != 1)
8908           continue;
8909 
8910         // Check that the parameter type can handle the argument.
8911         QualType ParamType = FDecl->getParamDecl(0)->getType();
8912         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
8913             S.Context.getTypeSize(ArgType) <=
8914                 S.Context.getTypeSize(ParamType)) {
8915           // Found a function, don't need the header hint.
8916           EmitHeaderHint = false;
8917           break;
8918         }
8919       }
8920     }
8921   } else {
8922     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
8923     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
8924 
8925     if (HeaderName) {
8926       DeclarationName DN(&S.Context.Idents.get(FunctionName));
8927       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
8928       R.suppressDiagnostics();
8929       S.LookupName(R, S.getCurScope());
8930 
8931       if (R.isSingleResult()) {
8932         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
8933         if (FD && FD->getBuiltinID() == AbsKind) {
8934           EmitHeaderHint = false;
8935         } else {
8936           return;
8937         }
8938       } else if (!R.empty()) {
8939         return;
8940       }
8941     }
8942   }
8943 
8944   S.Diag(Loc, diag::note_replace_abs_function)
8945       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
8946 
8947   if (!HeaderName)
8948     return;
8949 
8950   if (!EmitHeaderHint)
8951     return;
8952 
8953   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
8954                                                     << FunctionName;
8955 }
8956 
8957 template <std::size_t StrLen>
8958 static bool IsStdFunction(const FunctionDecl *FDecl,
8959                           const char (&Str)[StrLen]) {
8960   if (!FDecl)
8961     return false;
8962   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
8963     return false;
8964   if (!FDecl->isInStdNamespace())
8965     return false;
8966 
8967   return true;
8968 }
8969 
8970 // Warn when using the wrong abs() function.
8971 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
8972                                       const FunctionDecl *FDecl) {
8973   if (Call->getNumArgs() != 1)
8974     return;
8975 
8976   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
8977   bool IsStdAbs = IsStdFunction(FDecl, "abs");
8978   if (AbsKind == 0 && !IsStdAbs)
8979     return;
8980 
8981   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
8982   QualType ParamType = Call->getArg(0)->getType();
8983 
8984   // Unsigned types cannot be negative.  Suggest removing the absolute value
8985   // function call.
8986   if (ArgType->isUnsignedIntegerType()) {
8987     const char *FunctionName =
8988         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
8989     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
8990     Diag(Call->getExprLoc(), diag::note_remove_abs)
8991         << FunctionName
8992         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
8993     return;
8994   }
8995 
8996   // Taking the absolute value of a pointer is very suspicious, they probably
8997   // wanted to index into an array, dereference a pointer, call a function, etc.
8998   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
8999     unsigned DiagType = 0;
9000     if (ArgType->isFunctionType())
9001       DiagType = 1;
9002     else if (ArgType->isArrayType())
9003       DiagType = 2;
9004 
9005     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
9006     return;
9007   }
9008 
9009   // std::abs has overloads which prevent most of the absolute value problems
9010   // from occurring.
9011   if (IsStdAbs)
9012     return;
9013 
9014   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
9015   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
9016 
9017   // The argument and parameter are the same kind.  Check if they are the right
9018   // size.
9019   if (ArgValueKind == ParamValueKind) {
9020     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
9021       return;
9022 
9023     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
9024     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
9025         << FDecl << ArgType << ParamType;
9026 
9027     if (NewAbsKind == 0)
9028       return;
9029 
9030     emitReplacement(*this, Call->getExprLoc(),
9031                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9032     return;
9033   }
9034 
9035   // ArgValueKind != ParamValueKind
9036   // The wrong type of absolute value function was used.  Attempt to find the
9037   // proper one.
9038   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
9039   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
9040   if (NewAbsKind == 0)
9041     return;
9042 
9043   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
9044       << FDecl << ParamValueKind << ArgValueKind;
9045 
9046   emitReplacement(*this, Call->getExprLoc(),
9047                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9048 }
9049 
9050 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
9051 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
9052                                 const FunctionDecl *FDecl) {
9053   if (!Call || !FDecl) return;
9054 
9055   // Ignore template specializations and macros.
9056   if (inTemplateInstantiation()) return;
9057   if (Call->getExprLoc().isMacroID()) return;
9058 
9059   // Only care about the one template argument, two function parameter std::max
9060   if (Call->getNumArgs() != 2) return;
9061   if (!IsStdFunction(FDecl, "max")) return;
9062   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
9063   if (!ArgList) return;
9064   if (ArgList->size() != 1) return;
9065 
9066   // Check that template type argument is unsigned integer.
9067   const auto& TA = ArgList->get(0);
9068   if (TA.getKind() != TemplateArgument::Type) return;
9069   QualType ArgType = TA.getAsType();
9070   if (!ArgType->isUnsignedIntegerType()) return;
9071 
9072   // See if either argument is a literal zero.
9073   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
9074     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
9075     if (!MTE) return false;
9076     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
9077     if (!Num) return false;
9078     if (Num->getValue() != 0) return false;
9079     return true;
9080   };
9081 
9082   const Expr *FirstArg = Call->getArg(0);
9083   const Expr *SecondArg = Call->getArg(1);
9084   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
9085   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
9086 
9087   // Only warn when exactly one argument is zero.
9088   if (IsFirstArgZero == IsSecondArgZero) return;
9089 
9090   SourceRange FirstRange = FirstArg->getSourceRange();
9091   SourceRange SecondRange = SecondArg->getSourceRange();
9092 
9093   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
9094 
9095   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
9096       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
9097 
9098   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
9099   SourceRange RemovalRange;
9100   if (IsFirstArgZero) {
9101     RemovalRange = SourceRange(FirstRange.getBegin(),
9102                                SecondRange.getBegin().getLocWithOffset(-1));
9103   } else {
9104     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
9105                                SecondRange.getEnd());
9106   }
9107 
9108   Diag(Call->getExprLoc(), diag::note_remove_max_call)
9109         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
9110         << FixItHint::CreateRemoval(RemovalRange);
9111 }
9112 
9113 //===--- CHECK: Standard memory functions ---------------------------------===//
9114 
9115 /// Takes the expression passed to the size_t parameter of functions
9116 /// such as memcmp, strncat, etc and warns if it's a comparison.
9117 ///
9118 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
9119 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
9120                                            IdentifierInfo *FnName,
9121                                            SourceLocation FnLoc,
9122                                            SourceLocation RParenLoc) {
9123   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
9124   if (!Size)
9125     return false;
9126 
9127   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
9128   if (!Size->isComparisonOp() && !Size->isLogicalOp())
9129     return false;
9130 
9131   SourceRange SizeRange = Size->getSourceRange();
9132   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
9133       << SizeRange << FnName;
9134   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
9135       << FnName
9136       << FixItHint::CreateInsertion(
9137              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
9138       << FixItHint::CreateRemoval(RParenLoc);
9139   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
9140       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
9141       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
9142                                     ")");
9143 
9144   return true;
9145 }
9146 
9147 /// Determine whether the given type is or contains a dynamic class type
9148 /// (e.g., whether it has a vtable).
9149 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
9150                                                      bool &IsContained) {
9151   // Look through array types while ignoring qualifiers.
9152   const Type *Ty = T->getBaseElementTypeUnsafe();
9153   IsContained = false;
9154 
9155   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
9156   RD = RD ? RD->getDefinition() : nullptr;
9157   if (!RD || RD->isInvalidDecl())
9158     return nullptr;
9159 
9160   if (RD->isDynamicClass())
9161     return RD;
9162 
9163   // Check all the fields.  If any bases were dynamic, the class is dynamic.
9164   // It's impossible for a class to transitively contain itself by value, so
9165   // infinite recursion is impossible.
9166   for (auto *FD : RD->fields()) {
9167     bool SubContained;
9168     if (const CXXRecordDecl *ContainedRD =
9169             getContainedDynamicClass(FD->getType(), SubContained)) {
9170       IsContained = true;
9171       return ContainedRD;
9172     }
9173   }
9174 
9175   return nullptr;
9176 }
9177 
9178 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
9179   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
9180     if (Unary->getKind() == UETT_SizeOf)
9181       return Unary;
9182   return nullptr;
9183 }
9184 
9185 /// If E is a sizeof expression, returns its argument expression,
9186 /// otherwise returns NULL.
9187 static const Expr *getSizeOfExprArg(const Expr *E) {
9188   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9189     if (!SizeOf->isArgumentType())
9190       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
9191   return nullptr;
9192 }
9193 
9194 /// If E is a sizeof expression, returns its argument type.
9195 static QualType getSizeOfArgType(const Expr *E) {
9196   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9197     return SizeOf->getTypeOfArgument();
9198   return QualType();
9199 }
9200 
9201 namespace {
9202 
9203 struct SearchNonTrivialToInitializeField
9204     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
9205   using Super =
9206       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
9207 
9208   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
9209 
9210   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
9211                      SourceLocation SL) {
9212     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9213       asDerived().visitArray(PDIK, AT, SL);
9214       return;
9215     }
9216 
9217     Super::visitWithKind(PDIK, FT, SL);
9218   }
9219 
9220   void visitARCStrong(QualType FT, SourceLocation SL) {
9221     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9222   }
9223   void visitARCWeak(QualType FT, SourceLocation SL) {
9224     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9225   }
9226   void visitStruct(QualType FT, SourceLocation SL) {
9227     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9228       visit(FD->getType(), FD->getLocation());
9229   }
9230   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
9231                   const ArrayType *AT, SourceLocation SL) {
9232     visit(getContext().getBaseElementType(AT), SL);
9233   }
9234   void visitTrivial(QualType FT, SourceLocation SL) {}
9235 
9236   static void diag(QualType RT, const Expr *E, Sema &S) {
9237     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
9238   }
9239 
9240   ASTContext &getContext() { return S.getASTContext(); }
9241 
9242   const Expr *E;
9243   Sema &S;
9244 };
9245 
9246 struct SearchNonTrivialToCopyField
9247     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
9248   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
9249 
9250   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
9251 
9252   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
9253                      SourceLocation SL) {
9254     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9255       asDerived().visitArray(PCK, AT, SL);
9256       return;
9257     }
9258 
9259     Super::visitWithKind(PCK, FT, SL);
9260   }
9261 
9262   void visitARCStrong(QualType FT, SourceLocation SL) {
9263     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9264   }
9265   void visitARCWeak(QualType FT, SourceLocation SL) {
9266     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9267   }
9268   void visitStruct(QualType FT, SourceLocation SL) {
9269     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9270       visit(FD->getType(), FD->getLocation());
9271   }
9272   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
9273                   SourceLocation SL) {
9274     visit(getContext().getBaseElementType(AT), SL);
9275   }
9276   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
9277                 SourceLocation SL) {}
9278   void visitTrivial(QualType FT, SourceLocation SL) {}
9279   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
9280 
9281   static void diag(QualType RT, const Expr *E, Sema &S) {
9282     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
9283   }
9284 
9285   ASTContext &getContext() { return S.getASTContext(); }
9286 
9287   const Expr *E;
9288   Sema &S;
9289 };
9290 
9291 }
9292 
9293 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
9294 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
9295   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
9296 
9297   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
9298     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
9299       return false;
9300 
9301     return doesExprLikelyComputeSize(BO->getLHS()) ||
9302            doesExprLikelyComputeSize(BO->getRHS());
9303   }
9304 
9305   return getAsSizeOfExpr(SizeofExpr) != nullptr;
9306 }
9307 
9308 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
9309 ///
9310 /// \code
9311 ///   #define MACRO 0
9312 ///   foo(MACRO);
9313 ///   foo(0);
9314 /// \endcode
9315 ///
9316 /// This should return true for the first call to foo, but not for the second
9317 /// (regardless of whether foo is a macro or function).
9318 static bool isArgumentExpandedFromMacro(SourceManager &SM,
9319                                         SourceLocation CallLoc,
9320                                         SourceLocation ArgLoc) {
9321   if (!CallLoc.isMacroID())
9322     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
9323 
9324   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
9325          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
9326 }
9327 
9328 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
9329 /// last two arguments transposed.
9330 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
9331   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
9332     return;
9333 
9334   const Expr *SizeArg =
9335     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
9336 
9337   auto isLiteralZero = [](const Expr *E) {
9338     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
9339   };
9340 
9341   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
9342   SourceLocation CallLoc = Call->getRParenLoc();
9343   SourceManager &SM = S.getSourceManager();
9344   if (isLiteralZero(SizeArg) &&
9345       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
9346 
9347     SourceLocation DiagLoc = SizeArg->getExprLoc();
9348 
9349     // Some platforms #define bzero to __builtin_memset. See if this is the
9350     // case, and if so, emit a better diagnostic.
9351     if (BId == Builtin::BIbzero ||
9352         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
9353                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
9354       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
9355       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
9356     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
9357       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
9358       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
9359     }
9360     return;
9361   }
9362 
9363   // If the second argument to a memset is a sizeof expression and the third
9364   // isn't, this is also likely an error. This should catch
9365   // 'memset(buf, sizeof(buf), 0xff)'.
9366   if (BId == Builtin::BImemset &&
9367       doesExprLikelyComputeSize(Call->getArg(1)) &&
9368       !doesExprLikelyComputeSize(Call->getArg(2))) {
9369     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
9370     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
9371     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
9372     return;
9373   }
9374 }
9375 
9376 /// Check for dangerous or invalid arguments to memset().
9377 ///
9378 /// This issues warnings on known problematic, dangerous or unspecified
9379 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
9380 /// function calls.
9381 ///
9382 /// \param Call The call expression to diagnose.
9383 void Sema::CheckMemaccessArguments(const CallExpr *Call,
9384                                    unsigned BId,
9385                                    IdentifierInfo *FnName) {
9386   assert(BId != 0);
9387 
9388   // It is possible to have a non-standard definition of memset.  Validate
9389   // we have enough arguments, and if not, abort further checking.
9390   unsigned ExpectedNumArgs =
9391       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
9392   if (Call->getNumArgs() < ExpectedNumArgs)
9393     return;
9394 
9395   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
9396                       BId == Builtin::BIstrndup ? 1 : 2);
9397   unsigned LenArg =
9398       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
9399   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
9400 
9401   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
9402                                      Call->getBeginLoc(), Call->getRParenLoc()))
9403     return;
9404 
9405   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
9406   CheckMemaccessSize(*this, BId, Call);
9407 
9408   // We have special checking when the length is a sizeof expression.
9409   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
9410   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
9411   llvm::FoldingSetNodeID SizeOfArgID;
9412 
9413   // Although widely used, 'bzero' is not a standard function. Be more strict
9414   // with the argument types before allowing diagnostics and only allow the
9415   // form bzero(ptr, sizeof(...)).
9416   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9417   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
9418     return;
9419 
9420   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
9421     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
9422     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
9423 
9424     QualType DestTy = Dest->getType();
9425     QualType PointeeTy;
9426     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
9427       PointeeTy = DestPtrTy->getPointeeType();
9428 
9429       // Never warn about void type pointers. This can be used to suppress
9430       // false positives.
9431       if (PointeeTy->isVoidType())
9432         continue;
9433 
9434       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
9435       // actually comparing the expressions for equality. Because computing the
9436       // expression IDs can be expensive, we only do this if the diagnostic is
9437       // enabled.
9438       if (SizeOfArg &&
9439           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
9440                            SizeOfArg->getExprLoc())) {
9441         // We only compute IDs for expressions if the warning is enabled, and
9442         // cache the sizeof arg's ID.
9443         if (SizeOfArgID == llvm::FoldingSetNodeID())
9444           SizeOfArg->Profile(SizeOfArgID, Context, true);
9445         llvm::FoldingSetNodeID DestID;
9446         Dest->Profile(DestID, Context, true);
9447         if (DestID == SizeOfArgID) {
9448           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
9449           //       over sizeof(src) as well.
9450           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
9451           StringRef ReadableName = FnName->getName();
9452 
9453           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
9454             if (UnaryOp->getOpcode() == UO_AddrOf)
9455               ActionIdx = 1; // If its an address-of operator, just remove it.
9456           if (!PointeeTy->isIncompleteType() &&
9457               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
9458             ActionIdx = 2; // If the pointee's size is sizeof(char),
9459                            // suggest an explicit length.
9460 
9461           // If the function is defined as a builtin macro, do not show macro
9462           // expansion.
9463           SourceLocation SL = SizeOfArg->getExprLoc();
9464           SourceRange DSR = Dest->getSourceRange();
9465           SourceRange SSR = SizeOfArg->getSourceRange();
9466           SourceManager &SM = getSourceManager();
9467 
9468           if (SM.isMacroArgExpansion(SL)) {
9469             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
9470             SL = SM.getSpellingLoc(SL);
9471             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
9472                              SM.getSpellingLoc(DSR.getEnd()));
9473             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
9474                              SM.getSpellingLoc(SSR.getEnd()));
9475           }
9476 
9477           DiagRuntimeBehavior(SL, SizeOfArg,
9478                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
9479                                 << ReadableName
9480                                 << PointeeTy
9481                                 << DestTy
9482                                 << DSR
9483                                 << SSR);
9484           DiagRuntimeBehavior(SL, SizeOfArg,
9485                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
9486                                 << ActionIdx
9487                                 << SSR);
9488 
9489           break;
9490         }
9491       }
9492 
9493       // Also check for cases where the sizeof argument is the exact same
9494       // type as the memory argument, and where it points to a user-defined
9495       // record type.
9496       if (SizeOfArgTy != QualType()) {
9497         if (PointeeTy->isRecordType() &&
9498             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
9499           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
9500                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
9501                                 << FnName << SizeOfArgTy << ArgIdx
9502                                 << PointeeTy << Dest->getSourceRange()
9503                                 << LenExpr->getSourceRange());
9504           break;
9505         }
9506       }
9507     } else if (DestTy->isArrayType()) {
9508       PointeeTy = DestTy;
9509     }
9510 
9511     if (PointeeTy == QualType())
9512       continue;
9513 
9514     // Always complain about dynamic classes.
9515     bool IsContained;
9516     if (const CXXRecordDecl *ContainedRD =
9517             getContainedDynamicClass(PointeeTy, IsContained)) {
9518 
9519       unsigned OperationType = 0;
9520       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
9521       // "overwritten" if we're warning about the destination for any call
9522       // but memcmp; otherwise a verb appropriate to the call.
9523       if (ArgIdx != 0 || IsCmp) {
9524         if (BId == Builtin::BImemcpy)
9525           OperationType = 1;
9526         else if(BId == Builtin::BImemmove)
9527           OperationType = 2;
9528         else if (IsCmp)
9529           OperationType = 3;
9530       }
9531 
9532       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9533                           PDiag(diag::warn_dyn_class_memaccess)
9534                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
9535                               << IsContained << ContainedRD << OperationType
9536                               << Call->getCallee()->getSourceRange());
9537     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
9538              BId != Builtin::BImemset)
9539       DiagRuntimeBehavior(
9540         Dest->getExprLoc(), Dest,
9541         PDiag(diag::warn_arc_object_memaccess)
9542           << ArgIdx << FnName << PointeeTy
9543           << Call->getCallee()->getSourceRange());
9544     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
9545       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
9546           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
9547         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9548                             PDiag(diag::warn_cstruct_memaccess)
9549                                 << ArgIdx << FnName << PointeeTy << 0);
9550         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
9551       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
9552                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
9553         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9554                             PDiag(diag::warn_cstruct_memaccess)
9555                                 << ArgIdx << FnName << PointeeTy << 1);
9556         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
9557       } else {
9558         continue;
9559       }
9560     } else
9561       continue;
9562 
9563     DiagRuntimeBehavior(
9564       Dest->getExprLoc(), Dest,
9565       PDiag(diag::note_bad_memaccess_silence)
9566         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
9567     break;
9568   }
9569 }
9570 
9571 // A little helper routine: ignore addition and subtraction of integer literals.
9572 // This intentionally does not ignore all integer constant expressions because
9573 // we don't want to remove sizeof().
9574 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
9575   Ex = Ex->IgnoreParenCasts();
9576 
9577   while (true) {
9578     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
9579     if (!BO || !BO->isAdditiveOp())
9580       break;
9581 
9582     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
9583     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
9584 
9585     if (isa<IntegerLiteral>(RHS))
9586       Ex = LHS;
9587     else if (isa<IntegerLiteral>(LHS))
9588       Ex = RHS;
9589     else
9590       break;
9591   }
9592 
9593   return Ex;
9594 }
9595 
9596 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
9597                                                       ASTContext &Context) {
9598   // Only handle constant-sized or VLAs, but not flexible members.
9599   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
9600     // Only issue the FIXIT for arrays of size > 1.
9601     if (CAT->getSize().getSExtValue() <= 1)
9602       return false;
9603   } else if (!Ty->isVariableArrayType()) {
9604     return false;
9605   }
9606   return true;
9607 }
9608 
9609 // Warn if the user has made the 'size' argument to strlcpy or strlcat
9610 // be the size of the source, instead of the destination.
9611 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
9612                                     IdentifierInfo *FnName) {
9613 
9614   // Don't crash if the user has the wrong number of arguments
9615   unsigned NumArgs = Call->getNumArgs();
9616   if ((NumArgs != 3) && (NumArgs != 4))
9617     return;
9618 
9619   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
9620   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
9621   const Expr *CompareWithSrc = nullptr;
9622 
9623   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
9624                                      Call->getBeginLoc(), Call->getRParenLoc()))
9625     return;
9626 
9627   // Look for 'strlcpy(dst, x, sizeof(x))'
9628   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
9629     CompareWithSrc = Ex;
9630   else {
9631     // Look for 'strlcpy(dst, x, strlen(x))'
9632     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
9633       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
9634           SizeCall->getNumArgs() == 1)
9635         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
9636     }
9637   }
9638 
9639   if (!CompareWithSrc)
9640     return;
9641 
9642   // Determine if the argument to sizeof/strlen is equal to the source
9643   // argument.  In principle there's all kinds of things you could do
9644   // here, for instance creating an == expression and evaluating it with
9645   // EvaluateAsBooleanCondition, but this uses a more direct technique:
9646   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
9647   if (!SrcArgDRE)
9648     return;
9649 
9650   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
9651   if (!CompareWithSrcDRE ||
9652       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
9653     return;
9654 
9655   const Expr *OriginalSizeArg = Call->getArg(2);
9656   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
9657       << OriginalSizeArg->getSourceRange() << FnName;
9658 
9659   // Output a FIXIT hint if the destination is an array (rather than a
9660   // pointer to an array).  This could be enhanced to handle some
9661   // pointers if we know the actual size, like if DstArg is 'array+2'
9662   // we could say 'sizeof(array)-2'.
9663   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
9664   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
9665     return;
9666 
9667   SmallString<128> sizeString;
9668   llvm::raw_svector_ostream OS(sizeString);
9669   OS << "sizeof(";
9670   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9671   OS << ")";
9672 
9673   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
9674       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
9675                                       OS.str());
9676 }
9677 
9678 /// Check if two expressions refer to the same declaration.
9679 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
9680   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
9681     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
9682       return D1->getDecl() == D2->getDecl();
9683   return false;
9684 }
9685 
9686 static const Expr *getStrlenExprArg(const Expr *E) {
9687   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9688     const FunctionDecl *FD = CE->getDirectCallee();
9689     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
9690       return nullptr;
9691     return CE->getArg(0)->IgnoreParenCasts();
9692   }
9693   return nullptr;
9694 }
9695 
9696 // Warn on anti-patterns as the 'size' argument to strncat.
9697 // The correct size argument should look like following:
9698 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
9699 void Sema::CheckStrncatArguments(const CallExpr *CE,
9700                                  IdentifierInfo *FnName) {
9701   // Don't crash if the user has the wrong number of arguments.
9702   if (CE->getNumArgs() < 3)
9703     return;
9704   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
9705   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
9706   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
9707 
9708   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
9709                                      CE->getRParenLoc()))
9710     return;
9711 
9712   // Identify common expressions, which are wrongly used as the size argument
9713   // to strncat and may lead to buffer overflows.
9714   unsigned PatternType = 0;
9715   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
9716     // - sizeof(dst)
9717     if (referToTheSameDecl(SizeOfArg, DstArg))
9718       PatternType = 1;
9719     // - sizeof(src)
9720     else if (referToTheSameDecl(SizeOfArg, SrcArg))
9721       PatternType = 2;
9722   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
9723     if (BE->getOpcode() == BO_Sub) {
9724       const Expr *L = BE->getLHS()->IgnoreParenCasts();
9725       const Expr *R = BE->getRHS()->IgnoreParenCasts();
9726       // - sizeof(dst) - strlen(dst)
9727       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
9728           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
9729         PatternType = 1;
9730       // - sizeof(src) - (anything)
9731       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
9732         PatternType = 2;
9733     }
9734   }
9735 
9736   if (PatternType == 0)
9737     return;
9738 
9739   // Generate the diagnostic.
9740   SourceLocation SL = LenArg->getBeginLoc();
9741   SourceRange SR = LenArg->getSourceRange();
9742   SourceManager &SM = getSourceManager();
9743 
9744   // If the function is defined as a builtin macro, do not show macro expansion.
9745   if (SM.isMacroArgExpansion(SL)) {
9746     SL = SM.getSpellingLoc(SL);
9747     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
9748                      SM.getSpellingLoc(SR.getEnd()));
9749   }
9750 
9751   // Check if the destination is an array (rather than a pointer to an array).
9752   QualType DstTy = DstArg->getType();
9753   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
9754                                                                     Context);
9755   if (!isKnownSizeArray) {
9756     if (PatternType == 1)
9757       Diag(SL, diag::warn_strncat_wrong_size) << SR;
9758     else
9759       Diag(SL, diag::warn_strncat_src_size) << SR;
9760     return;
9761   }
9762 
9763   if (PatternType == 1)
9764     Diag(SL, diag::warn_strncat_large_size) << SR;
9765   else
9766     Diag(SL, diag::warn_strncat_src_size) << SR;
9767 
9768   SmallString<128> sizeString;
9769   llvm::raw_svector_ostream OS(sizeString);
9770   OS << "sizeof(";
9771   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9772   OS << ") - ";
9773   OS << "strlen(";
9774   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9775   OS << ") - 1";
9776 
9777   Diag(SL, diag::note_strncat_wrong_size)
9778     << FixItHint::CreateReplacement(SR, OS.str());
9779 }
9780 
9781 void
9782 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
9783                          SourceLocation ReturnLoc,
9784                          bool isObjCMethod,
9785                          const AttrVec *Attrs,
9786                          const FunctionDecl *FD) {
9787   // Check if the return value is null but should not be.
9788   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
9789        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
9790       CheckNonNullExpr(*this, RetValExp))
9791     Diag(ReturnLoc, diag::warn_null_ret)
9792       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
9793 
9794   // C++11 [basic.stc.dynamic.allocation]p4:
9795   //   If an allocation function declared with a non-throwing
9796   //   exception-specification fails to allocate storage, it shall return
9797   //   a null pointer. Any other allocation function that fails to allocate
9798   //   storage shall indicate failure only by throwing an exception [...]
9799   if (FD) {
9800     OverloadedOperatorKind Op = FD->getOverloadedOperator();
9801     if (Op == OO_New || Op == OO_Array_New) {
9802       const FunctionProtoType *Proto
9803         = FD->getType()->castAs<FunctionProtoType>();
9804       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
9805           CheckNonNullExpr(*this, RetValExp))
9806         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
9807           << FD << getLangOpts().CPlusPlus11;
9808     }
9809   }
9810 }
9811 
9812 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
9813 
9814 /// Check for comparisons of floating point operands using != and ==.
9815 /// Issue a warning if these are no self-comparisons, as they are not likely
9816 /// to do what the programmer intended.
9817 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
9818   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
9819   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
9820 
9821   // Special case: check for x == x (which is OK).
9822   // Do not emit warnings for such cases.
9823   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
9824     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
9825       if (DRL->getDecl() == DRR->getDecl())
9826         return;
9827 
9828   // Special case: check for comparisons against literals that can be exactly
9829   //  represented by APFloat.  In such cases, do not emit a warning.  This
9830   //  is a heuristic: often comparison against such literals are used to
9831   //  detect if a value in a variable has not changed.  This clearly can
9832   //  lead to false negatives.
9833   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
9834     if (FLL->isExact())
9835       return;
9836   } else
9837     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
9838       if (FLR->isExact())
9839         return;
9840 
9841   // Check for comparisons with builtin types.
9842   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
9843     if (CL->getBuiltinCallee())
9844       return;
9845 
9846   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
9847     if (CR->getBuiltinCallee())
9848       return;
9849 
9850   // Emit the diagnostic.
9851   Diag(Loc, diag::warn_floatingpoint_eq)
9852     << LHS->getSourceRange() << RHS->getSourceRange();
9853 }
9854 
9855 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
9856 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
9857 
9858 namespace {
9859 
9860 /// Structure recording the 'active' range of an integer-valued
9861 /// expression.
9862 struct IntRange {
9863   /// The number of bits active in the int.
9864   unsigned Width;
9865 
9866   /// True if the int is known not to have negative values.
9867   bool NonNegative;
9868 
9869   IntRange(unsigned Width, bool NonNegative)
9870       : Width(Width), NonNegative(NonNegative) {}
9871 
9872   /// Returns the range of the bool type.
9873   static IntRange forBoolType() {
9874     return IntRange(1, true);
9875   }
9876 
9877   /// Returns the range of an opaque value of the given integral type.
9878   static IntRange forValueOfType(ASTContext &C, QualType T) {
9879     return forValueOfCanonicalType(C,
9880                           T->getCanonicalTypeInternal().getTypePtr());
9881   }
9882 
9883   /// Returns the range of an opaque value of a canonical integral type.
9884   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
9885     assert(T->isCanonicalUnqualified());
9886 
9887     if (const VectorType *VT = dyn_cast<VectorType>(T))
9888       T = VT->getElementType().getTypePtr();
9889     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9890       T = CT->getElementType().getTypePtr();
9891     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9892       T = AT->getValueType().getTypePtr();
9893 
9894     if (!C.getLangOpts().CPlusPlus) {
9895       // For enum types in C code, use the underlying datatype.
9896       if (const EnumType *ET = dyn_cast<EnumType>(T))
9897         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
9898     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
9899       // For enum types in C++, use the known bit width of the enumerators.
9900       EnumDecl *Enum = ET->getDecl();
9901       // In C++11, enums can have a fixed underlying type. Use this type to
9902       // compute the range.
9903       if (Enum->isFixed()) {
9904         return IntRange(C.getIntWidth(QualType(T, 0)),
9905                         !ET->isSignedIntegerOrEnumerationType());
9906       }
9907 
9908       unsigned NumPositive = Enum->getNumPositiveBits();
9909       unsigned NumNegative = Enum->getNumNegativeBits();
9910 
9911       if (NumNegative == 0)
9912         return IntRange(NumPositive, true/*NonNegative*/);
9913       else
9914         return IntRange(std::max(NumPositive + 1, NumNegative),
9915                         false/*NonNegative*/);
9916     }
9917 
9918     if (const auto *EIT = dyn_cast<ExtIntType>(T))
9919       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
9920 
9921     const BuiltinType *BT = cast<BuiltinType>(T);
9922     assert(BT->isInteger());
9923 
9924     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9925   }
9926 
9927   /// Returns the "target" range of a canonical integral type, i.e.
9928   /// the range of values expressible in the type.
9929   ///
9930   /// This matches forValueOfCanonicalType except that enums have the
9931   /// full range of their type, not the range of their enumerators.
9932   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
9933     assert(T->isCanonicalUnqualified());
9934 
9935     if (const VectorType *VT = dyn_cast<VectorType>(T))
9936       T = VT->getElementType().getTypePtr();
9937     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9938       T = CT->getElementType().getTypePtr();
9939     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9940       T = AT->getValueType().getTypePtr();
9941     if (const EnumType *ET = dyn_cast<EnumType>(T))
9942       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
9943 
9944     if (const auto *EIT = dyn_cast<ExtIntType>(T))
9945       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
9946 
9947     const BuiltinType *BT = cast<BuiltinType>(T);
9948     assert(BT->isInteger());
9949 
9950     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9951   }
9952 
9953   /// Returns the supremum of two ranges: i.e. their conservative merge.
9954   static IntRange join(IntRange L, IntRange R) {
9955     return IntRange(std::max(L.Width, R.Width),
9956                     L.NonNegative && R.NonNegative);
9957   }
9958 
9959   /// Returns the infinum of two ranges: i.e. their aggressive merge.
9960   static IntRange meet(IntRange L, IntRange R) {
9961     return IntRange(std::min(L.Width, R.Width),
9962                     L.NonNegative || R.NonNegative);
9963   }
9964 };
9965 
9966 } // namespace
9967 
9968 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
9969                               unsigned MaxWidth) {
9970   if (value.isSigned() && value.isNegative())
9971     return IntRange(value.getMinSignedBits(), false);
9972 
9973   if (value.getBitWidth() > MaxWidth)
9974     value = value.trunc(MaxWidth);
9975 
9976   // isNonNegative() just checks the sign bit without considering
9977   // signedness.
9978   return IntRange(value.getActiveBits(), true);
9979 }
9980 
9981 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
9982                               unsigned MaxWidth) {
9983   if (result.isInt())
9984     return GetValueRange(C, result.getInt(), MaxWidth);
9985 
9986   if (result.isVector()) {
9987     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
9988     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
9989       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
9990       R = IntRange::join(R, El);
9991     }
9992     return R;
9993   }
9994 
9995   if (result.isComplexInt()) {
9996     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
9997     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
9998     return IntRange::join(R, I);
9999   }
10000 
10001   // This can happen with lossless casts to intptr_t of "based" lvalues.
10002   // Assume it might use arbitrary bits.
10003   // FIXME: The only reason we need to pass the type in here is to get
10004   // the sign right on this one case.  It would be nice if APValue
10005   // preserved this.
10006   assert(result.isLValue() || result.isAddrLabelDiff());
10007   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
10008 }
10009 
10010 static QualType GetExprType(const Expr *E) {
10011   QualType Ty = E->getType();
10012   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
10013     Ty = AtomicRHS->getValueType();
10014   return Ty;
10015 }
10016 
10017 /// Pseudo-evaluate the given integer expression, estimating the
10018 /// range of values it might take.
10019 ///
10020 /// \param MaxWidth - the width to which the value will be truncated
10021 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
10022                              bool InConstantContext) {
10023   E = E->IgnoreParens();
10024 
10025   // Try a full evaluation first.
10026   Expr::EvalResult result;
10027   if (E->EvaluateAsRValue(result, C, InConstantContext))
10028     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
10029 
10030   // I think we only want to look through implicit casts here; if the
10031   // user has an explicit widening cast, we should treat the value as
10032   // being of the new, wider type.
10033   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
10034     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
10035       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext);
10036 
10037     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
10038 
10039     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
10040                          CE->getCastKind() == CK_BooleanToSignedIntegral;
10041 
10042     // Assume that non-integer casts can span the full range of the type.
10043     if (!isIntegerCast)
10044       return OutputTypeRange;
10045 
10046     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
10047                                      std::min(MaxWidth, OutputTypeRange.Width),
10048                                      InConstantContext);
10049 
10050     // Bail out if the subexpr's range is as wide as the cast type.
10051     if (SubRange.Width >= OutputTypeRange.Width)
10052       return OutputTypeRange;
10053 
10054     // Otherwise, we take the smaller width, and we're non-negative if
10055     // either the output type or the subexpr is.
10056     return IntRange(SubRange.Width,
10057                     SubRange.NonNegative || OutputTypeRange.NonNegative);
10058   }
10059 
10060   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
10061     // If we can fold the condition, just take that operand.
10062     bool CondResult;
10063     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
10064       return GetExprRange(C,
10065                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
10066                           MaxWidth, InConstantContext);
10067 
10068     // Otherwise, conservatively merge.
10069     IntRange L =
10070         GetExprRange(C, CO->getTrueExpr(), MaxWidth, InConstantContext);
10071     IntRange R =
10072         GetExprRange(C, CO->getFalseExpr(), MaxWidth, InConstantContext);
10073     return IntRange::join(L, R);
10074   }
10075 
10076   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
10077     switch (BO->getOpcode()) {
10078     case BO_Cmp:
10079       llvm_unreachable("builtin <=> should have class type");
10080 
10081     // Boolean-valued operations are single-bit and positive.
10082     case BO_LAnd:
10083     case BO_LOr:
10084     case BO_LT:
10085     case BO_GT:
10086     case BO_LE:
10087     case BO_GE:
10088     case BO_EQ:
10089     case BO_NE:
10090       return IntRange::forBoolType();
10091 
10092     // The type of the assignments is the type of the LHS, so the RHS
10093     // is not necessarily the same type.
10094     case BO_MulAssign:
10095     case BO_DivAssign:
10096     case BO_RemAssign:
10097     case BO_AddAssign:
10098     case BO_SubAssign:
10099     case BO_XorAssign:
10100     case BO_OrAssign:
10101       // TODO: bitfields?
10102       return IntRange::forValueOfType(C, GetExprType(E));
10103 
10104     // Simple assignments just pass through the RHS, which will have
10105     // been coerced to the LHS type.
10106     case BO_Assign:
10107       // TODO: bitfields?
10108       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10109 
10110     // Operations with opaque sources are black-listed.
10111     case BO_PtrMemD:
10112     case BO_PtrMemI:
10113       return IntRange::forValueOfType(C, GetExprType(E));
10114 
10115     // Bitwise-and uses the *infinum* of the two source ranges.
10116     case BO_And:
10117     case BO_AndAssign:
10118       return IntRange::meet(
10119           GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext),
10120           GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext));
10121 
10122     // Left shift gets black-listed based on a judgement call.
10123     case BO_Shl:
10124       // ...except that we want to treat '1 << (blah)' as logically
10125       // positive.  It's an important idiom.
10126       if (IntegerLiteral *I
10127             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
10128         if (I->getValue() == 1) {
10129           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
10130           return IntRange(R.Width, /*NonNegative*/ true);
10131         }
10132       }
10133       LLVM_FALLTHROUGH;
10134 
10135     case BO_ShlAssign:
10136       return IntRange::forValueOfType(C, GetExprType(E));
10137 
10138     // Right shift by a constant can narrow its left argument.
10139     case BO_Shr:
10140     case BO_ShrAssign: {
10141       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
10142 
10143       // If the shift amount is a positive constant, drop the width by
10144       // that much.
10145       llvm::APSInt shift;
10146       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
10147           shift.isNonNegative()) {
10148         unsigned zext = shift.getZExtValue();
10149         if (zext >= L.Width)
10150           L.Width = (L.NonNegative ? 0 : 1);
10151         else
10152           L.Width -= zext;
10153       }
10154 
10155       return L;
10156     }
10157 
10158     // Comma acts as its right operand.
10159     case BO_Comma:
10160       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10161 
10162     // Black-list pointer subtractions.
10163     case BO_Sub:
10164       if (BO->getLHS()->getType()->isPointerType())
10165         return IntRange::forValueOfType(C, GetExprType(E));
10166       break;
10167 
10168     // The width of a division result is mostly determined by the size
10169     // of the LHS.
10170     case BO_Div: {
10171       // Don't 'pre-truncate' the operands.
10172       unsigned opWidth = C.getIntWidth(GetExprType(E));
10173       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
10174 
10175       // If the divisor is constant, use that.
10176       llvm::APSInt divisor;
10177       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
10178         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
10179         if (log2 >= L.Width)
10180           L.Width = (L.NonNegative ? 0 : 1);
10181         else
10182           L.Width = std::min(L.Width - log2, MaxWidth);
10183         return L;
10184       }
10185 
10186       // Otherwise, just use the LHS's width.
10187       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
10188       return IntRange(L.Width, L.NonNegative && R.NonNegative);
10189     }
10190 
10191     // The result of a remainder can't be larger than the result of
10192     // either side.
10193     case BO_Rem: {
10194       // Don't 'pre-truncate' the operands.
10195       unsigned opWidth = C.getIntWidth(GetExprType(E));
10196       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
10197       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
10198 
10199       IntRange meet = IntRange::meet(L, R);
10200       meet.Width = std::min(meet.Width, MaxWidth);
10201       return meet;
10202     }
10203 
10204     // The default behavior is okay for these.
10205     case BO_Mul:
10206     case BO_Add:
10207     case BO_Xor:
10208     case BO_Or:
10209       break;
10210     }
10211 
10212     // The default case is to treat the operation as if it were closed
10213     // on the narrowest type that encompasses both operands.
10214     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
10215     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10216     return IntRange::join(L, R);
10217   }
10218 
10219   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
10220     switch (UO->getOpcode()) {
10221     // Boolean-valued operations are white-listed.
10222     case UO_LNot:
10223       return IntRange::forBoolType();
10224 
10225     // Operations with opaque sources are black-listed.
10226     case UO_Deref:
10227     case UO_AddrOf: // should be impossible
10228       return IntRange::forValueOfType(C, GetExprType(E));
10229 
10230     default:
10231       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext);
10232     }
10233   }
10234 
10235   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
10236     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext);
10237 
10238   if (const auto *BitField = E->getSourceBitField())
10239     return IntRange(BitField->getBitWidthValue(C),
10240                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
10241 
10242   return IntRange::forValueOfType(C, GetExprType(E));
10243 }
10244 
10245 static IntRange GetExprRange(ASTContext &C, const Expr *E,
10246                              bool InConstantContext) {
10247   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext);
10248 }
10249 
10250 /// Checks whether the given value, which currently has the given
10251 /// source semantics, has the same value when coerced through the
10252 /// target semantics.
10253 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
10254                                  const llvm::fltSemantics &Src,
10255                                  const llvm::fltSemantics &Tgt) {
10256   llvm::APFloat truncated = value;
10257 
10258   bool ignored;
10259   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
10260   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
10261 
10262   return truncated.bitwiseIsEqual(value);
10263 }
10264 
10265 /// Checks whether the given value, which currently has the given
10266 /// source semantics, has the same value when coerced through the
10267 /// target semantics.
10268 ///
10269 /// The value might be a vector of floats (or a complex number).
10270 static bool IsSameFloatAfterCast(const APValue &value,
10271                                  const llvm::fltSemantics &Src,
10272                                  const llvm::fltSemantics &Tgt) {
10273   if (value.isFloat())
10274     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
10275 
10276   if (value.isVector()) {
10277     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
10278       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
10279         return false;
10280     return true;
10281   }
10282 
10283   assert(value.isComplexFloat());
10284   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
10285           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
10286 }
10287 
10288 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
10289                                        bool IsListInit = false);
10290 
10291 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
10292   // Suppress cases where we are comparing against an enum constant.
10293   if (const DeclRefExpr *DR =
10294       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
10295     if (isa<EnumConstantDecl>(DR->getDecl()))
10296       return true;
10297 
10298   // Suppress cases where the value is expanded from a macro, unless that macro
10299   // is how a language represents a boolean literal. This is the case in both C
10300   // and Objective-C.
10301   SourceLocation BeginLoc = E->getBeginLoc();
10302   if (BeginLoc.isMacroID()) {
10303     StringRef MacroName = Lexer::getImmediateMacroName(
10304         BeginLoc, S.getSourceManager(), S.getLangOpts());
10305     return MacroName != "YES" && MacroName != "NO" &&
10306            MacroName != "true" && MacroName != "false";
10307   }
10308 
10309   return false;
10310 }
10311 
10312 static bool isKnownToHaveUnsignedValue(Expr *E) {
10313   return E->getType()->isIntegerType() &&
10314          (!E->getType()->isSignedIntegerType() ||
10315           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
10316 }
10317 
10318 namespace {
10319 /// The promoted range of values of a type. In general this has the
10320 /// following structure:
10321 ///
10322 ///     |-----------| . . . |-----------|
10323 ///     ^           ^       ^           ^
10324 ///    Min       HoleMin  HoleMax      Max
10325 ///
10326 /// ... where there is only a hole if a signed type is promoted to unsigned
10327 /// (in which case Min and Max are the smallest and largest representable
10328 /// values).
10329 struct PromotedRange {
10330   // Min, or HoleMax if there is a hole.
10331   llvm::APSInt PromotedMin;
10332   // Max, or HoleMin if there is a hole.
10333   llvm::APSInt PromotedMax;
10334 
10335   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
10336     if (R.Width == 0)
10337       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
10338     else if (R.Width >= BitWidth && !Unsigned) {
10339       // Promotion made the type *narrower*. This happens when promoting
10340       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
10341       // Treat all values of 'signed int' as being in range for now.
10342       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
10343       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
10344     } else {
10345       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
10346                         .extOrTrunc(BitWidth);
10347       PromotedMin.setIsUnsigned(Unsigned);
10348 
10349       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
10350                         .extOrTrunc(BitWidth);
10351       PromotedMax.setIsUnsigned(Unsigned);
10352     }
10353   }
10354 
10355   // Determine whether this range is contiguous (has no hole).
10356   bool isContiguous() const { return PromotedMin <= PromotedMax; }
10357 
10358   // Where a constant value is within the range.
10359   enum ComparisonResult {
10360     LT = 0x1,
10361     LE = 0x2,
10362     GT = 0x4,
10363     GE = 0x8,
10364     EQ = 0x10,
10365     NE = 0x20,
10366     InRangeFlag = 0x40,
10367 
10368     Less = LE | LT | NE,
10369     Min = LE | InRangeFlag,
10370     InRange = InRangeFlag,
10371     Max = GE | InRangeFlag,
10372     Greater = GE | GT | NE,
10373 
10374     OnlyValue = LE | GE | EQ | InRangeFlag,
10375     InHole = NE
10376   };
10377 
10378   ComparisonResult compare(const llvm::APSInt &Value) const {
10379     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
10380            Value.isUnsigned() == PromotedMin.isUnsigned());
10381     if (!isContiguous()) {
10382       assert(Value.isUnsigned() && "discontiguous range for signed compare");
10383       if (Value.isMinValue()) return Min;
10384       if (Value.isMaxValue()) return Max;
10385       if (Value >= PromotedMin) return InRange;
10386       if (Value <= PromotedMax) return InRange;
10387       return InHole;
10388     }
10389 
10390     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
10391     case -1: return Less;
10392     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
10393     case 1:
10394       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
10395       case -1: return InRange;
10396       case 0: return Max;
10397       case 1: return Greater;
10398       }
10399     }
10400 
10401     llvm_unreachable("impossible compare result");
10402   }
10403 
10404   static llvm::Optional<StringRef>
10405   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
10406     if (Op == BO_Cmp) {
10407       ComparisonResult LTFlag = LT, GTFlag = GT;
10408       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
10409 
10410       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
10411       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
10412       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
10413       return llvm::None;
10414     }
10415 
10416     ComparisonResult TrueFlag, FalseFlag;
10417     if (Op == BO_EQ) {
10418       TrueFlag = EQ;
10419       FalseFlag = NE;
10420     } else if (Op == BO_NE) {
10421       TrueFlag = NE;
10422       FalseFlag = EQ;
10423     } else {
10424       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
10425         TrueFlag = LT;
10426         FalseFlag = GE;
10427       } else {
10428         TrueFlag = GT;
10429         FalseFlag = LE;
10430       }
10431       if (Op == BO_GE || Op == BO_LE)
10432         std::swap(TrueFlag, FalseFlag);
10433     }
10434     if (R & TrueFlag)
10435       return StringRef("true");
10436     if (R & FalseFlag)
10437       return StringRef("false");
10438     return llvm::None;
10439   }
10440 };
10441 }
10442 
10443 static bool HasEnumType(Expr *E) {
10444   // Strip off implicit integral promotions.
10445   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
10446     if (ICE->getCastKind() != CK_IntegralCast &&
10447         ICE->getCastKind() != CK_NoOp)
10448       break;
10449     E = ICE->getSubExpr();
10450   }
10451 
10452   return E->getType()->isEnumeralType();
10453 }
10454 
10455 static int classifyConstantValue(Expr *Constant) {
10456   // The values of this enumeration are used in the diagnostics
10457   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
10458   enum ConstantValueKind {
10459     Miscellaneous = 0,
10460     LiteralTrue,
10461     LiteralFalse
10462   };
10463   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
10464     return BL->getValue() ? ConstantValueKind::LiteralTrue
10465                           : ConstantValueKind::LiteralFalse;
10466   return ConstantValueKind::Miscellaneous;
10467 }
10468 
10469 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
10470                                         Expr *Constant, Expr *Other,
10471                                         const llvm::APSInt &Value,
10472                                         bool RhsConstant) {
10473   if (S.inTemplateInstantiation())
10474     return false;
10475 
10476   Expr *OriginalOther = Other;
10477 
10478   Constant = Constant->IgnoreParenImpCasts();
10479   Other = Other->IgnoreParenImpCasts();
10480 
10481   // Suppress warnings on tautological comparisons between values of the same
10482   // enumeration type. There are only two ways we could warn on this:
10483   //  - If the constant is outside the range of representable values of
10484   //    the enumeration. In such a case, we should warn about the cast
10485   //    to enumeration type, not about the comparison.
10486   //  - If the constant is the maximum / minimum in-range value. For an
10487   //    enumeratin type, such comparisons can be meaningful and useful.
10488   if (Constant->getType()->isEnumeralType() &&
10489       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
10490     return false;
10491 
10492   // TODO: Investigate using GetExprRange() to get tighter bounds
10493   // on the bit ranges.
10494   QualType OtherT = Other->getType();
10495   if (const auto *AT = OtherT->getAs<AtomicType>())
10496     OtherT = AT->getValueType();
10497   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
10498 
10499   // Special case for ObjC BOOL on targets where its a typedef for a signed char
10500   // (Namely, macOS).
10501   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
10502                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
10503                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
10504 
10505   // Whether we're treating Other as being a bool because of the form of
10506   // expression despite it having another type (typically 'int' in C).
10507   bool OtherIsBooleanDespiteType =
10508       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
10509   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
10510     OtherRange = IntRange::forBoolType();
10511 
10512   // Determine the promoted range of the other type and see if a comparison of
10513   // the constant against that range is tautological.
10514   PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
10515                                    Value.isUnsigned());
10516   auto Cmp = OtherPromotedRange.compare(Value);
10517   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
10518   if (!Result)
10519     return false;
10520 
10521   // Suppress the diagnostic for an in-range comparison if the constant comes
10522   // from a macro or enumerator. We don't want to diagnose
10523   //
10524   //   some_long_value <= INT_MAX
10525   //
10526   // when sizeof(int) == sizeof(long).
10527   bool InRange = Cmp & PromotedRange::InRangeFlag;
10528   if (InRange && IsEnumConstOrFromMacro(S, Constant))
10529     return false;
10530 
10531   // If this is a comparison to an enum constant, include that
10532   // constant in the diagnostic.
10533   const EnumConstantDecl *ED = nullptr;
10534   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
10535     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
10536 
10537   // Should be enough for uint128 (39 decimal digits)
10538   SmallString<64> PrettySourceValue;
10539   llvm::raw_svector_ostream OS(PrettySourceValue);
10540   if (ED) {
10541     OS << '\'' << *ED << "' (" << Value << ")";
10542   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
10543                Constant->IgnoreParenImpCasts())) {
10544     OS << (BL->getValue() ? "YES" : "NO");
10545   } else {
10546     OS << Value;
10547   }
10548 
10549   if (IsObjCSignedCharBool) {
10550     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10551                           S.PDiag(diag::warn_tautological_compare_objc_bool)
10552                               << OS.str() << *Result);
10553     return true;
10554   }
10555 
10556   // FIXME: We use a somewhat different formatting for the in-range cases and
10557   // cases involving boolean values for historical reasons. We should pick a
10558   // consistent way of presenting these diagnostics.
10559   if (!InRange || Other->isKnownToHaveBooleanValue()) {
10560 
10561     S.DiagRuntimeBehavior(
10562         E->getOperatorLoc(), E,
10563         S.PDiag(!InRange ? diag::warn_out_of_range_compare
10564                          : diag::warn_tautological_bool_compare)
10565             << OS.str() << classifyConstantValue(Constant) << OtherT
10566             << OtherIsBooleanDespiteType << *Result
10567             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
10568   } else {
10569     unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
10570                         ? (HasEnumType(OriginalOther)
10571                                ? diag::warn_unsigned_enum_always_true_comparison
10572                                : diag::warn_unsigned_always_true_comparison)
10573                         : diag::warn_tautological_constant_compare;
10574 
10575     S.Diag(E->getOperatorLoc(), Diag)
10576         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
10577         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
10578   }
10579 
10580   return true;
10581 }
10582 
10583 /// Analyze the operands of the given comparison.  Implements the
10584 /// fallback case from AnalyzeComparison.
10585 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
10586   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10587   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10588 }
10589 
10590 /// Implements -Wsign-compare.
10591 ///
10592 /// \param E the binary operator to check for warnings
10593 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
10594   // The type the comparison is being performed in.
10595   QualType T = E->getLHS()->getType();
10596 
10597   // Only analyze comparison operators where both sides have been converted to
10598   // the same type.
10599   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
10600     return AnalyzeImpConvsInComparison(S, E);
10601 
10602   // Don't analyze value-dependent comparisons directly.
10603   if (E->isValueDependent())
10604     return AnalyzeImpConvsInComparison(S, E);
10605 
10606   Expr *LHS = E->getLHS();
10607   Expr *RHS = E->getRHS();
10608 
10609   if (T->isIntegralType(S.Context)) {
10610     llvm::APSInt RHSValue;
10611     llvm::APSInt LHSValue;
10612 
10613     bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
10614     bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
10615 
10616     // We don't care about expressions whose result is a constant.
10617     if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
10618       return AnalyzeImpConvsInComparison(S, E);
10619 
10620     // We only care about expressions where just one side is literal
10621     if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
10622       // Is the constant on the RHS or LHS?
10623       const bool RhsConstant = IsRHSIntegralLiteral;
10624       Expr *Const = RhsConstant ? RHS : LHS;
10625       Expr *Other = RhsConstant ? LHS : RHS;
10626       const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
10627 
10628       // Check whether an integer constant comparison results in a value
10629       // of 'true' or 'false'.
10630       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
10631         return AnalyzeImpConvsInComparison(S, E);
10632     }
10633   }
10634 
10635   if (!T->hasUnsignedIntegerRepresentation()) {
10636     // We don't do anything special if this isn't an unsigned integral
10637     // comparison:  we're only interested in integral comparisons, and
10638     // signed comparisons only happen in cases we don't care to warn about.
10639     return AnalyzeImpConvsInComparison(S, E);
10640   }
10641 
10642   LHS = LHS->IgnoreParenImpCasts();
10643   RHS = RHS->IgnoreParenImpCasts();
10644 
10645   if (!S.getLangOpts().CPlusPlus) {
10646     // Avoid warning about comparison of integers with different signs when
10647     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
10648     // the type of `E`.
10649     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
10650       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10651     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
10652       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10653   }
10654 
10655   // Check to see if one of the (unmodified) operands is of different
10656   // signedness.
10657   Expr *signedOperand, *unsignedOperand;
10658   if (LHS->getType()->hasSignedIntegerRepresentation()) {
10659     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
10660            "unsigned comparison between two signed integer expressions?");
10661     signedOperand = LHS;
10662     unsignedOperand = RHS;
10663   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
10664     signedOperand = RHS;
10665     unsignedOperand = LHS;
10666   } else {
10667     return AnalyzeImpConvsInComparison(S, E);
10668   }
10669 
10670   // Otherwise, calculate the effective range of the signed operand.
10671   IntRange signedRange =
10672       GetExprRange(S.Context, signedOperand, S.isConstantEvaluated());
10673 
10674   // Go ahead and analyze implicit conversions in the operands.  Note
10675   // that we skip the implicit conversions on both sides.
10676   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
10677   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
10678 
10679   // If the signed range is non-negative, -Wsign-compare won't fire.
10680   if (signedRange.NonNegative)
10681     return;
10682 
10683   // For (in)equality comparisons, if the unsigned operand is a
10684   // constant which cannot collide with a overflowed signed operand,
10685   // then reinterpreting the signed operand as unsigned will not
10686   // change the result of the comparison.
10687   if (E->isEqualityOp()) {
10688     unsigned comparisonWidth = S.Context.getIntWidth(T);
10689     IntRange unsignedRange =
10690         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated());
10691 
10692     // We should never be unable to prove that the unsigned operand is
10693     // non-negative.
10694     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
10695 
10696     if (unsignedRange.Width < comparisonWidth)
10697       return;
10698   }
10699 
10700   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10701                         S.PDiag(diag::warn_mixed_sign_comparison)
10702                             << LHS->getType() << RHS->getType()
10703                             << LHS->getSourceRange() << RHS->getSourceRange());
10704 }
10705 
10706 /// Analyzes an attempt to assign the given value to a bitfield.
10707 ///
10708 /// Returns true if there was something fishy about the attempt.
10709 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
10710                                       SourceLocation InitLoc) {
10711   assert(Bitfield->isBitField());
10712   if (Bitfield->isInvalidDecl())
10713     return false;
10714 
10715   // White-list bool bitfields.
10716   QualType BitfieldType = Bitfield->getType();
10717   if (BitfieldType->isBooleanType())
10718      return false;
10719 
10720   if (BitfieldType->isEnumeralType()) {
10721     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
10722     // If the underlying enum type was not explicitly specified as an unsigned
10723     // type and the enum contain only positive values, MSVC++ will cause an
10724     // inconsistency by storing this as a signed type.
10725     if (S.getLangOpts().CPlusPlus11 &&
10726         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
10727         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
10728         BitfieldEnumDecl->getNumNegativeBits() == 0) {
10729       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
10730         << BitfieldEnumDecl->getNameAsString();
10731     }
10732   }
10733 
10734   if (Bitfield->getType()->isBooleanType())
10735     return false;
10736 
10737   // Ignore value- or type-dependent expressions.
10738   if (Bitfield->getBitWidth()->isValueDependent() ||
10739       Bitfield->getBitWidth()->isTypeDependent() ||
10740       Init->isValueDependent() ||
10741       Init->isTypeDependent())
10742     return false;
10743 
10744   Expr *OriginalInit = Init->IgnoreParenImpCasts();
10745   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
10746 
10747   Expr::EvalResult Result;
10748   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
10749                                    Expr::SE_AllowSideEffects)) {
10750     // The RHS is not constant.  If the RHS has an enum type, make sure the
10751     // bitfield is wide enough to hold all the values of the enum without
10752     // truncation.
10753     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
10754       EnumDecl *ED = EnumTy->getDecl();
10755       bool SignedBitfield = BitfieldType->isSignedIntegerType();
10756 
10757       // Enum types are implicitly signed on Windows, so check if there are any
10758       // negative enumerators to see if the enum was intended to be signed or
10759       // not.
10760       bool SignedEnum = ED->getNumNegativeBits() > 0;
10761 
10762       // Check for surprising sign changes when assigning enum values to a
10763       // bitfield of different signedness.  If the bitfield is signed and we
10764       // have exactly the right number of bits to store this unsigned enum,
10765       // suggest changing the enum to an unsigned type. This typically happens
10766       // on Windows where unfixed enums always use an underlying type of 'int'.
10767       unsigned DiagID = 0;
10768       if (SignedEnum && !SignedBitfield) {
10769         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
10770       } else if (SignedBitfield && !SignedEnum &&
10771                  ED->getNumPositiveBits() == FieldWidth) {
10772         DiagID = diag::warn_signed_bitfield_enum_conversion;
10773       }
10774 
10775       if (DiagID) {
10776         S.Diag(InitLoc, DiagID) << Bitfield << ED;
10777         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
10778         SourceRange TypeRange =
10779             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
10780         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
10781             << SignedEnum << TypeRange;
10782       }
10783 
10784       // Compute the required bitwidth. If the enum has negative values, we need
10785       // one more bit than the normal number of positive bits to represent the
10786       // sign bit.
10787       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
10788                                                   ED->getNumNegativeBits())
10789                                        : ED->getNumPositiveBits();
10790 
10791       // Check the bitwidth.
10792       if (BitsNeeded > FieldWidth) {
10793         Expr *WidthExpr = Bitfield->getBitWidth();
10794         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
10795             << Bitfield << ED;
10796         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
10797             << BitsNeeded << ED << WidthExpr->getSourceRange();
10798       }
10799     }
10800 
10801     return false;
10802   }
10803 
10804   llvm::APSInt Value = Result.Val.getInt();
10805 
10806   unsigned OriginalWidth = Value.getBitWidth();
10807 
10808   if (!Value.isSigned() || Value.isNegative())
10809     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
10810       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
10811         OriginalWidth = Value.getMinSignedBits();
10812 
10813   if (OriginalWidth <= FieldWidth)
10814     return false;
10815 
10816   // Compute the value which the bitfield will contain.
10817   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
10818   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
10819 
10820   // Check whether the stored value is equal to the original value.
10821   TruncatedValue = TruncatedValue.extend(OriginalWidth);
10822   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
10823     return false;
10824 
10825   // Special-case bitfields of width 1: booleans are naturally 0/1, and
10826   // therefore don't strictly fit into a signed bitfield of width 1.
10827   if (FieldWidth == 1 && Value == 1)
10828     return false;
10829 
10830   std::string PrettyValue = Value.toString(10);
10831   std::string PrettyTrunc = TruncatedValue.toString(10);
10832 
10833   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
10834     << PrettyValue << PrettyTrunc << OriginalInit->getType()
10835     << Init->getSourceRange();
10836 
10837   return true;
10838 }
10839 
10840 /// Analyze the given simple or compound assignment for warning-worthy
10841 /// operations.
10842 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
10843   // Just recurse on the LHS.
10844   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10845 
10846   // We want to recurse on the RHS as normal unless we're assigning to
10847   // a bitfield.
10848   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
10849     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
10850                                   E->getOperatorLoc())) {
10851       // Recurse, ignoring any implicit conversions on the RHS.
10852       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
10853                                         E->getOperatorLoc());
10854     }
10855   }
10856 
10857   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10858 
10859   // Diagnose implicitly sequentially-consistent atomic assignment.
10860   if (E->getLHS()->getType()->isAtomicType())
10861     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
10862 }
10863 
10864 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
10865 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
10866                             SourceLocation CContext, unsigned diag,
10867                             bool pruneControlFlow = false) {
10868   if (pruneControlFlow) {
10869     S.DiagRuntimeBehavior(E->getExprLoc(), E,
10870                           S.PDiag(diag)
10871                               << SourceType << T << E->getSourceRange()
10872                               << SourceRange(CContext));
10873     return;
10874   }
10875   S.Diag(E->getExprLoc(), diag)
10876     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
10877 }
10878 
10879 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
10880 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
10881                             SourceLocation CContext,
10882                             unsigned diag, bool pruneControlFlow = false) {
10883   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
10884 }
10885 
10886 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
10887   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
10888       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
10889 }
10890 
10891 static void adornObjCBoolConversionDiagWithTernaryFixit(
10892     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
10893   Expr *Ignored = SourceExpr->IgnoreImplicit();
10894   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
10895     Ignored = OVE->getSourceExpr();
10896   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
10897                      isa<BinaryOperator>(Ignored) ||
10898                      isa<CXXOperatorCallExpr>(Ignored);
10899   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
10900   if (NeedsParens)
10901     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
10902             << FixItHint::CreateInsertion(EndLoc, ")");
10903   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
10904 }
10905 
10906 /// Diagnose an implicit cast from a floating point value to an integer value.
10907 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
10908                                     SourceLocation CContext) {
10909   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
10910   const bool PruneWarnings = S.inTemplateInstantiation();
10911 
10912   Expr *InnerE = E->IgnoreParenImpCasts();
10913   // We also want to warn on, e.g., "int i = -1.234"
10914   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
10915     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
10916       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
10917 
10918   const bool IsLiteral =
10919       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
10920 
10921   llvm::APFloat Value(0.0);
10922   bool IsConstant =
10923     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
10924   if (!IsConstant) {
10925     if (isObjCSignedCharBool(S, T)) {
10926       return adornObjCBoolConversionDiagWithTernaryFixit(
10927           S, E,
10928           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
10929               << E->getType());
10930     }
10931 
10932     return DiagnoseImpCast(S, E, T, CContext,
10933                            diag::warn_impcast_float_integer, PruneWarnings);
10934   }
10935 
10936   bool isExact = false;
10937 
10938   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
10939                             T->hasUnsignedIntegerRepresentation());
10940   llvm::APFloat::opStatus Result = Value.convertToInteger(
10941       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
10942 
10943   // FIXME: Force the precision of the source value down so we don't print
10944   // digits which are usually useless (we don't really care here if we
10945   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
10946   // would automatically print the shortest representation, but it's a bit
10947   // tricky to implement.
10948   SmallString<16> PrettySourceValue;
10949   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
10950   precision = (precision * 59 + 195) / 196;
10951   Value.toString(PrettySourceValue, precision);
10952 
10953   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
10954     return adornObjCBoolConversionDiagWithTernaryFixit(
10955         S, E,
10956         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
10957             << PrettySourceValue);
10958   }
10959 
10960   if (Result == llvm::APFloat::opOK && isExact) {
10961     if (IsLiteral) return;
10962     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
10963                            PruneWarnings);
10964   }
10965 
10966   // Conversion of a floating-point value to a non-bool integer where the
10967   // integral part cannot be represented by the integer type is undefined.
10968   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
10969     return DiagnoseImpCast(
10970         S, E, T, CContext,
10971         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
10972                   : diag::warn_impcast_float_to_integer_out_of_range,
10973         PruneWarnings);
10974 
10975   unsigned DiagID = 0;
10976   if (IsLiteral) {
10977     // Warn on floating point literal to integer.
10978     DiagID = diag::warn_impcast_literal_float_to_integer;
10979   } else if (IntegerValue == 0) {
10980     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
10981       return DiagnoseImpCast(S, E, T, CContext,
10982                              diag::warn_impcast_float_integer, PruneWarnings);
10983     }
10984     // Warn on non-zero to zero conversion.
10985     DiagID = diag::warn_impcast_float_to_integer_zero;
10986   } else {
10987     if (IntegerValue.isUnsigned()) {
10988       if (!IntegerValue.isMaxValue()) {
10989         return DiagnoseImpCast(S, E, T, CContext,
10990                                diag::warn_impcast_float_integer, PruneWarnings);
10991       }
10992     } else {  // IntegerValue.isSigned()
10993       if (!IntegerValue.isMaxSignedValue() &&
10994           !IntegerValue.isMinSignedValue()) {
10995         return DiagnoseImpCast(S, E, T, CContext,
10996                                diag::warn_impcast_float_integer, PruneWarnings);
10997       }
10998     }
10999     // Warn on evaluatable floating point expression to integer conversion.
11000     DiagID = diag::warn_impcast_float_to_integer;
11001   }
11002 
11003   SmallString<16> PrettyTargetValue;
11004   if (IsBool)
11005     PrettyTargetValue = Value.isZero() ? "false" : "true";
11006   else
11007     IntegerValue.toString(PrettyTargetValue);
11008 
11009   if (PruneWarnings) {
11010     S.DiagRuntimeBehavior(E->getExprLoc(), E,
11011                           S.PDiag(DiagID)
11012                               << E->getType() << T.getUnqualifiedType()
11013                               << PrettySourceValue << PrettyTargetValue
11014                               << E->getSourceRange() << SourceRange(CContext));
11015   } else {
11016     S.Diag(E->getExprLoc(), DiagID)
11017         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
11018         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
11019   }
11020 }
11021 
11022 /// Analyze the given compound assignment for the possible losing of
11023 /// floating-point precision.
11024 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
11025   assert(isa<CompoundAssignOperator>(E) &&
11026          "Must be compound assignment operation");
11027   // Recurse on the LHS and RHS in here
11028   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11029   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11030 
11031   if (E->getLHS()->getType()->isAtomicType())
11032     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
11033 
11034   // Now check the outermost expression
11035   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
11036   const auto *RBT = cast<CompoundAssignOperator>(E)
11037                         ->getComputationResultType()
11038                         ->getAs<BuiltinType>();
11039 
11040   // The below checks assume source is floating point.
11041   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
11042 
11043   // If source is floating point but target is an integer.
11044   if (ResultBT->isInteger())
11045     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
11046                            E->getExprLoc(), diag::warn_impcast_float_integer);
11047 
11048   if (!ResultBT->isFloatingPoint())
11049     return;
11050 
11051   // If both source and target are floating points, warn about losing precision.
11052   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11053       QualType(ResultBT, 0), QualType(RBT, 0));
11054   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
11055     // warn about dropping FP rank.
11056     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
11057                     diag::warn_impcast_float_result_precision);
11058 }
11059 
11060 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
11061                                       IntRange Range) {
11062   if (!Range.Width) return "0";
11063 
11064   llvm::APSInt ValueInRange = Value;
11065   ValueInRange.setIsSigned(!Range.NonNegative);
11066   ValueInRange = ValueInRange.trunc(Range.Width);
11067   return ValueInRange.toString(10);
11068 }
11069 
11070 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
11071   if (!isa<ImplicitCastExpr>(Ex))
11072     return false;
11073 
11074   Expr *InnerE = Ex->IgnoreParenImpCasts();
11075   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
11076   const Type *Source =
11077     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
11078   if (Target->isDependentType())
11079     return false;
11080 
11081   const BuiltinType *FloatCandidateBT =
11082     dyn_cast<BuiltinType>(ToBool ? Source : Target);
11083   const Type *BoolCandidateType = ToBool ? Target : Source;
11084 
11085   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
11086           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
11087 }
11088 
11089 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
11090                                              SourceLocation CC) {
11091   unsigned NumArgs = TheCall->getNumArgs();
11092   for (unsigned i = 0; i < NumArgs; ++i) {
11093     Expr *CurrA = TheCall->getArg(i);
11094     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
11095       continue;
11096 
11097     bool IsSwapped = ((i > 0) &&
11098         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
11099     IsSwapped |= ((i < (NumArgs - 1)) &&
11100         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
11101     if (IsSwapped) {
11102       // Warn on this floating-point to bool conversion.
11103       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
11104                       CurrA->getType(), CC,
11105                       diag::warn_impcast_floating_point_to_bool);
11106     }
11107   }
11108 }
11109 
11110 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
11111                                    SourceLocation CC) {
11112   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
11113                         E->getExprLoc()))
11114     return;
11115 
11116   // Don't warn on functions which have return type nullptr_t.
11117   if (isa<CallExpr>(E))
11118     return;
11119 
11120   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
11121   const Expr::NullPointerConstantKind NullKind =
11122       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
11123   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
11124     return;
11125 
11126   // Return if target type is a safe conversion.
11127   if (T->isAnyPointerType() || T->isBlockPointerType() ||
11128       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
11129     return;
11130 
11131   SourceLocation Loc = E->getSourceRange().getBegin();
11132 
11133   // Venture through the macro stacks to get to the source of macro arguments.
11134   // The new location is a better location than the complete location that was
11135   // passed in.
11136   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
11137   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
11138 
11139   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
11140   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
11141     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
11142         Loc, S.SourceMgr, S.getLangOpts());
11143     if (MacroName == "NULL")
11144       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
11145   }
11146 
11147   // Only warn if the null and context location are in the same macro expansion.
11148   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
11149     return;
11150 
11151   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
11152       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
11153       << FixItHint::CreateReplacement(Loc,
11154                                       S.getFixItZeroLiteralForType(T, Loc));
11155 }
11156 
11157 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11158                                   ObjCArrayLiteral *ArrayLiteral);
11159 
11160 static void
11161 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11162                            ObjCDictionaryLiteral *DictionaryLiteral);
11163 
11164 /// Check a single element within a collection literal against the
11165 /// target element type.
11166 static void checkObjCCollectionLiteralElement(Sema &S,
11167                                               QualType TargetElementType,
11168                                               Expr *Element,
11169                                               unsigned ElementKind) {
11170   // Skip a bitcast to 'id' or qualified 'id'.
11171   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
11172     if (ICE->getCastKind() == CK_BitCast &&
11173         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
11174       Element = ICE->getSubExpr();
11175   }
11176 
11177   QualType ElementType = Element->getType();
11178   ExprResult ElementResult(Element);
11179   if (ElementType->getAs<ObjCObjectPointerType>() &&
11180       S.CheckSingleAssignmentConstraints(TargetElementType,
11181                                          ElementResult,
11182                                          false, false)
11183         != Sema::Compatible) {
11184     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
11185         << ElementType << ElementKind << TargetElementType
11186         << Element->getSourceRange();
11187   }
11188 
11189   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
11190     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
11191   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
11192     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
11193 }
11194 
11195 /// Check an Objective-C array literal being converted to the given
11196 /// target type.
11197 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11198                                   ObjCArrayLiteral *ArrayLiteral) {
11199   if (!S.NSArrayDecl)
11200     return;
11201 
11202   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11203   if (!TargetObjCPtr)
11204     return;
11205 
11206   if (TargetObjCPtr->isUnspecialized() ||
11207       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11208         != S.NSArrayDecl->getCanonicalDecl())
11209     return;
11210 
11211   auto TypeArgs = TargetObjCPtr->getTypeArgs();
11212   if (TypeArgs.size() != 1)
11213     return;
11214 
11215   QualType TargetElementType = TypeArgs[0];
11216   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
11217     checkObjCCollectionLiteralElement(S, TargetElementType,
11218                                       ArrayLiteral->getElement(I),
11219                                       0);
11220   }
11221 }
11222 
11223 /// Check an Objective-C dictionary literal being converted to the given
11224 /// target type.
11225 static void
11226 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11227                            ObjCDictionaryLiteral *DictionaryLiteral) {
11228   if (!S.NSDictionaryDecl)
11229     return;
11230 
11231   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11232   if (!TargetObjCPtr)
11233     return;
11234 
11235   if (TargetObjCPtr->isUnspecialized() ||
11236       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11237         != S.NSDictionaryDecl->getCanonicalDecl())
11238     return;
11239 
11240   auto TypeArgs = TargetObjCPtr->getTypeArgs();
11241   if (TypeArgs.size() != 2)
11242     return;
11243 
11244   QualType TargetKeyType = TypeArgs[0];
11245   QualType TargetObjectType = TypeArgs[1];
11246   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
11247     auto Element = DictionaryLiteral->getKeyValueElement(I);
11248     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
11249     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
11250   }
11251 }
11252 
11253 // Helper function to filter out cases for constant width constant conversion.
11254 // Don't warn on char array initialization or for non-decimal values.
11255 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
11256                                           SourceLocation CC) {
11257   // If initializing from a constant, and the constant starts with '0',
11258   // then it is a binary, octal, or hexadecimal.  Allow these constants
11259   // to fill all the bits, even if there is a sign change.
11260   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
11261     const char FirstLiteralCharacter =
11262         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
11263     if (FirstLiteralCharacter == '0')
11264       return false;
11265   }
11266 
11267   // If the CC location points to a '{', and the type is char, then assume
11268   // assume it is an array initialization.
11269   if (CC.isValid() && T->isCharType()) {
11270     const char FirstContextCharacter =
11271         S.getSourceManager().getCharacterData(CC)[0];
11272     if (FirstContextCharacter == '{')
11273       return false;
11274   }
11275 
11276   return true;
11277 }
11278 
11279 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
11280   const auto *IL = dyn_cast<IntegerLiteral>(E);
11281   if (!IL) {
11282     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
11283       if (UO->getOpcode() == UO_Minus)
11284         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
11285     }
11286   }
11287 
11288   return IL;
11289 }
11290 
11291 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
11292   E = E->IgnoreParenImpCasts();
11293   SourceLocation ExprLoc = E->getExprLoc();
11294 
11295   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11296     BinaryOperator::Opcode Opc = BO->getOpcode();
11297     Expr::EvalResult Result;
11298     // Do not diagnose unsigned shifts.
11299     if (Opc == BO_Shl) {
11300       const auto *LHS = getIntegerLiteral(BO->getLHS());
11301       const auto *RHS = getIntegerLiteral(BO->getRHS());
11302       if (LHS && LHS->getValue() == 0)
11303         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
11304       else if (!E->isValueDependent() && LHS && RHS &&
11305                RHS->getValue().isNonNegative() &&
11306                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
11307         S.Diag(ExprLoc, diag::warn_left_shift_always)
11308             << (Result.Val.getInt() != 0);
11309       else if (E->getType()->isSignedIntegerType())
11310         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
11311     }
11312   }
11313 
11314   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11315     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
11316     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
11317     if (!LHS || !RHS)
11318       return;
11319     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
11320         (RHS->getValue() == 0 || RHS->getValue() == 1))
11321       // Do not diagnose common idioms.
11322       return;
11323     if (LHS->getValue() != 0 && RHS->getValue() != 0)
11324       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
11325   }
11326 }
11327 
11328 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
11329                                     SourceLocation CC,
11330                                     bool *ICContext = nullptr,
11331                                     bool IsListInit = false) {
11332   if (E->isTypeDependent() || E->isValueDependent()) return;
11333 
11334   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
11335   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
11336   if (Source == Target) return;
11337   if (Target->isDependentType()) return;
11338 
11339   // If the conversion context location is invalid don't complain. We also
11340   // don't want to emit a warning if the issue occurs from the expansion of
11341   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
11342   // delay this check as long as possible. Once we detect we are in that
11343   // scenario, we just return.
11344   if (CC.isInvalid())
11345     return;
11346 
11347   if (Source->isAtomicType())
11348     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
11349 
11350   // Diagnose implicit casts to bool.
11351   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
11352     if (isa<StringLiteral>(E))
11353       // Warn on string literal to bool.  Checks for string literals in logical
11354       // and expressions, for instance, assert(0 && "error here"), are
11355       // prevented by a check in AnalyzeImplicitConversions().
11356       return DiagnoseImpCast(S, E, T, CC,
11357                              diag::warn_impcast_string_literal_to_bool);
11358     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
11359         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
11360       // This covers the literal expressions that evaluate to Objective-C
11361       // objects.
11362       return DiagnoseImpCast(S, E, T, CC,
11363                              diag::warn_impcast_objective_c_literal_to_bool);
11364     }
11365     if (Source->isPointerType() || Source->canDecayToPointerType()) {
11366       // Warn on pointer to bool conversion that is always true.
11367       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
11368                                      SourceRange(CC));
11369     }
11370   }
11371 
11372   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
11373   // is a typedef for signed char (macOS), then that constant value has to be 1
11374   // or 0.
11375   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
11376     Expr::EvalResult Result;
11377     if (E->EvaluateAsInt(Result, S.getASTContext(),
11378                          Expr::SE_AllowSideEffects)) {
11379       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
11380         adornObjCBoolConversionDiagWithTernaryFixit(
11381             S, E,
11382             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
11383                 << Result.Val.getInt().toString(10));
11384       }
11385       return;
11386     }
11387   }
11388 
11389   // Check implicit casts from Objective-C collection literals to specialized
11390   // collection types, e.g., NSArray<NSString *> *.
11391   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
11392     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
11393   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
11394     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
11395 
11396   // Strip vector types.
11397   if (isa<VectorType>(Source)) {
11398     if (!isa<VectorType>(Target)) {
11399       if (S.SourceMgr.isInSystemMacro(CC))
11400         return;
11401       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
11402     }
11403 
11404     // If the vector cast is cast between two vectors of the same size, it is
11405     // a bitcast, not a conversion.
11406     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
11407       return;
11408 
11409     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
11410     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
11411   }
11412   if (auto VecTy = dyn_cast<VectorType>(Target))
11413     Target = VecTy->getElementType().getTypePtr();
11414 
11415   // Strip complex types.
11416   if (isa<ComplexType>(Source)) {
11417     if (!isa<ComplexType>(Target)) {
11418       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
11419         return;
11420 
11421       return DiagnoseImpCast(S, E, T, CC,
11422                              S.getLangOpts().CPlusPlus
11423                                  ? diag::err_impcast_complex_scalar
11424                                  : diag::warn_impcast_complex_scalar);
11425     }
11426 
11427     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
11428     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
11429   }
11430 
11431   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
11432   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
11433 
11434   // If the source is floating point...
11435   if (SourceBT && SourceBT->isFloatingPoint()) {
11436     // ...and the target is floating point...
11437     if (TargetBT && TargetBT->isFloatingPoint()) {
11438       // ...then warn if we're dropping FP rank.
11439 
11440       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11441           QualType(SourceBT, 0), QualType(TargetBT, 0));
11442       if (Order > 0) {
11443         // Don't warn about float constants that are precisely
11444         // representable in the target type.
11445         Expr::EvalResult result;
11446         if (E->EvaluateAsRValue(result, S.Context)) {
11447           // Value might be a float, a float vector, or a float complex.
11448           if (IsSameFloatAfterCast(result.Val,
11449                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
11450                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
11451             return;
11452         }
11453 
11454         if (S.SourceMgr.isInSystemMacro(CC))
11455           return;
11456 
11457         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
11458       }
11459       // ... or possibly if we're increasing rank, too
11460       else if (Order < 0) {
11461         if (S.SourceMgr.isInSystemMacro(CC))
11462           return;
11463 
11464         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
11465       }
11466       return;
11467     }
11468 
11469     // If the target is integral, always warn.
11470     if (TargetBT && TargetBT->isInteger()) {
11471       if (S.SourceMgr.isInSystemMacro(CC))
11472         return;
11473 
11474       DiagnoseFloatingImpCast(S, E, T, CC);
11475     }
11476 
11477     // Detect the case where a call result is converted from floating-point to
11478     // to bool, and the final argument to the call is converted from bool, to
11479     // discover this typo:
11480     //
11481     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
11482     //
11483     // FIXME: This is an incredibly special case; is there some more general
11484     // way to detect this class of misplaced-parentheses bug?
11485     if (Target->isBooleanType() && isa<CallExpr>(E)) {
11486       // Check last argument of function call to see if it is an
11487       // implicit cast from a type matching the type the result
11488       // is being cast to.
11489       CallExpr *CEx = cast<CallExpr>(E);
11490       if (unsigned NumArgs = CEx->getNumArgs()) {
11491         Expr *LastA = CEx->getArg(NumArgs - 1);
11492         Expr *InnerE = LastA->IgnoreParenImpCasts();
11493         if (isa<ImplicitCastExpr>(LastA) &&
11494             InnerE->getType()->isBooleanType()) {
11495           // Warn on this floating-point to bool conversion
11496           DiagnoseImpCast(S, E, T, CC,
11497                           diag::warn_impcast_floating_point_to_bool);
11498         }
11499       }
11500     }
11501     return;
11502   }
11503 
11504   // Valid casts involving fixed point types should be accounted for here.
11505   if (Source->isFixedPointType()) {
11506     if (Target->isUnsaturatedFixedPointType()) {
11507       Expr::EvalResult Result;
11508       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
11509                                   S.isConstantEvaluated())) {
11510         APFixedPoint Value = Result.Val.getFixedPoint();
11511         APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
11512         APFixedPoint MinVal = S.Context.getFixedPointMin(T);
11513         if (Value > MaxVal || Value < MinVal) {
11514           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11515                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11516                                     << Value.toString() << T
11517                                     << E->getSourceRange()
11518                                     << clang::SourceRange(CC));
11519           return;
11520         }
11521       }
11522     } else if (Target->isIntegerType()) {
11523       Expr::EvalResult Result;
11524       if (!S.isConstantEvaluated() &&
11525           E->EvaluateAsFixedPoint(Result, S.Context,
11526                                   Expr::SE_AllowSideEffects)) {
11527         APFixedPoint FXResult = Result.Val.getFixedPoint();
11528 
11529         bool Overflowed;
11530         llvm::APSInt IntResult = FXResult.convertToInt(
11531             S.Context.getIntWidth(T),
11532             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
11533 
11534         if (Overflowed) {
11535           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11536                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11537                                     << FXResult.toString() << T
11538                                     << E->getSourceRange()
11539                                     << clang::SourceRange(CC));
11540           return;
11541         }
11542       }
11543     }
11544   } else if (Target->isUnsaturatedFixedPointType()) {
11545     if (Source->isIntegerType()) {
11546       Expr::EvalResult Result;
11547       if (!S.isConstantEvaluated() &&
11548           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
11549         llvm::APSInt Value = Result.Val.getInt();
11550 
11551         bool Overflowed;
11552         APFixedPoint IntResult = APFixedPoint::getFromIntValue(
11553             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
11554 
11555         if (Overflowed) {
11556           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11557                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11558                                     << Value.toString(/*Radix=*/10) << T
11559                                     << E->getSourceRange()
11560                                     << clang::SourceRange(CC));
11561           return;
11562         }
11563       }
11564     }
11565   }
11566 
11567   // If we are casting an integer type to a floating point type without
11568   // initialization-list syntax, we might lose accuracy if the floating
11569   // point type has a narrower significand than the integer type.
11570   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
11571       TargetBT->isFloatingType() && !IsListInit) {
11572     // Determine the number of precision bits in the source integer type.
11573     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated());
11574     unsigned int SourcePrecision = SourceRange.Width;
11575 
11576     // Determine the number of precision bits in the
11577     // target floating point type.
11578     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
11579         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
11580 
11581     if (SourcePrecision > 0 && TargetPrecision > 0 &&
11582         SourcePrecision > TargetPrecision) {
11583 
11584       llvm::APSInt SourceInt;
11585       if (E->isIntegerConstantExpr(SourceInt, S.Context)) {
11586         // If the source integer is a constant, convert it to the target
11587         // floating point type. Issue a warning if the value changes
11588         // during the whole conversion.
11589         llvm::APFloat TargetFloatValue(
11590             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
11591         llvm::APFloat::opStatus ConversionStatus =
11592             TargetFloatValue.convertFromAPInt(
11593                 SourceInt, SourceBT->isSignedInteger(),
11594                 llvm::APFloat::rmNearestTiesToEven);
11595 
11596         if (ConversionStatus != llvm::APFloat::opOK) {
11597           std::string PrettySourceValue = SourceInt.toString(10);
11598           SmallString<32> PrettyTargetValue;
11599           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
11600 
11601           S.DiagRuntimeBehavior(
11602               E->getExprLoc(), E,
11603               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
11604                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
11605                   << E->getSourceRange() << clang::SourceRange(CC));
11606         }
11607       } else {
11608         // Otherwise, the implicit conversion may lose precision.
11609         DiagnoseImpCast(S, E, T, CC,
11610                         diag::warn_impcast_integer_float_precision);
11611       }
11612     }
11613   }
11614 
11615   DiagnoseNullConversion(S, E, T, CC);
11616 
11617   S.DiscardMisalignedMemberAddress(Target, E);
11618 
11619   if (Target->isBooleanType())
11620     DiagnoseIntInBoolContext(S, E);
11621 
11622   if (!Source->isIntegerType() || !Target->isIntegerType())
11623     return;
11624 
11625   // TODO: remove this early return once the false positives for constant->bool
11626   // in templates, macros, etc, are reduced or removed.
11627   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
11628     return;
11629 
11630   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
11631       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
11632     return adornObjCBoolConversionDiagWithTernaryFixit(
11633         S, E,
11634         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
11635             << E->getType());
11636   }
11637 
11638   IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated());
11639   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
11640 
11641   if (SourceRange.Width > TargetRange.Width) {
11642     // If the source is a constant, use a default-on diagnostic.
11643     // TODO: this should happen for bitfield stores, too.
11644     Expr::EvalResult Result;
11645     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
11646                          S.isConstantEvaluated())) {
11647       llvm::APSInt Value(32);
11648       Value = Result.Val.getInt();
11649 
11650       if (S.SourceMgr.isInSystemMacro(CC))
11651         return;
11652 
11653       std::string PrettySourceValue = Value.toString(10);
11654       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11655 
11656       S.DiagRuntimeBehavior(
11657           E->getExprLoc(), E,
11658           S.PDiag(diag::warn_impcast_integer_precision_constant)
11659               << PrettySourceValue << PrettyTargetValue << E->getType() << T
11660               << E->getSourceRange() << clang::SourceRange(CC));
11661       return;
11662     }
11663 
11664     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
11665     if (S.SourceMgr.isInSystemMacro(CC))
11666       return;
11667 
11668     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
11669       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
11670                              /* pruneControlFlow */ true);
11671     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
11672   }
11673 
11674   if (TargetRange.Width > SourceRange.Width) {
11675     if (auto *UO = dyn_cast<UnaryOperator>(E))
11676       if (UO->getOpcode() == UO_Minus)
11677         if (Source->isUnsignedIntegerType()) {
11678           if (Target->isUnsignedIntegerType())
11679             return DiagnoseImpCast(S, E, T, CC,
11680                                    diag::warn_impcast_high_order_zero_bits);
11681           if (Target->isSignedIntegerType())
11682             return DiagnoseImpCast(S, E, T, CC,
11683                                    diag::warn_impcast_nonnegative_result);
11684         }
11685   }
11686 
11687   if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
11688       SourceRange.NonNegative && Source->isSignedIntegerType()) {
11689     // Warn when doing a signed to signed conversion, warn if the positive
11690     // source value is exactly the width of the target type, which will
11691     // cause a negative value to be stored.
11692 
11693     Expr::EvalResult Result;
11694     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
11695         !S.SourceMgr.isInSystemMacro(CC)) {
11696       llvm::APSInt Value = Result.Val.getInt();
11697       if (isSameWidthConstantConversion(S, E, T, CC)) {
11698         std::string PrettySourceValue = Value.toString(10);
11699         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11700 
11701         S.DiagRuntimeBehavior(
11702             E->getExprLoc(), E,
11703             S.PDiag(diag::warn_impcast_integer_precision_constant)
11704                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
11705                 << E->getSourceRange() << clang::SourceRange(CC));
11706         return;
11707       }
11708     }
11709 
11710     // Fall through for non-constants to give a sign conversion warning.
11711   }
11712 
11713   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
11714       (!TargetRange.NonNegative && SourceRange.NonNegative &&
11715        SourceRange.Width == TargetRange.Width)) {
11716     if (S.SourceMgr.isInSystemMacro(CC))
11717       return;
11718 
11719     unsigned DiagID = diag::warn_impcast_integer_sign;
11720 
11721     // Traditionally, gcc has warned about this under -Wsign-compare.
11722     // We also want to warn about it in -Wconversion.
11723     // So if -Wconversion is off, use a completely identical diagnostic
11724     // in the sign-compare group.
11725     // The conditional-checking code will
11726     if (ICContext) {
11727       DiagID = diag::warn_impcast_integer_sign_conditional;
11728       *ICContext = true;
11729     }
11730 
11731     return DiagnoseImpCast(S, E, T, CC, DiagID);
11732   }
11733 
11734   // Diagnose conversions between different enumeration types.
11735   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
11736   // type, to give us better diagnostics.
11737   QualType SourceType = E->getType();
11738   if (!S.getLangOpts().CPlusPlus) {
11739     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11740       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
11741         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
11742         SourceType = S.Context.getTypeDeclType(Enum);
11743         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
11744       }
11745   }
11746 
11747   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
11748     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
11749       if (SourceEnum->getDecl()->hasNameForLinkage() &&
11750           TargetEnum->getDecl()->hasNameForLinkage() &&
11751           SourceEnum != TargetEnum) {
11752         if (S.SourceMgr.isInSystemMacro(CC))
11753           return;
11754 
11755         return DiagnoseImpCast(S, E, SourceType, T, CC,
11756                                diag::warn_impcast_different_enum_types);
11757       }
11758 }
11759 
11760 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11761                                      SourceLocation CC, QualType T);
11762 
11763 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
11764                                     SourceLocation CC, bool &ICContext) {
11765   E = E->IgnoreParenImpCasts();
11766 
11767   if (isa<ConditionalOperator>(E))
11768     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
11769 
11770   AnalyzeImplicitConversions(S, E, CC);
11771   if (E->getType() != T)
11772     return CheckImplicitConversion(S, E, T, CC, &ICContext);
11773 }
11774 
11775 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11776                                      SourceLocation CC, QualType T) {
11777   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
11778 
11779   bool Suspicious = false;
11780   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
11781   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
11782 
11783   if (T->isBooleanType())
11784     DiagnoseIntInBoolContext(S, E);
11785 
11786   // If -Wconversion would have warned about either of the candidates
11787   // for a signedness conversion to the context type...
11788   if (!Suspicious) return;
11789 
11790   // ...but it's currently ignored...
11791   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
11792     return;
11793 
11794   // ...then check whether it would have warned about either of the
11795   // candidates for a signedness conversion to the condition type.
11796   if (E->getType() == T) return;
11797 
11798   Suspicious = false;
11799   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
11800                           E->getType(), CC, &Suspicious);
11801   if (!Suspicious)
11802     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
11803                             E->getType(), CC, &Suspicious);
11804 }
11805 
11806 /// Check conversion of given expression to boolean.
11807 /// Input argument E is a logical expression.
11808 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
11809   if (S.getLangOpts().Bool)
11810     return;
11811   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
11812     return;
11813   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
11814 }
11815 
11816 namespace {
11817 struct AnalyzeImplicitConversionsWorkItem {
11818   Expr *E;
11819   SourceLocation CC;
11820   bool IsListInit;
11821 };
11822 }
11823 
11824 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
11825 /// that should be visited are added to WorkList.
11826 static void AnalyzeImplicitConversions(
11827     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
11828     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
11829   Expr *OrigE = Item.E;
11830   SourceLocation CC = Item.CC;
11831 
11832   QualType T = OrigE->getType();
11833   Expr *E = OrigE->IgnoreParenImpCasts();
11834 
11835   // Propagate whether we are in a C++ list initialization expression.
11836   // If so, we do not issue warnings for implicit int-float conversion
11837   // precision loss, because C++11 narrowing already handles it.
11838   bool IsListInit = Item.IsListInit ||
11839                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
11840 
11841   if (E->isTypeDependent() || E->isValueDependent())
11842     return;
11843 
11844   Expr *SourceExpr = E;
11845   // Examine, but don't traverse into the source expression of an
11846   // OpaqueValueExpr, since it may have multiple parents and we don't want to
11847   // emit duplicate diagnostics. Its fine to examine the form or attempt to
11848   // evaluate it in the context of checking the specific conversion to T though.
11849   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11850     if (auto *Src = OVE->getSourceExpr())
11851       SourceExpr = Src;
11852 
11853   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
11854     if (UO->getOpcode() == UO_Not &&
11855         UO->getSubExpr()->isKnownToHaveBooleanValue())
11856       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
11857           << OrigE->getSourceRange() << T->isBooleanType()
11858           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
11859 
11860   // For conditional operators, we analyze the arguments as if they
11861   // were being fed directly into the output.
11862   if (auto *CO = dyn_cast<ConditionalOperator>(SourceExpr)) {
11863     CheckConditionalOperator(S, CO, CC, T);
11864     return;
11865   }
11866 
11867   // Check implicit argument conversions for function calls.
11868   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
11869     CheckImplicitArgumentConversions(S, Call, CC);
11870 
11871   // Go ahead and check any implicit conversions we might have skipped.
11872   // The non-canonical typecheck is just an optimization;
11873   // CheckImplicitConversion will filter out dead implicit conversions.
11874   if (SourceExpr->getType() != T)
11875     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
11876 
11877   // Now continue drilling into this expression.
11878 
11879   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
11880     // The bound subexpressions in a PseudoObjectExpr are not reachable
11881     // as transitive children.
11882     // FIXME: Use a more uniform representation for this.
11883     for (auto *SE : POE->semantics())
11884       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
11885         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
11886   }
11887 
11888   // Skip past explicit casts.
11889   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
11890     E = CE->getSubExpr()->IgnoreParenImpCasts();
11891     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
11892       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
11893     WorkList.push_back({E, CC, IsListInit});
11894     return;
11895   }
11896 
11897   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11898     // Do a somewhat different check with comparison operators.
11899     if (BO->isComparisonOp())
11900       return AnalyzeComparison(S, BO);
11901 
11902     // And with simple assignments.
11903     if (BO->getOpcode() == BO_Assign)
11904       return AnalyzeAssignment(S, BO);
11905     // And with compound assignments.
11906     if (BO->isAssignmentOp())
11907       return AnalyzeCompoundAssignment(S, BO);
11908   }
11909 
11910   // These break the otherwise-useful invariant below.  Fortunately,
11911   // we don't really need to recurse into them, because any internal
11912   // expressions should have been analyzed already when they were
11913   // built into statements.
11914   if (isa<StmtExpr>(E)) return;
11915 
11916   // Don't descend into unevaluated contexts.
11917   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
11918 
11919   // Now just recurse over the expression's children.
11920   CC = E->getExprLoc();
11921   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
11922   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
11923   for (Stmt *SubStmt : E->children()) {
11924     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
11925     if (!ChildExpr)
11926       continue;
11927 
11928     if (IsLogicalAndOperator &&
11929         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
11930       // Ignore checking string literals that are in logical and operators.
11931       // This is a common pattern for asserts.
11932       continue;
11933     WorkList.push_back({ChildExpr, CC, IsListInit});
11934   }
11935 
11936   if (BO && BO->isLogicalOp()) {
11937     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
11938     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
11939       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
11940 
11941     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
11942     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
11943       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
11944   }
11945 
11946   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
11947     if (U->getOpcode() == UO_LNot) {
11948       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
11949     } else if (U->getOpcode() != UO_AddrOf) {
11950       if (U->getSubExpr()->getType()->isAtomicType())
11951         S.Diag(U->getSubExpr()->getBeginLoc(),
11952                diag::warn_atomic_implicit_seq_cst);
11953     }
11954   }
11955 }
11956 
11957 /// AnalyzeImplicitConversions - Find and report any interesting
11958 /// implicit conversions in the given expression.  There are a couple
11959 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
11960 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
11961                                        bool IsListInit/*= false*/) {
11962   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
11963   WorkList.push_back({OrigE, CC, IsListInit});
11964   while (!WorkList.empty())
11965     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
11966 }
11967 
11968 /// Diagnose integer type and any valid implicit conversion to it.
11969 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
11970   // Taking into account implicit conversions,
11971   // allow any integer.
11972   if (!E->getType()->isIntegerType()) {
11973     S.Diag(E->getBeginLoc(),
11974            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
11975     return true;
11976   }
11977   // Potentially emit standard warnings for implicit conversions if enabled
11978   // using -Wconversion.
11979   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
11980   return false;
11981 }
11982 
11983 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
11984 // Returns true when emitting a warning about taking the address of a reference.
11985 static bool CheckForReference(Sema &SemaRef, const Expr *E,
11986                               const PartialDiagnostic &PD) {
11987   E = E->IgnoreParenImpCasts();
11988 
11989   const FunctionDecl *FD = nullptr;
11990 
11991   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11992     if (!DRE->getDecl()->getType()->isReferenceType())
11993       return false;
11994   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
11995     if (!M->getMemberDecl()->getType()->isReferenceType())
11996       return false;
11997   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
11998     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
11999       return false;
12000     FD = Call->getDirectCallee();
12001   } else {
12002     return false;
12003   }
12004 
12005   SemaRef.Diag(E->getExprLoc(), PD);
12006 
12007   // If possible, point to location of function.
12008   if (FD) {
12009     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
12010   }
12011 
12012   return true;
12013 }
12014 
12015 // Returns true if the SourceLocation is expanded from any macro body.
12016 // Returns false if the SourceLocation is invalid, is from not in a macro
12017 // expansion, or is from expanded from a top-level macro argument.
12018 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
12019   if (Loc.isInvalid())
12020     return false;
12021 
12022   while (Loc.isMacroID()) {
12023     if (SM.isMacroBodyExpansion(Loc))
12024       return true;
12025     Loc = SM.getImmediateMacroCallerLoc(Loc);
12026   }
12027 
12028   return false;
12029 }
12030 
12031 /// Diagnose pointers that are always non-null.
12032 /// \param E the expression containing the pointer
12033 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
12034 /// compared to a null pointer
12035 /// \param IsEqual True when the comparison is equal to a null pointer
12036 /// \param Range Extra SourceRange to highlight in the diagnostic
12037 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
12038                                         Expr::NullPointerConstantKind NullKind,
12039                                         bool IsEqual, SourceRange Range) {
12040   if (!E)
12041     return;
12042 
12043   // Don't warn inside macros.
12044   if (E->getExprLoc().isMacroID()) {
12045     const SourceManager &SM = getSourceManager();
12046     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
12047         IsInAnyMacroBody(SM, Range.getBegin()))
12048       return;
12049   }
12050   E = E->IgnoreImpCasts();
12051 
12052   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
12053 
12054   if (isa<CXXThisExpr>(E)) {
12055     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
12056                                 : diag::warn_this_bool_conversion;
12057     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
12058     return;
12059   }
12060 
12061   bool IsAddressOf = false;
12062 
12063   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12064     if (UO->getOpcode() != UO_AddrOf)
12065       return;
12066     IsAddressOf = true;
12067     E = UO->getSubExpr();
12068   }
12069 
12070   if (IsAddressOf) {
12071     unsigned DiagID = IsCompare
12072                           ? diag::warn_address_of_reference_null_compare
12073                           : diag::warn_address_of_reference_bool_conversion;
12074     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
12075                                          << IsEqual;
12076     if (CheckForReference(*this, E, PD)) {
12077       return;
12078     }
12079   }
12080 
12081   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
12082     bool IsParam = isa<NonNullAttr>(NonnullAttr);
12083     std::string Str;
12084     llvm::raw_string_ostream S(Str);
12085     E->printPretty(S, nullptr, getPrintingPolicy());
12086     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
12087                                 : diag::warn_cast_nonnull_to_bool;
12088     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
12089       << E->getSourceRange() << Range << IsEqual;
12090     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
12091   };
12092 
12093   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
12094   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
12095     if (auto *Callee = Call->getDirectCallee()) {
12096       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
12097         ComplainAboutNonnullParamOrCall(A);
12098         return;
12099       }
12100     }
12101   }
12102 
12103   // Expect to find a single Decl.  Skip anything more complicated.
12104   ValueDecl *D = nullptr;
12105   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
12106     D = R->getDecl();
12107   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12108     D = M->getMemberDecl();
12109   }
12110 
12111   // Weak Decls can be null.
12112   if (!D || D->isWeak())
12113     return;
12114 
12115   // Check for parameter decl with nonnull attribute
12116   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
12117     if (getCurFunction() &&
12118         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
12119       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
12120         ComplainAboutNonnullParamOrCall(A);
12121         return;
12122       }
12123 
12124       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
12125         // Skip function template not specialized yet.
12126         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
12127           return;
12128         auto ParamIter = llvm::find(FD->parameters(), PV);
12129         assert(ParamIter != FD->param_end());
12130         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
12131 
12132         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
12133           if (!NonNull->args_size()) {
12134               ComplainAboutNonnullParamOrCall(NonNull);
12135               return;
12136           }
12137 
12138           for (const ParamIdx &ArgNo : NonNull->args()) {
12139             if (ArgNo.getASTIndex() == ParamNo) {
12140               ComplainAboutNonnullParamOrCall(NonNull);
12141               return;
12142             }
12143           }
12144         }
12145       }
12146     }
12147   }
12148 
12149   QualType T = D->getType();
12150   const bool IsArray = T->isArrayType();
12151   const bool IsFunction = T->isFunctionType();
12152 
12153   // Address of function is used to silence the function warning.
12154   if (IsAddressOf && IsFunction) {
12155     return;
12156   }
12157 
12158   // Found nothing.
12159   if (!IsAddressOf && !IsFunction && !IsArray)
12160     return;
12161 
12162   // Pretty print the expression for the diagnostic.
12163   std::string Str;
12164   llvm::raw_string_ostream S(Str);
12165   E->printPretty(S, nullptr, getPrintingPolicy());
12166 
12167   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
12168                               : diag::warn_impcast_pointer_to_bool;
12169   enum {
12170     AddressOf,
12171     FunctionPointer,
12172     ArrayPointer
12173   } DiagType;
12174   if (IsAddressOf)
12175     DiagType = AddressOf;
12176   else if (IsFunction)
12177     DiagType = FunctionPointer;
12178   else if (IsArray)
12179     DiagType = ArrayPointer;
12180   else
12181     llvm_unreachable("Could not determine diagnostic.");
12182   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
12183                                 << Range << IsEqual;
12184 
12185   if (!IsFunction)
12186     return;
12187 
12188   // Suggest '&' to silence the function warning.
12189   Diag(E->getExprLoc(), diag::note_function_warning_silence)
12190       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
12191 
12192   // Check to see if '()' fixit should be emitted.
12193   QualType ReturnType;
12194   UnresolvedSet<4> NonTemplateOverloads;
12195   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
12196   if (ReturnType.isNull())
12197     return;
12198 
12199   if (IsCompare) {
12200     // There are two cases here.  If there is null constant, the only suggest
12201     // for a pointer return type.  If the null is 0, then suggest if the return
12202     // type is a pointer or an integer type.
12203     if (!ReturnType->isPointerType()) {
12204       if (NullKind == Expr::NPCK_ZeroExpression ||
12205           NullKind == Expr::NPCK_ZeroLiteral) {
12206         if (!ReturnType->isIntegerType())
12207           return;
12208       } else {
12209         return;
12210       }
12211     }
12212   } else { // !IsCompare
12213     // For function to bool, only suggest if the function pointer has bool
12214     // return type.
12215     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
12216       return;
12217   }
12218   Diag(E->getExprLoc(), diag::note_function_to_function_call)
12219       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
12220 }
12221 
12222 /// Diagnoses "dangerous" implicit conversions within the given
12223 /// expression (which is a full expression).  Implements -Wconversion
12224 /// and -Wsign-compare.
12225 ///
12226 /// \param CC the "context" location of the implicit conversion, i.e.
12227 ///   the most location of the syntactic entity requiring the implicit
12228 ///   conversion
12229 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
12230   // Don't diagnose in unevaluated contexts.
12231   if (isUnevaluatedContext())
12232     return;
12233 
12234   // Don't diagnose for value- or type-dependent expressions.
12235   if (E->isTypeDependent() || E->isValueDependent())
12236     return;
12237 
12238   // Check for array bounds violations in cases where the check isn't triggered
12239   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
12240   // ArraySubscriptExpr is on the RHS of a variable initialization.
12241   CheckArrayAccess(E);
12242 
12243   // This is not the right CC for (e.g.) a variable initialization.
12244   AnalyzeImplicitConversions(*this, E, CC);
12245 }
12246 
12247 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
12248 /// Input argument E is a logical expression.
12249 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
12250   ::CheckBoolLikeConversion(*this, E, CC);
12251 }
12252 
12253 /// Diagnose when expression is an integer constant expression and its evaluation
12254 /// results in integer overflow
12255 void Sema::CheckForIntOverflow (Expr *E) {
12256   // Use a work list to deal with nested struct initializers.
12257   SmallVector<Expr *, 2> Exprs(1, E);
12258 
12259   do {
12260     Expr *OriginalE = Exprs.pop_back_val();
12261     Expr *E = OriginalE->IgnoreParenCasts();
12262 
12263     if (isa<BinaryOperator>(E)) {
12264       E->EvaluateForOverflow(Context);
12265       continue;
12266     }
12267 
12268     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
12269       Exprs.append(InitList->inits().begin(), InitList->inits().end());
12270     else if (isa<ObjCBoxedExpr>(OriginalE))
12271       E->EvaluateForOverflow(Context);
12272     else if (auto Call = dyn_cast<CallExpr>(E))
12273       Exprs.append(Call->arg_begin(), Call->arg_end());
12274     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
12275       Exprs.append(Message->arg_begin(), Message->arg_end());
12276   } while (!Exprs.empty());
12277 }
12278 
12279 namespace {
12280 
12281 /// Visitor for expressions which looks for unsequenced operations on the
12282 /// same object.
12283 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
12284   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
12285 
12286   /// A tree of sequenced regions within an expression. Two regions are
12287   /// unsequenced if one is an ancestor or a descendent of the other. When we
12288   /// finish processing an expression with sequencing, such as a comma
12289   /// expression, we fold its tree nodes into its parent, since they are
12290   /// unsequenced with respect to nodes we will visit later.
12291   class SequenceTree {
12292     struct Value {
12293       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
12294       unsigned Parent : 31;
12295       unsigned Merged : 1;
12296     };
12297     SmallVector<Value, 8> Values;
12298 
12299   public:
12300     /// A region within an expression which may be sequenced with respect
12301     /// to some other region.
12302     class Seq {
12303       friend class SequenceTree;
12304 
12305       unsigned Index;
12306 
12307       explicit Seq(unsigned N) : Index(N) {}
12308 
12309     public:
12310       Seq() : Index(0) {}
12311     };
12312 
12313     SequenceTree() { Values.push_back(Value(0)); }
12314     Seq root() const { return Seq(0); }
12315 
12316     /// Create a new sequence of operations, which is an unsequenced
12317     /// subset of \p Parent. This sequence of operations is sequenced with
12318     /// respect to other children of \p Parent.
12319     Seq allocate(Seq Parent) {
12320       Values.push_back(Value(Parent.Index));
12321       return Seq(Values.size() - 1);
12322     }
12323 
12324     /// Merge a sequence of operations into its parent.
12325     void merge(Seq S) {
12326       Values[S.Index].Merged = true;
12327     }
12328 
12329     /// Determine whether two operations are unsequenced. This operation
12330     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
12331     /// should have been merged into its parent as appropriate.
12332     bool isUnsequenced(Seq Cur, Seq Old) {
12333       unsigned C = representative(Cur.Index);
12334       unsigned Target = representative(Old.Index);
12335       while (C >= Target) {
12336         if (C == Target)
12337           return true;
12338         C = Values[C].Parent;
12339       }
12340       return false;
12341     }
12342 
12343   private:
12344     /// Pick a representative for a sequence.
12345     unsigned representative(unsigned K) {
12346       if (Values[K].Merged)
12347         // Perform path compression as we go.
12348         return Values[K].Parent = representative(Values[K].Parent);
12349       return K;
12350     }
12351   };
12352 
12353   /// An object for which we can track unsequenced uses.
12354   using Object = const NamedDecl *;
12355 
12356   /// Different flavors of object usage which we track. We only track the
12357   /// least-sequenced usage of each kind.
12358   enum UsageKind {
12359     /// A read of an object. Multiple unsequenced reads are OK.
12360     UK_Use,
12361 
12362     /// A modification of an object which is sequenced before the value
12363     /// computation of the expression, such as ++n in C++.
12364     UK_ModAsValue,
12365 
12366     /// A modification of an object which is not sequenced before the value
12367     /// computation of the expression, such as n++.
12368     UK_ModAsSideEffect,
12369 
12370     UK_Count = UK_ModAsSideEffect + 1
12371   };
12372 
12373   /// Bundle together a sequencing region and the expression corresponding
12374   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
12375   struct Usage {
12376     const Expr *UsageExpr;
12377     SequenceTree::Seq Seq;
12378 
12379     Usage() : UsageExpr(nullptr), Seq() {}
12380   };
12381 
12382   struct UsageInfo {
12383     Usage Uses[UK_Count];
12384 
12385     /// Have we issued a diagnostic for this object already?
12386     bool Diagnosed;
12387 
12388     UsageInfo() : Uses(), Diagnosed(false) {}
12389   };
12390   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
12391 
12392   Sema &SemaRef;
12393 
12394   /// Sequenced regions within the expression.
12395   SequenceTree Tree;
12396 
12397   /// Declaration modifications and references which we have seen.
12398   UsageInfoMap UsageMap;
12399 
12400   /// The region we are currently within.
12401   SequenceTree::Seq Region;
12402 
12403   /// Filled in with declarations which were modified as a side-effect
12404   /// (that is, post-increment operations).
12405   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
12406 
12407   /// Expressions to check later. We defer checking these to reduce
12408   /// stack usage.
12409   SmallVectorImpl<const Expr *> &WorkList;
12410 
12411   /// RAII object wrapping the visitation of a sequenced subexpression of an
12412   /// expression. At the end of this process, the side-effects of the evaluation
12413   /// become sequenced with respect to the value computation of the result, so
12414   /// we downgrade any UK_ModAsSideEffect within the evaluation to
12415   /// UK_ModAsValue.
12416   struct SequencedSubexpression {
12417     SequencedSubexpression(SequenceChecker &Self)
12418       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
12419       Self.ModAsSideEffect = &ModAsSideEffect;
12420     }
12421 
12422     ~SequencedSubexpression() {
12423       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
12424         // Add a new usage with usage kind UK_ModAsValue, and then restore
12425         // the previous usage with UK_ModAsSideEffect (thus clearing it if
12426         // the previous one was empty).
12427         UsageInfo &UI = Self.UsageMap[M.first];
12428         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
12429         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
12430         SideEffectUsage = M.second;
12431       }
12432       Self.ModAsSideEffect = OldModAsSideEffect;
12433     }
12434 
12435     SequenceChecker &Self;
12436     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
12437     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
12438   };
12439 
12440   /// RAII object wrapping the visitation of a subexpression which we might
12441   /// choose to evaluate as a constant. If any subexpression is evaluated and
12442   /// found to be non-constant, this allows us to suppress the evaluation of
12443   /// the outer expression.
12444   class EvaluationTracker {
12445   public:
12446     EvaluationTracker(SequenceChecker &Self)
12447         : Self(Self), Prev(Self.EvalTracker) {
12448       Self.EvalTracker = this;
12449     }
12450 
12451     ~EvaluationTracker() {
12452       Self.EvalTracker = Prev;
12453       if (Prev)
12454         Prev->EvalOK &= EvalOK;
12455     }
12456 
12457     bool evaluate(const Expr *E, bool &Result) {
12458       if (!EvalOK || E->isValueDependent())
12459         return false;
12460       EvalOK = E->EvaluateAsBooleanCondition(
12461           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
12462       return EvalOK;
12463     }
12464 
12465   private:
12466     SequenceChecker &Self;
12467     EvaluationTracker *Prev;
12468     bool EvalOK = true;
12469   } *EvalTracker = nullptr;
12470 
12471   /// Find the object which is produced by the specified expression,
12472   /// if any.
12473   Object getObject(const Expr *E, bool Mod) const {
12474     E = E->IgnoreParenCasts();
12475     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12476       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
12477         return getObject(UO->getSubExpr(), Mod);
12478     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12479       if (BO->getOpcode() == BO_Comma)
12480         return getObject(BO->getRHS(), Mod);
12481       if (Mod && BO->isAssignmentOp())
12482         return getObject(BO->getLHS(), Mod);
12483     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12484       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
12485       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
12486         return ME->getMemberDecl();
12487     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12488       // FIXME: If this is a reference, map through to its value.
12489       return DRE->getDecl();
12490     return nullptr;
12491   }
12492 
12493   /// Note that an object \p O was modified or used by an expression
12494   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
12495   /// the object \p O as obtained via the \p UsageMap.
12496   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
12497     // Get the old usage for the given object and usage kind.
12498     Usage &U = UI.Uses[UK];
12499     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
12500       // If we have a modification as side effect and are in a sequenced
12501       // subexpression, save the old Usage so that we can restore it later
12502       // in SequencedSubexpression::~SequencedSubexpression.
12503       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
12504         ModAsSideEffect->push_back(std::make_pair(O, U));
12505       // Then record the new usage with the current sequencing region.
12506       U.UsageExpr = UsageExpr;
12507       U.Seq = Region;
12508     }
12509   }
12510 
12511   /// Check whether a modification or use of an object \p O in an expression
12512   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
12513   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
12514   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
12515   /// usage and false we are checking for a mod-use unsequenced usage.
12516   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
12517                   UsageKind OtherKind, bool IsModMod) {
12518     if (UI.Diagnosed)
12519       return;
12520 
12521     const Usage &U = UI.Uses[OtherKind];
12522     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
12523       return;
12524 
12525     const Expr *Mod = U.UsageExpr;
12526     const Expr *ModOrUse = UsageExpr;
12527     if (OtherKind == UK_Use)
12528       std::swap(Mod, ModOrUse);
12529 
12530     SemaRef.DiagRuntimeBehavior(
12531         Mod->getExprLoc(), {Mod, ModOrUse},
12532         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
12533                                : diag::warn_unsequenced_mod_use)
12534             << O << SourceRange(ModOrUse->getExprLoc()));
12535     UI.Diagnosed = true;
12536   }
12537 
12538   // A note on note{Pre, Post}{Use, Mod}:
12539   //
12540   // (It helps to follow the algorithm with an expression such as
12541   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
12542   //  operations before C++17 and both are well-defined in C++17).
12543   //
12544   // When visiting a node which uses/modify an object we first call notePreUse
12545   // or notePreMod before visiting its sub-expression(s). At this point the
12546   // children of the current node have not yet been visited and so the eventual
12547   // uses/modifications resulting from the children of the current node have not
12548   // been recorded yet.
12549   //
12550   // We then visit the children of the current node. After that notePostUse or
12551   // notePostMod is called. These will 1) detect an unsequenced modification
12552   // as side effect (as in "k++ + k") and 2) add a new usage with the
12553   // appropriate usage kind.
12554   //
12555   // We also have to be careful that some operation sequences modification as
12556   // side effect as well (for example: || or ,). To account for this we wrap
12557   // the visitation of such a sub-expression (for example: the LHS of || or ,)
12558   // with SequencedSubexpression. SequencedSubexpression is an RAII object
12559   // which record usages which are modifications as side effect, and then
12560   // downgrade them (or more accurately restore the previous usage which was a
12561   // modification as side effect) when exiting the scope of the sequenced
12562   // subexpression.
12563 
12564   void notePreUse(Object O, const Expr *UseExpr) {
12565     UsageInfo &UI = UsageMap[O];
12566     // Uses conflict with other modifications.
12567     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
12568   }
12569 
12570   void notePostUse(Object O, const Expr *UseExpr) {
12571     UsageInfo &UI = UsageMap[O];
12572     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
12573                /*IsModMod=*/false);
12574     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
12575   }
12576 
12577   void notePreMod(Object O, const Expr *ModExpr) {
12578     UsageInfo &UI = UsageMap[O];
12579     // Modifications conflict with other modifications and with uses.
12580     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
12581     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
12582   }
12583 
12584   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
12585     UsageInfo &UI = UsageMap[O];
12586     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
12587                /*IsModMod=*/true);
12588     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
12589   }
12590 
12591 public:
12592   SequenceChecker(Sema &S, const Expr *E,
12593                   SmallVectorImpl<const Expr *> &WorkList)
12594       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
12595     Visit(E);
12596     // Silence a -Wunused-private-field since WorkList is now unused.
12597     // TODO: Evaluate if it can be used, and if not remove it.
12598     (void)this->WorkList;
12599   }
12600 
12601   void VisitStmt(const Stmt *S) {
12602     // Skip all statements which aren't expressions for now.
12603   }
12604 
12605   void VisitExpr(const Expr *E) {
12606     // By default, just recurse to evaluated subexpressions.
12607     Base::VisitStmt(E);
12608   }
12609 
12610   void VisitCastExpr(const CastExpr *E) {
12611     Object O = Object();
12612     if (E->getCastKind() == CK_LValueToRValue)
12613       O = getObject(E->getSubExpr(), false);
12614 
12615     if (O)
12616       notePreUse(O, E);
12617     VisitExpr(E);
12618     if (O)
12619       notePostUse(O, E);
12620   }
12621 
12622   void VisitSequencedExpressions(const Expr *SequencedBefore,
12623                                  const Expr *SequencedAfter) {
12624     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
12625     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
12626     SequenceTree::Seq OldRegion = Region;
12627 
12628     {
12629       SequencedSubexpression SeqBefore(*this);
12630       Region = BeforeRegion;
12631       Visit(SequencedBefore);
12632     }
12633 
12634     Region = AfterRegion;
12635     Visit(SequencedAfter);
12636 
12637     Region = OldRegion;
12638 
12639     Tree.merge(BeforeRegion);
12640     Tree.merge(AfterRegion);
12641   }
12642 
12643   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
12644     // C++17 [expr.sub]p1:
12645     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
12646     //   expression E1 is sequenced before the expression E2.
12647     if (SemaRef.getLangOpts().CPlusPlus17)
12648       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
12649     else {
12650       Visit(ASE->getLHS());
12651       Visit(ASE->getRHS());
12652     }
12653   }
12654 
12655   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
12656   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
12657   void VisitBinPtrMem(const BinaryOperator *BO) {
12658     // C++17 [expr.mptr.oper]p4:
12659     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
12660     //  the expression E1 is sequenced before the expression E2.
12661     if (SemaRef.getLangOpts().CPlusPlus17)
12662       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12663     else {
12664       Visit(BO->getLHS());
12665       Visit(BO->getRHS());
12666     }
12667   }
12668 
12669   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
12670   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
12671   void VisitBinShlShr(const BinaryOperator *BO) {
12672     // C++17 [expr.shift]p4:
12673     //  The expression E1 is sequenced before the expression E2.
12674     if (SemaRef.getLangOpts().CPlusPlus17)
12675       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12676     else {
12677       Visit(BO->getLHS());
12678       Visit(BO->getRHS());
12679     }
12680   }
12681 
12682   void VisitBinComma(const BinaryOperator *BO) {
12683     // C++11 [expr.comma]p1:
12684     //   Every value computation and side effect associated with the left
12685     //   expression is sequenced before every value computation and side
12686     //   effect associated with the right expression.
12687     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12688   }
12689 
12690   void VisitBinAssign(const BinaryOperator *BO) {
12691     SequenceTree::Seq RHSRegion;
12692     SequenceTree::Seq LHSRegion;
12693     if (SemaRef.getLangOpts().CPlusPlus17) {
12694       RHSRegion = Tree.allocate(Region);
12695       LHSRegion = Tree.allocate(Region);
12696     } else {
12697       RHSRegion = Region;
12698       LHSRegion = Region;
12699     }
12700     SequenceTree::Seq OldRegion = Region;
12701 
12702     // C++11 [expr.ass]p1:
12703     //  [...] the assignment is sequenced after the value computation
12704     //  of the right and left operands, [...]
12705     //
12706     // so check it before inspecting the operands and update the
12707     // map afterwards.
12708     Object O = getObject(BO->getLHS(), /*Mod=*/true);
12709     if (O)
12710       notePreMod(O, BO);
12711 
12712     if (SemaRef.getLangOpts().CPlusPlus17) {
12713       // C++17 [expr.ass]p1:
12714       //  [...] The right operand is sequenced before the left operand. [...]
12715       {
12716         SequencedSubexpression SeqBefore(*this);
12717         Region = RHSRegion;
12718         Visit(BO->getRHS());
12719       }
12720 
12721       Region = LHSRegion;
12722       Visit(BO->getLHS());
12723 
12724       if (O && isa<CompoundAssignOperator>(BO))
12725         notePostUse(O, BO);
12726 
12727     } else {
12728       // C++11 does not specify any sequencing between the LHS and RHS.
12729       Region = LHSRegion;
12730       Visit(BO->getLHS());
12731 
12732       if (O && isa<CompoundAssignOperator>(BO))
12733         notePostUse(O, BO);
12734 
12735       Region = RHSRegion;
12736       Visit(BO->getRHS());
12737     }
12738 
12739     // C++11 [expr.ass]p1:
12740     //  the assignment is sequenced [...] before the value computation of the
12741     //  assignment expression.
12742     // C11 6.5.16/3 has no such rule.
12743     Region = OldRegion;
12744     if (O)
12745       notePostMod(O, BO,
12746                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12747                                                   : UK_ModAsSideEffect);
12748     if (SemaRef.getLangOpts().CPlusPlus17) {
12749       Tree.merge(RHSRegion);
12750       Tree.merge(LHSRegion);
12751     }
12752   }
12753 
12754   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
12755     VisitBinAssign(CAO);
12756   }
12757 
12758   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12759   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12760   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
12761     Object O = getObject(UO->getSubExpr(), true);
12762     if (!O)
12763       return VisitExpr(UO);
12764 
12765     notePreMod(O, UO);
12766     Visit(UO->getSubExpr());
12767     // C++11 [expr.pre.incr]p1:
12768     //   the expression ++x is equivalent to x+=1
12769     notePostMod(O, UO,
12770                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12771                                                 : UK_ModAsSideEffect);
12772   }
12773 
12774   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12775   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12776   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
12777     Object O = getObject(UO->getSubExpr(), true);
12778     if (!O)
12779       return VisitExpr(UO);
12780 
12781     notePreMod(O, UO);
12782     Visit(UO->getSubExpr());
12783     notePostMod(O, UO, UK_ModAsSideEffect);
12784   }
12785 
12786   void VisitBinLOr(const BinaryOperator *BO) {
12787     // C++11 [expr.log.or]p2:
12788     //  If the second expression is evaluated, every value computation and
12789     //  side effect associated with the first expression is sequenced before
12790     //  every value computation and side effect associated with the
12791     //  second expression.
12792     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
12793     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
12794     SequenceTree::Seq OldRegion = Region;
12795 
12796     EvaluationTracker Eval(*this);
12797     {
12798       SequencedSubexpression Sequenced(*this);
12799       Region = LHSRegion;
12800       Visit(BO->getLHS());
12801     }
12802 
12803     // C++11 [expr.log.or]p1:
12804     //  [...] the second operand is not evaluated if the first operand
12805     //  evaluates to true.
12806     bool EvalResult = false;
12807     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
12808     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
12809     if (ShouldVisitRHS) {
12810       Region = RHSRegion;
12811       Visit(BO->getRHS());
12812     }
12813 
12814     Region = OldRegion;
12815     Tree.merge(LHSRegion);
12816     Tree.merge(RHSRegion);
12817   }
12818 
12819   void VisitBinLAnd(const BinaryOperator *BO) {
12820     // C++11 [expr.log.and]p2:
12821     //  If the second expression is evaluated, every value computation and
12822     //  side effect associated with the first expression is sequenced before
12823     //  every value computation and side effect associated with the
12824     //  second expression.
12825     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
12826     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
12827     SequenceTree::Seq OldRegion = Region;
12828 
12829     EvaluationTracker Eval(*this);
12830     {
12831       SequencedSubexpression Sequenced(*this);
12832       Region = LHSRegion;
12833       Visit(BO->getLHS());
12834     }
12835 
12836     // C++11 [expr.log.and]p1:
12837     //  [...] the second operand is not evaluated if the first operand is false.
12838     bool EvalResult = false;
12839     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
12840     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
12841     if (ShouldVisitRHS) {
12842       Region = RHSRegion;
12843       Visit(BO->getRHS());
12844     }
12845 
12846     Region = OldRegion;
12847     Tree.merge(LHSRegion);
12848     Tree.merge(RHSRegion);
12849   }
12850 
12851   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
12852     // C++11 [expr.cond]p1:
12853     //  [...] Every value computation and side effect associated with the first
12854     //  expression is sequenced before every value computation and side effect
12855     //  associated with the second or third expression.
12856     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
12857 
12858     // No sequencing is specified between the true and false expression.
12859     // However since exactly one of both is going to be evaluated we can
12860     // consider them to be sequenced. This is needed to avoid warning on
12861     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
12862     // both the true and false expressions because we can't evaluate x.
12863     // This will still allow us to detect an expression like (pre C++17)
12864     // "(x ? y += 1 : y += 2) = y".
12865     //
12866     // We don't wrap the visitation of the true and false expression with
12867     // SequencedSubexpression because we don't want to downgrade modifications
12868     // as side effect in the true and false expressions after the visition
12869     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
12870     // not warn between the two "y++", but we should warn between the "y++"
12871     // and the "y".
12872     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
12873     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
12874     SequenceTree::Seq OldRegion = Region;
12875 
12876     EvaluationTracker Eval(*this);
12877     {
12878       SequencedSubexpression Sequenced(*this);
12879       Region = ConditionRegion;
12880       Visit(CO->getCond());
12881     }
12882 
12883     // C++11 [expr.cond]p1:
12884     // [...] The first expression is contextually converted to bool (Clause 4).
12885     // It is evaluated and if it is true, the result of the conditional
12886     // expression is the value of the second expression, otherwise that of the
12887     // third expression. Only one of the second and third expressions is
12888     // evaluated. [...]
12889     bool EvalResult = false;
12890     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
12891     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
12892     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
12893     if (ShouldVisitTrueExpr) {
12894       Region = TrueRegion;
12895       Visit(CO->getTrueExpr());
12896     }
12897     if (ShouldVisitFalseExpr) {
12898       Region = FalseRegion;
12899       Visit(CO->getFalseExpr());
12900     }
12901 
12902     Region = OldRegion;
12903     Tree.merge(ConditionRegion);
12904     Tree.merge(TrueRegion);
12905     Tree.merge(FalseRegion);
12906   }
12907 
12908   void VisitCallExpr(const CallExpr *CE) {
12909     // C++11 [intro.execution]p15:
12910     //   When calling a function [...], every value computation and side effect
12911     //   associated with any argument expression, or with the postfix expression
12912     //   designating the called function, is sequenced before execution of every
12913     //   expression or statement in the body of the function [and thus before
12914     //   the value computation of its result].
12915     SequencedSubexpression Sequenced(*this);
12916     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(),
12917                                         [&] { Base::VisitCallExpr(CE); });
12918 
12919     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
12920   }
12921 
12922   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
12923     // This is a call, so all subexpressions are sequenced before the result.
12924     SequencedSubexpression Sequenced(*this);
12925 
12926     if (!CCE->isListInitialization())
12927       return VisitExpr(CCE);
12928 
12929     // In C++11, list initializations are sequenced.
12930     SmallVector<SequenceTree::Seq, 32> Elts;
12931     SequenceTree::Seq Parent = Region;
12932     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
12933                                               E = CCE->arg_end();
12934          I != E; ++I) {
12935       Region = Tree.allocate(Parent);
12936       Elts.push_back(Region);
12937       Visit(*I);
12938     }
12939 
12940     // Forget that the initializers are sequenced.
12941     Region = Parent;
12942     for (unsigned I = 0; I < Elts.size(); ++I)
12943       Tree.merge(Elts[I]);
12944   }
12945 
12946   void VisitInitListExpr(const InitListExpr *ILE) {
12947     if (!SemaRef.getLangOpts().CPlusPlus11)
12948       return VisitExpr(ILE);
12949 
12950     // In C++11, list initializations are sequenced.
12951     SmallVector<SequenceTree::Seq, 32> Elts;
12952     SequenceTree::Seq Parent = Region;
12953     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
12954       const Expr *E = ILE->getInit(I);
12955       if (!E)
12956         continue;
12957       Region = Tree.allocate(Parent);
12958       Elts.push_back(Region);
12959       Visit(E);
12960     }
12961 
12962     // Forget that the initializers are sequenced.
12963     Region = Parent;
12964     for (unsigned I = 0; I < Elts.size(); ++I)
12965       Tree.merge(Elts[I]);
12966   }
12967 };
12968 
12969 } // namespace
12970 
12971 void Sema::CheckUnsequencedOperations(const Expr *E) {
12972   SmallVector<const Expr *, 8> WorkList;
12973   WorkList.push_back(E);
12974   while (!WorkList.empty()) {
12975     const Expr *Item = WorkList.pop_back_val();
12976     SequenceChecker(*this, Item, WorkList);
12977   }
12978 }
12979 
12980 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
12981                               bool IsConstexpr) {
12982   llvm::SaveAndRestore<bool> ConstantContext(
12983       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
12984   CheckImplicitConversions(E, CheckLoc);
12985   if (!E->isInstantiationDependent())
12986     CheckUnsequencedOperations(E);
12987   if (!IsConstexpr && !E->isValueDependent())
12988     CheckForIntOverflow(E);
12989   DiagnoseMisalignedMembers();
12990 }
12991 
12992 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
12993                                        FieldDecl *BitField,
12994                                        Expr *Init) {
12995   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
12996 }
12997 
12998 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
12999                                          SourceLocation Loc) {
13000   if (!PType->isVariablyModifiedType())
13001     return;
13002   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
13003     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
13004     return;
13005   }
13006   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
13007     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
13008     return;
13009   }
13010   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
13011     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
13012     return;
13013   }
13014 
13015   const ArrayType *AT = S.Context.getAsArrayType(PType);
13016   if (!AT)
13017     return;
13018 
13019   if (AT->getSizeModifier() != ArrayType::Star) {
13020     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
13021     return;
13022   }
13023 
13024   S.Diag(Loc, diag::err_array_star_in_function_definition);
13025 }
13026 
13027 /// CheckParmsForFunctionDef - Check that the parameters of the given
13028 /// function are appropriate for the definition of a function. This
13029 /// takes care of any checks that cannot be performed on the
13030 /// declaration itself, e.g., that the types of each of the function
13031 /// parameters are complete.
13032 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
13033                                     bool CheckParameterNames) {
13034   bool HasInvalidParm = false;
13035   for (ParmVarDecl *Param : Parameters) {
13036     // C99 6.7.5.3p4: the parameters in a parameter type list in a
13037     // function declarator that is part of a function definition of
13038     // that function shall not have incomplete type.
13039     //
13040     // This is also C++ [dcl.fct]p6.
13041     if (!Param->isInvalidDecl() &&
13042         RequireCompleteType(Param->getLocation(), Param->getType(),
13043                             diag::err_typecheck_decl_incomplete_type)) {
13044       Param->setInvalidDecl();
13045       HasInvalidParm = true;
13046     }
13047 
13048     // C99 6.9.1p5: If the declarator includes a parameter type list, the
13049     // declaration of each parameter shall include an identifier.
13050     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
13051         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
13052       // Diagnose this as an extension in C17 and earlier.
13053       if (!getLangOpts().C2x)
13054         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
13055     }
13056 
13057     // C99 6.7.5.3p12:
13058     //   If the function declarator is not part of a definition of that
13059     //   function, parameters may have incomplete type and may use the [*]
13060     //   notation in their sequences of declarator specifiers to specify
13061     //   variable length array types.
13062     QualType PType = Param->getOriginalType();
13063     // FIXME: This diagnostic should point the '[*]' if source-location
13064     // information is added for it.
13065     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
13066 
13067     // If the parameter is a c++ class type and it has to be destructed in the
13068     // callee function, declare the destructor so that it can be called by the
13069     // callee function. Do not perform any direct access check on the dtor here.
13070     if (!Param->isInvalidDecl()) {
13071       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
13072         if (!ClassDecl->isInvalidDecl() &&
13073             !ClassDecl->hasIrrelevantDestructor() &&
13074             !ClassDecl->isDependentContext() &&
13075             ClassDecl->isParamDestroyedInCallee()) {
13076           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
13077           MarkFunctionReferenced(Param->getLocation(), Destructor);
13078           DiagnoseUseOfDecl(Destructor, Param->getLocation());
13079         }
13080       }
13081     }
13082 
13083     // Parameters with the pass_object_size attribute only need to be marked
13084     // constant at function definitions. Because we lack information about
13085     // whether we're on a declaration or definition when we're instantiating the
13086     // attribute, we need to check for constness here.
13087     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
13088       if (!Param->getType().isConstQualified())
13089         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
13090             << Attr->getSpelling() << 1;
13091 
13092     // Check for parameter names shadowing fields from the class.
13093     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
13094       // The owning context for the parameter should be the function, but we
13095       // want to see if this function's declaration context is a record.
13096       DeclContext *DC = Param->getDeclContext();
13097       if (DC && DC->isFunctionOrMethod()) {
13098         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
13099           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
13100                                      RD, /*DeclIsField*/ false);
13101       }
13102     }
13103   }
13104 
13105   return HasInvalidParm;
13106 }
13107 
13108 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
13109 /// or MemberExpr.
13110 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
13111                               ASTContext &Context) {
13112   if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
13113     return Context.getDeclAlign(DRE->getDecl());
13114 
13115   if (const auto *ME = dyn_cast<MemberExpr>(E))
13116     return Context.getDeclAlign(ME->getMemberDecl());
13117 
13118   return TypeAlign;
13119 }
13120 
13121 /// CheckCastAlign - Implements -Wcast-align, which warns when a
13122 /// pointer cast increases the alignment requirements.
13123 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
13124   // This is actually a lot of work to potentially be doing on every
13125   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
13126   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
13127     return;
13128 
13129   // Ignore dependent types.
13130   if (T->isDependentType() || Op->getType()->isDependentType())
13131     return;
13132 
13133   // Require that the destination be a pointer type.
13134   const PointerType *DestPtr = T->getAs<PointerType>();
13135   if (!DestPtr) return;
13136 
13137   // If the destination has alignment 1, we're done.
13138   QualType DestPointee = DestPtr->getPointeeType();
13139   if (DestPointee->isIncompleteType()) return;
13140   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
13141   if (DestAlign.isOne()) return;
13142 
13143   // Require that the source be a pointer type.
13144   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
13145   if (!SrcPtr) return;
13146   QualType SrcPointee = SrcPtr->getPointeeType();
13147 
13148   // Whitelist casts from cv void*.  We already implicitly
13149   // whitelisted casts to cv void*, since they have alignment 1.
13150   // Also whitelist casts involving incomplete types, which implicitly
13151   // includes 'void'.
13152   if (SrcPointee->isIncompleteType()) return;
13153 
13154   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
13155 
13156   if (auto *CE = dyn_cast<CastExpr>(Op)) {
13157     if (CE->getCastKind() == CK_ArrayToPointerDecay)
13158       SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
13159   } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
13160     if (UO->getOpcode() == UO_AddrOf)
13161       SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
13162   }
13163 
13164   if (SrcAlign >= DestAlign) return;
13165 
13166   Diag(TRange.getBegin(), diag::warn_cast_align)
13167     << Op->getType() << T
13168     << static_cast<unsigned>(SrcAlign.getQuantity())
13169     << static_cast<unsigned>(DestAlign.getQuantity())
13170     << TRange << Op->getSourceRange();
13171 }
13172 
13173 /// Check whether this array fits the idiom of a size-one tail padded
13174 /// array member of a struct.
13175 ///
13176 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
13177 /// commonly used to emulate flexible arrays in C89 code.
13178 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
13179                                     const NamedDecl *ND) {
13180   if (Size != 1 || !ND) return false;
13181 
13182   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
13183   if (!FD) return false;
13184 
13185   // Don't consider sizes resulting from macro expansions or template argument
13186   // substitution to form C89 tail-padded arrays.
13187 
13188   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
13189   while (TInfo) {
13190     TypeLoc TL = TInfo->getTypeLoc();
13191     // Look through typedefs.
13192     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
13193       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
13194       TInfo = TDL->getTypeSourceInfo();
13195       continue;
13196     }
13197     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
13198       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
13199       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
13200         return false;
13201     }
13202     break;
13203   }
13204 
13205   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
13206   if (!RD) return false;
13207   if (RD->isUnion()) return false;
13208   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
13209     if (!CRD->isStandardLayout()) return false;
13210   }
13211 
13212   // See if this is the last field decl in the record.
13213   const Decl *D = FD;
13214   while ((D = D->getNextDeclInContext()))
13215     if (isa<FieldDecl>(D))
13216       return false;
13217   return true;
13218 }
13219 
13220 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
13221                             const ArraySubscriptExpr *ASE,
13222                             bool AllowOnePastEnd, bool IndexNegated) {
13223   // Already diagnosed by the constant evaluator.
13224   if (isConstantEvaluated())
13225     return;
13226 
13227   IndexExpr = IndexExpr->IgnoreParenImpCasts();
13228   if (IndexExpr->isValueDependent())
13229     return;
13230 
13231   const Type *EffectiveType =
13232       BaseExpr->getType()->getPointeeOrArrayElementType();
13233   BaseExpr = BaseExpr->IgnoreParenCasts();
13234   const ConstantArrayType *ArrayTy =
13235       Context.getAsConstantArrayType(BaseExpr->getType());
13236 
13237   if (!ArrayTy)
13238     return;
13239 
13240   const Type *BaseType = ArrayTy->getElementType().getTypePtr();
13241   if (EffectiveType->isDependentType() || BaseType->isDependentType())
13242     return;
13243 
13244   Expr::EvalResult Result;
13245   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
13246     return;
13247 
13248   llvm::APSInt index = Result.Val.getInt();
13249   if (IndexNegated)
13250     index = -index;
13251 
13252   const NamedDecl *ND = nullptr;
13253   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
13254     ND = DRE->getDecl();
13255   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
13256     ND = ME->getMemberDecl();
13257 
13258   if (index.isUnsigned() || !index.isNegative()) {
13259     // It is possible that the type of the base expression after
13260     // IgnoreParenCasts is incomplete, even though the type of the base
13261     // expression before IgnoreParenCasts is complete (see PR39746 for an
13262     // example). In this case we have no information about whether the array
13263     // access exceeds the array bounds. However we can still diagnose an array
13264     // access which precedes the array bounds.
13265     if (BaseType->isIncompleteType())
13266       return;
13267 
13268     llvm::APInt size = ArrayTy->getSize();
13269     if (!size.isStrictlyPositive())
13270       return;
13271 
13272     if (BaseType != EffectiveType) {
13273       // Make sure we're comparing apples to apples when comparing index to size
13274       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
13275       uint64_t array_typesize = Context.getTypeSize(BaseType);
13276       // Handle ptrarith_typesize being zero, such as when casting to void*
13277       if (!ptrarith_typesize) ptrarith_typesize = 1;
13278       if (ptrarith_typesize != array_typesize) {
13279         // There's a cast to a different size type involved
13280         uint64_t ratio = array_typesize / ptrarith_typesize;
13281         // TODO: Be smarter about handling cases where array_typesize is not a
13282         // multiple of ptrarith_typesize
13283         if (ptrarith_typesize * ratio == array_typesize)
13284           size *= llvm::APInt(size.getBitWidth(), ratio);
13285       }
13286     }
13287 
13288     if (size.getBitWidth() > index.getBitWidth())
13289       index = index.zext(size.getBitWidth());
13290     else if (size.getBitWidth() < index.getBitWidth())
13291       size = size.zext(index.getBitWidth());
13292 
13293     // For array subscripting the index must be less than size, but for pointer
13294     // arithmetic also allow the index (offset) to be equal to size since
13295     // computing the next address after the end of the array is legal and
13296     // commonly done e.g. in C++ iterators and range-based for loops.
13297     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
13298       return;
13299 
13300     // Also don't warn for arrays of size 1 which are members of some
13301     // structure. These are often used to approximate flexible arrays in C89
13302     // code.
13303     if (IsTailPaddedMemberArray(*this, size, ND))
13304       return;
13305 
13306     // Suppress the warning if the subscript expression (as identified by the
13307     // ']' location) and the index expression are both from macro expansions
13308     // within a system header.
13309     if (ASE) {
13310       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
13311           ASE->getRBracketLoc());
13312       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
13313         SourceLocation IndexLoc =
13314             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
13315         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
13316           return;
13317       }
13318     }
13319 
13320     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
13321     if (ASE)
13322       DiagID = diag::warn_array_index_exceeds_bounds;
13323 
13324     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
13325                         PDiag(DiagID) << index.toString(10, true)
13326                                       << size.toString(10, true)
13327                                       << (unsigned)size.getLimitedValue(~0U)
13328                                       << IndexExpr->getSourceRange());
13329   } else {
13330     unsigned DiagID = diag::warn_array_index_precedes_bounds;
13331     if (!ASE) {
13332       DiagID = diag::warn_ptr_arith_precedes_bounds;
13333       if (index.isNegative()) index = -index;
13334     }
13335 
13336     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
13337                         PDiag(DiagID) << index.toString(10, true)
13338                                       << IndexExpr->getSourceRange());
13339   }
13340 
13341   if (!ND) {
13342     // Try harder to find a NamedDecl to point at in the note.
13343     while (const ArraySubscriptExpr *ASE =
13344            dyn_cast<ArraySubscriptExpr>(BaseExpr))
13345       BaseExpr = ASE->getBase()->IgnoreParenCasts();
13346     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
13347       ND = DRE->getDecl();
13348     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
13349       ND = ME->getMemberDecl();
13350   }
13351 
13352   if (ND)
13353     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
13354                         PDiag(diag::note_array_declared_here)
13355                             << ND->getDeclName());
13356 }
13357 
13358 void Sema::CheckArrayAccess(const Expr *expr) {
13359   int AllowOnePastEnd = 0;
13360   while (expr) {
13361     expr = expr->IgnoreParenImpCasts();
13362     switch (expr->getStmtClass()) {
13363       case Stmt::ArraySubscriptExprClass: {
13364         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
13365         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
13366                          AllowOnePastEnd > 0);
13367         expr = ASE->getBase();
13368         break;
13369       }
13370       case Stmt::MemberExprClass: {
13371         expr = cast<MemberExpr>(expr)->getBase();
13372         break;
13373       }
13374       case Stmt::OMPArraySectionExprClass: {
13375         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
13376         if (ASE->getLowerBound())
13377           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
13378                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
13379         return;
13380       }
13381       case Stmt::UnaryOperatorClass: {
13382         // Only unwrap the * and & unary operators
13383         const UnaryOperator *UO = cast<UnaryOperator>(expr);
13384         expr = UO->getSubExpr();
13385         switch (UO->getOpcode()) {
13386           case UO_AddrOf:
13387             AllowOnePastEnd++;
13388             break;
13389           case UO_Deref:
13390             AllowOnePastEnd--;
13391             break;
13392           default:
13393             return;
13394         }
13395         break;
13396       }
13397       case Stmt::ConditionalOperatorClass: {
13398         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
13399         if (const Expr *lhs = cond->getLHS())
13400           CheckArrayAccess(lhs);
13401         if (const Expr *rhs = cond->getRHS())
13402           CheckArrayAccess(rhs);
13403         return;
13404       }
13405       case Stmt::CXXOperatorCallExprClass: {
13406         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
13407         for (const auto *Arg : OCE->arguments())
13408           CheckArrayAccess(Arg);
13409         return;
13410       }
13411       default:
13412         return;
13413     }
13414   }
13415 }
13416 
13417 //===--- CHECK: Objective-C retain cycles ----------------------------------//
13418 
13419 namespace {
13420 
13421 struct RetainCycleOwner {
13422   VarDecl *Variable = nullptr;
13423   SourceRange Range;
13424   SourceLocation Loc;
13425   bool Indirect = false;
13426 
13427   RetainCycleOwner() = default;
13428 
13429   void setLocsFrom(Expr *e) {
13430     Loc = e->getExprLoc();
13431     Range = e->getSourceRange();
13432   }
13433 };
13434 
13435 } // namespace
13436 
13437 /// Consider whether capturing the given variable can possibly lead to
13438 /// a retain cycle.
13439 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
13440   // In ARC, it's captured strongly iff the variable has __strong
13441   // lifetime.  In MRR, it's captured strongly if the variable is
13442   // __block and has an appropriate type.
13443   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
13444     return false;
13445 
13446   owner.Variable = var;
13447   if (ref)
13448     owner.setLocsFrom(ref);
13449   return true;
13450 }
13451 
13452 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
13453   while (true) {
13454     e = e->IgnoreParens();
13455     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
13456       switch (cast->getCastKind()) {
13457       case CK_BitCast:
13458       case CK_LValueBitCast:
13459       case CK_LValueToRValue:
13460       case CK_ARCReclaimReturnedObject:
13461         e = cast->getSubExpr();
13462         continue;
13463 
13464       default:
13465         return false;
13466       }
13467     }
13468 
13469     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
13470       ObjCIvarDecl *ivar = ref->getDecl();
13471       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
13472         return false;
13473 
13474       // Try to find a retain cycle in the base.
13475       if (!findRetainCycleOwner(S, ref->getBase(), owner))
13476         return false;
13477 
13478       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
13479       owner.Indirect = true;
13480       return true;
13481     }
13482 
13483     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
13484       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
13485       if (!var) return false;
13486       return considerVariable(var, ref, owner);
13487     }
13488 
13489     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
13490       if (member->isArrow()) return false;
13491 
13492       // Don't count this as an indirect ownership.
13493       e = member->getBase();
13494       continue;
13495     }
13496 
13497     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
13498       // Only pay attention to pseudo-objects on property references.
13499       ObjCPropertyRefExpr *pre
13500         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
13501                                               ->IgnoreParens());
13502       if (!pre) return false;
13503       if (pre->isImplicitProperty()) return false;
13504       ObjCPropertyDecl *property = pre->getExplicitProperty();
13505       if (!property->isRetaining() &&
13506           !(property->getPropertyIvarDecl() &&
13507             property->getPropertyIvarDecl()->getType()
13508               .getObjCLifetime() == Qualifiers::OCL_Strong))
13509           return false;
13510 
13511       owner.Indirect = true;
13512       if (pre->isSuperReceiver()) {
13513         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
13514         if (!owner.Variable)
13515           return false;
13516         owner.Loc = pre->getLocation();
13517         owner.Range = pre->getSourceRange();
13518         return true;
13519       }
13520       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
13521                               ->getSourceExpr());
13522       continue;
13523     }
13524 
13525     // Array ivars?
13526 
13527     return false;
13528   }
13529 }
13530 
13531 namespace {
13532 
13533   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
13534     ASTContext &Context;
13535     VarDecl *Variable;
13536     Expr *Capturer = nullptr;
13537     bool VarWillBeReased = false;
13538 
13539     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
13540         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
13541           Context(Context), Variable(variable) {}
13542 
13543     void VisitDeclRefExpr(DeclRefExpr *ref) {
13544       if (ref->getDecl() == Variable && !Capturer)
13545         Capturer = ref;
13546     }
13547 
13548     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
13549       if (Capturer) return;
13550       Visit(ref->getBase());
13551       if (Capturer && ref->isFreeIvar())
13552         Capturer = ref;
13553     }
13554 
13555     void VisitBlockExpr(BlockExpr *block) {
13556       // Look inside nested blocks
13557       if (block->getBlockDecl()->capturesVariable(Variable))
13558         Visit(block->getBlockDecl()->getBody());
13559     }
13560 
13561     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
13562       if (Capturer) return;
13563       if (OVE->getSourceExpr())
13564         Visit(OVE->getSourceExpr());
13565     }
13566 
13567     void VisitBinaryOperator(BinaryOperator *BinOp) {
13568       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
13569         return;
13570       Expr *LHS = BinOp->getLHS();
13571       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
13572         if (DRE->getDecl() != Variable)
13573           return;
13574         if (Expr *RHS = BinOp->getRHS()) {
13575           RHS = RHS->IgnoreParenCasts();
13576           llvm::APSInt Value;
13577           VarWillBeReased =
13578             (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
13579         }
13580       }
13581     }
13582   };
13583 
13584 } // namespace
13585 
13586 /// Check whether the given argument is a block which captures a
13587 /// variable.
13588 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
13589   assert(owner.Variable && owner.Loc.isValid());
13590 
13591   e = e->IgnoreParenCasts();
13592 
13593   // Look through [^{...} copy] and Block_copy(^{...}).
13594   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
13595     Selector Cmd = ME->getSelector();
13596     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
13597       e = ME->getInstanceReceiver();
13598       if (!e)
13599         return nullptr;
13600       e = e->IgnoreParenCasts();
13601     }
13602   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
13603     if (CE->getNumArgs() == 1) {
13604       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
13605       if (Fn) {
13606         const IdentifierInfo *FnI = Fn->getIdentifier();
13607         if (FnI && FnI->isStr("_Block_copy")) {
13608           e = CE->getArg(0)->IgnoreParenCasts();
13609         }
13610       }
13611     }
13612   }
13613 
13614   BlockExpr *block = dyn_cast<BlockExpr>(e);
13615   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
13616     return nullptr;
13617 
13618   FindCaptureVisitor visitor(S.Context, owner.Variable);
13619   visitor.Visit(block->getBlockDecl()->getBody());
13620   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
13621 }
13622 
13623 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
13624                                 RetainCycleOwner &owner) {
13625   assert(capturer);
13626   assert(owner.Variable && owner.Loc.isValid());
13627 
13628   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
13629     << owner.Variable << capturer->getSourceRange();
13630   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
13631     << owner.Indirect << owner.Range;
13632 }
13633 
13634 /// Check for a keyword selector that starts with the word 'add' or
13635 /// 'set'.
13636 static bool isSetterLikeSelector(Selector sel) {
13637   if (sel.isUnarySelector()) return false;
13638 
13639   StringRef str = sel.getNameForSlot(0);
13640   while (!str.empty() && str.front() == '_') str = str.substr(1);
13641   if (str.startswith("set"))
13642     str = str.substr(3);
13643   else if (str.startswith("add")) {
13644     // Specially whitelist 'addOperationWithBlock:'.
13645     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
13646       return false;
13647     str = str.substr(3);
13648   }
13649   else
13650     return false;
13651 
13652   if (str.empty()) return true;
13653   return !isLowercase(str.front());
13654 }
13655 
13656 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
13657                                                     ObjCMessageExpr *Message) {
13658   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
13659                                                 Message->getReceiverInterface(),
13660                                                 NSAPI::ClassId_NSMutableArray);
13661   if (!IsMutableArray) {
13662     return None;
13663   }
13664 
13665   Selector Sel = Message->getSelector();
13666 
13667   Optional<NSAPI::NSArrayMethodKind> MKOpt =
13668     S.NSAPIObj->getNSArrayMethodKind(Sel);
13669   if (!MKOpt) {
13670     return None;
13671   }
13672 
13673   NSAPI::NSArrayMethodKind MK = *MKOpt;
13674 
13675   switch (MK) {
13676     case NSAPI::NSMutableArr_addObject:
13677     case NSAPI::NSMutableArr_insertObjectAtIndex:
13678     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
13679       return 0;
13680     case NSAPI::NSMutableArr_replaceObjectAtIndex:
13681       return 1;
13682 
13683     default:
13684       return None;
13685   }
13686 
13687   return None;
13688 }
13689 
13690 static
13691 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
13692                                                   ObjCMessageExpr *Message) {
13693   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
13694                                             Message->getReceiverInterface(),
13695                                             NSAPI::ClassId_NSMutableDictionary);
13696   if (!IsMutableDictionary) {
13697     return None;
13698   }
13699 
13700   Selector Sel = Message->getSelector();
13701 
13702   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
13703     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
13704   if (!MKOpt) {
13705     return None;
13706   }
13707 
13708   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
13709 
13710   switch (MK) {
13711     case NSAPI::NSMutableDict_setObjectForKey:
13712     case NSAPI::NSMutableDict_setValueForKey:
13713     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
13714       return 0;
13715 
13716     default:
13717       return None;
13718   }
13719 
13720   return None;
13721 }
13722 
13723 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
13724   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
13725                                                 Message->getReceiverInterface(),
13726                                                 NSAPI::ClassId_NSMutableSet);
13727 
13728   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
13729                                             Message->getReceiverInterface(),
13730                                             NSAPI::ClassId_NSMutableOrderedSet);
13731   if (!IsMutableSet && !IsMutableOrderedSet) {
13732     return None;
13733   }
13734 
13735   Selector Sel = Message->getSelector();
13736 
13737   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
13738   if (!MKOpt) {
13739     return None;
13740   }
13741 
13742   NSAPI::NSSetMethodKind MK = *MKOpt;
13743 
13744   switch (MK) {
13745     case NSAPI::NSMutableSet_addObject:
13746     case NSAPI::NSOrderedSet_setObjectAtIndex:
13747     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
13748     case NSAPI::NSOrderedSet_insertObjectAtIndex:
13749       return 0;
13750     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
13751       return 1;
13752   }
13753 
13754   return None;
13755 }
13756 
13757 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
13758   if (!Message->isInstanceMessage()) {
13759     return;
13760   }
13761 
13762   Optional<int> ArgOpt;
13763 
13764   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
13765       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
13766       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
13767     return;
13768   }
13769 
13770   int ArgIndex = *ArgOpt;
13771 
13772   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
13773   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
13774     Arg = OE->getSourceExpr()->IgnoreImpCasts();
13775   }
13776 
13777   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
13778     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
13779       if (ArgRE->isObjCSelfExpr()) {
13780         Diag(Message->getSourceRange().getBegin(),
13781              diag::warn_objc_circular_container)
13782           << ArgRE->getDecl() << StringRef("'super'");
13783       }
13784     }
13785   } else {
13786     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
13787 
13788     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
13789       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
13790     }
13791 
13792     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
13793       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
13794         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
13795           ValueDecl *Decl = ReceiverRE->getDecl();
13796           Diag(Message->getSourceRange().getBegin(),
13797                diag::warn_objc_circular_container)
13798             << Decl << Decl;
13799           if (!ArgRE->isObjCSelfExpr()) {
13800             Diag(Decl->getLocation(),
13801                  diag::note_objc_circular_container_declared_here)
13802               << Decl;
13803           }
13804         }
13805       }
13806     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
13807       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
13808         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
13809           ObjCIvarDecl *Decl = IvarRE->getDecl();
13810           Diag(Message->getSourceRange().getBegin(),
13811                diag::warn_objc_circular_container)
13812             << Decl << Decl;
13813           Diag(Decl->getLocation(),
13814                diag::note_objc_circular_container_declared_here)
13815             << Decl;
13816         }
13817       }
13818     }
13819   }
13820 }
13821 
13822 /// Check a message send to see if it's likely to cause a retain cycle.
13823 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
13824   // Only check instance methods whose selector looks like a setter.
13825   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
13826     return;
13827 
13828   // Try to find a variable that the receiver is strongly owned by.
13829   RetainCycleOwner owner;
13830   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
13831     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
13832       return;
13833   } else {
13834     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
13835     owner.Variable = getCurMethodDecl()->getSelfDecl();
13836     owner.Loc = msg->getSuperLoc();
13837     owner.Range = msg->getSuperLoc();
13838   }
13839 
13840   // Check whether the receiver is captured by any of the arguments.
13841   const ObjCMethodDecl *MD = msg->getMethodDecl();
13842   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
13843     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
13844       // noescape blocks should not be retained by the method.
13845       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
13846         continue;
13847       return diagnoseRetainCycle(*this, capturer, owner);
13848     }
13849   }
13850 }
13851 
13852 /// Check a property assign to see if it's likely to cause a retain cycle.
13853 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
13854   RetainCycleOwner owner;
13855   if (!findRetainCycleOwner(*this, receiver, owner))
13856     return;
13857 
13858   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
13859     diagnoseRetainCycle(*this, capturer, owner);
13860 }
13861 
13862 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
13863   RetainCycleOwner Owner;
13864   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
13865     return;
13866 
13867   // Because we don't have an expression for the variable, we have to set the
13868   // location explicitly here.
13869   Owner.Loc = Var->getLocation();
13870   Owner.Range = Var->getSourceRange();
13871 
13872   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
13873     diagnoseRetainCycle(*this, Capturer, Owner);
13874 }
13875 
13876 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
13877                                      Expr *RHS, bool isProperty) {
13878   // Check if RHS is an Objective-C object literal, which also can get
13879   // immediately zapped in a weak reference.  Note that we explicitly
13880   // allow ObjCStringLiterals, since those are designed to never really die.
13881   RHS = RHS->IgnoreParenImpCasts();
13882 
13883   // This enum needs to match with the 'select' in
13884   // warn_objc_arc_literal_assign (off-by-1).
13885   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
13886   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
13887     return false;
13888 
13889   S.Diag(Loc, diag::warn_arc_literal_assign)
13890     << (unsigned) Kind
13891     << (isProperty ? 0 : 1)
13892     << RHS->getSourceRange();
13893 
13894   return true;
13895 }
13896 
13897 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
13898                                     Qualifiers::ObjCLifetime LT,
13899                                     Expr *RHS, bool isProperty) {
13900   // Strip off any implicit cast added to get to the one ARC-specific.
13901   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
13902     if (cast->getCastKind() == CK_ARCConsumeObject) {
13903       S.Diag(Loc, diag::warn_arc_retained_assign)
13904         << (LT == Qualifiers::OCL_ExplicitNone)
13905         << (isProperty ? 0 : 1)
13906         << RHS->getSourceRange();
13907       return true;
13908     }
13909     RHS = cast->getSubExpr();
13910   }
13911 
13912   if (LT == Qualifiers::OCL_Weak &&
13913       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
13914     return true;
13915 
13916   return false;
13917 }
13918 
13919 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
13920                               QualType LHS, Expr *RHS) {
13921   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
13922 
13923   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
13924     return false;
13925 
13926   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
13927     return true;
13928 
13929   return false;
13930 }
13931 
13932 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
13933                               Expr *LHS, Expr *RHS) {
13934   QualType LHSType;
13935   // PropertyRef on LHS type need be directly obtained from
13936   // its declaration as it has a PseudoType.
13937   ObjCPropertyRefExpr *PRE
13938     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
13939   if (PRE && !PRE->isImplicitProperty()) {
13940     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
13941     if (PD)
13942       LHSType = PD->getType();
13943   }
13944 
13945   if (LHSType.isNull())
13946     LHSType = LHS->getType();
13947 
13948   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
13949 
13950   if (LT == Qualifiers::OCL_Weak) {
13951     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
13952       getCurFunction()->markSafeWeakUse(LHS);
13953   }
13954 
13955   if (checkUnsafeAssigns(Loc, LHSType, RHS))
13956     return;
13957 
13958   // FIXME. Check for other life times.
13959   if (LT != Qualifiers::OCL_None)
13960     return;
13961 
13962   if (PRE) {
13963     if (PRE->isImplicitProperty())
13964       return;
13965     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
13966     if (!PD)
13967       return;
13968 
13969     unsigned Attributes = PD->getPropertyAttributes();
13970     if (Attributes & ObjCPropertyAttribute::kind_assign) {
13971       // when 'assign' attribute was not explicitly specified
13972       // by user, ignore it and rely on property type itself
13973       // for lifetime info.
13974       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
13975       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
13976           LHSType->isObjCRetainableType())
13977         return;
13978 
13979       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
13980         if (cast->getCastKind() == CK_ARCConsumeObject) {
13981           Diag(Loc, diag::warn_arc_retained_property_assign)
13982           << RHS->getSourceRange();
13983           return;
13984         }
13985         RHS = cast->getSubExpr();
13986       }
13987     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
13988       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
13989         return;
13990     }
13991   }
13992 }
13993 
13994 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
13995 
13996 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
13997                                         SourceLocation StmtLoc,
13998                                         const NullStmt *Body) {
13999   // Do not warn if the body is a macro that expands to nothing, e.g:
14000   //
14001   // #define CALL(x)
14002   // if (condition)
14003   //   CALL(0);
14004   if (Body->hasLeadingEmptyMacro())
14005     return false;
14006 
14007   // Get line numbers of statement and body.
14008   bool StmtLineInvalid;
14009   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
14010                                                       &StmtLineInvalid);
14011   if (StmtLineInvalid)
14012     return false;
14013 
14014   bool BodyLineInvalid;
14015   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
14016                                                       &BodyLineInvalid);
14017   if (BodyLineInvalid)
14018     return false;
14019 
14020   // Warn if null statement and body are on the same line.
14021   if (StmtLine != BodyLine)
14022     return false;
14023 
14024   return true;
14025 }
14026 
14027 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
14028                                  const Stmt *Body,
14029                                  unsigned DiagID) {
14030   // Since this is a syntactic check, don't emit diagnostic for template
14031   // instantiations, this just adds noise.
14032   if (CurrentInstantiationScope)
14033     return;
14034 
14035   // The body should be a null statement.
14036   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
14037   if (!NBody)
14038     return;
14039 
14040   // Do the usual checks.
14041   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
14042     return;
14043 
14044   Diag(NBody->getSemiLoc(), DiagID);
14045   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
14046 }
14047 
14048 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
14049                                  const Stmt *PossibleBody) {
14050   assert(!CurrentInstantiationScope); // Ensured by caller
14051 
14052   SourceLocation StmtLoc;
14053   const Stmt *Body;
14054   unsigned DiagID;
14055   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
14056     StmtLoc = FS->getRParenLoc();
14057     Body = FS->getBody();
14058     DiagID = diag::warn_empty_for_body;
14059   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
14060     StmtLoc = WS->getCond()->getSourceRange().getEnd();
14061     Body = WS->getBody();
14062     DiagID = diag::warn_empty_while_body;
14063   } else
14064     return; // Neither `for' nor `while'.
14065 
14066   // The body should be a null statement.
14067   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
14068   if (!NBody)
14069     return;
14070 
14071   // Skip expensive checks if diagnostic is disabled.
14072   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
14073     return;
14074 
14075   // Do the usual checks.
14076   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
14077     return;
14078 
14079   // `for(...);' and `while(...);' are popular idioms, so in order to keep
14080   // noise level low, emit diagnostics only if for/while is followed by a
14081   // CompoundStmt, e.g.:
14082   //    for (int i = 0; i < n; i++);
14083   //    {
14084   //      a(i);
14085   //    }
14086   // or if for/while is followed by a statement with more indentation
14087   // than for/while itself:
14088   //    for (int i = 0; i < n; i++);
14089   //      a(i);
14090   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
14091   if (!ProbableTypo) {
14092     bool BodyColInvalid;
14093     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
14094         PossibleBody->getBeginLoc(), &BodyColInvalid);
14095     if (BodyColInvalid)
14096       return;
14097 
14098     bool StmtColInvalid;
14099     unsigned StmtCol =
14100         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
14101     if (StmtColInvalid)
14102       return;
14103 
14104     if (BodyCol > StmtCol)
14105       ProbableTypo = true;
14106   }
14107 
14108   if (ProbableTypo) {
14109     Diag(NBody->getSemiLoc(), DiagID);
14110     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
14111   }
14112 }
14113 
14114 //===--- CHECK: Warn on self move with std::move. -------------------------===//
14115 
14116 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
14117 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
14118                              SourceLocation OpLoc) {
14119   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
14120     return;
14121 
14122   if (inTemplateInstantiation())
14123     return;
14124 
14125   // Strip parens and casts away.
14126   LHSExpr = LHSExpr->IgnoreParenImpCasts();
14127   RHSExpr = RHSExpr->IgnoreParenImpCasts();
14128 
14129   // Check for a call expression
14130   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
14131   if (!CE || CE->getNumArgs() != 1)
14132     return;
14133 
14134   // Check for a call to std::move
14135   if (!CE->isCallToStdMove())
14136     return;
14137 
14138   // Get argument from std::move
14139   RHSExpr = CE->getArg(0);
14140 
14141   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
14142   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
14143 
14144   // Two DeclRefExpr's, check that the decls are the same.
14145   if (LHSDeclRef && RHSDeclRef) {
14146     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
14147       return;
14148     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
14149         RHSDeclRef->getDecl()->getCanonicalDecl())
14150       return;
14151 
14152     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14153                                         << LHSExpr->getSourceRange()
14154                                         << RHSExpr->getSourceRange();
14155     return;
14156   }
14157 
14158   // Member variables require a different approach to check for self moves.
14159   // MemberExpr's are the same if every nested MemberExpr refers to the same
14160   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
14161   // the base Expr's are CXXThisExpr's.
14162   const Expr *LHSBase = LHSExpr;
14163   const Expr *RHSBase = RHSExpr;
14164   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
14165   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
14166   if (!LHSME || !RHSME)
14167     return;
14168 
14169   while (LHSME && RHSME) {
14170     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
14171         RHSME->getMemberDecl()->getCanonicalDecl())
14172       return;
14173 
14174     LHSBase = LHSME->getBase();
14175     RHSBase = RHSME->getBase();
14176     LHSME = dyn_cast<MemberExpr>(LHSBase);
14177     RHSME = dyn_cast<MemberExpr>(RHSBase);
14178   }
14179 
14180   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
14181   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
14182   if (LHSDeclRef && RHSDeclRef) {
14183     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
14184       return;
14185     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
14186         RHSDeclRef->getDecl()->getCanonicalDecl())
14187       return;
14188 
14189     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14190                                         << LHSExpr->getSourceRange()
14191                                         << RHSExpr->getSourceRange();
14192     return;
14193   }
14194 
14195   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
14196     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14197                                         << LHSExpr->getSourceRange()
14198                                         << RHSExpr->getSourceRange();
14199 }
14200 
14201 //===--- Layout compatibility ----------------------------------------------//
14202 
14203 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
14204 
14205 /// Check if two enumeration types are layout-compatible.
14206 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
14207   // C++11 [dcl.enum] p8:
14208   // Two enumeration types are layout-compatible if they have the same
14209   // underlying type.
14210   return ED1->isComplete() && ED2->isComplete() &&
14211          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
14212 }
14213 
14214 /// Check if two fields are layout-compatible.
14215 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
14216                                FieldDecl *Field2) {
14217   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
14218     return false;
14219 
14220   if (Field1->isBitField() != Field2->isBitField())
14221     return false;
14222 
14223   if (Field1->isBitField()) {
14224     // Make sure that the bit-fields are the same length.
14225     unsigned Bits1 = Field1->getBitWidthValue(C);
14226     unsigned Bits2 = Field2->getBitWidthValue(C);
14227 
14228     if (Bits1 != Bits2)
14229       return false;
14230   }
14231 
14232   return true;
14233 }
14234 
14235 /// Check if two standard-layout structs are layout-compatible.
14236 /// (C++11 [class.mem] p17)
14237 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
14238                                      RecordDecl *RD2) {
14239   // If both records are C++ classes, check that base classes match.
14240   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
14241     // If one of records is a CXXRecordDecl we are in C++ mode,
14242     // thus the other one is a CXXRecordDecl, too.
14243     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
14244     // Check number of base classes.
14245     if (D1CXX->getNumBases() != D2CXX->getNumBases())
14246       return false;
14247 
14248     // Check the base classes.
14249     for (CXXRecordDecl::base_class_const_iterator
14250                Base1 = D1CXX->bases_begin(),
14251            BaseEnd1 = D1CXX->bases_end(),
14252               Base2 = D2CXX->bases_begin();
14253          Base1 != BaseEnd1;
14254          ++Base1, ++Base2) {
14255       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
14256         return false;
14257     }
14258   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
14259     // If only RD2 is a C++ class, it should have zero base classes.
14260     if (D2CXX->getNumBases() > 0)
14261       return false;
14262   }
14263 
14264   // Check the fields.
14265   RecordDecl::field_iterator Field2 = RD2->field_begin(),
14266                              Field2End = RD2->field_end(),
14267                              Field1 = RD1->field_begin(),
14268                              Field1End = RD1->field_end();
14269   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
14270     if (!isLayoutCompatible(C, *Field1, *Field2))
14271       return false;
14272   }
14273   if (Field1 != Field1End || Field2 != Field2End)
14274     return false;
14275 
14276   return true;
14277 }
14278 
14279 /// Check if two standard-layout unions are layout-compatible.
14280 /// (C++11 [class.mem] p18)
14281 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
14282                                     RecordDecl *RD2) {
14283   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
14284   for (auto *Field2 : RD2->fields())
14285     UnmatchedFields.insert(Field2);
14286 
14287   for (auto *Field1 : RD1->fields()) {
14288     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
14289         I = UnmatchedFields.begin(),
14290         E = UnmatchedFields.end();
14291 
14292     for ( ; I != E; ++I) {
14293       if (isLayoutCompatible(C, Field1, *I)) {
14294         bool Result = UnmatchedFields.erase(*I);
14295         (void) Result;
14296         assert(Result);
14297         break;
14298       }
14299     }
14300     if (I == E)
14301       return false;
14302   }
14303 
14304   return UnmatchedFields.empty();
14305 }
14306 
14307 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
14308                                RecordDecl *RD2) {
14309   if (RD1->isUnion() != RD2->isUnion())
14310     return false;
14311 
14312   if (RD1->isUnion())
14313     return isLayoutCompatibleUnion(C, RD1, RD2);
14314   else
14315     return isLayoutCompatibleStruct(C, RD1, RD2);
14316 }
14317 
14318 /// Check if two types are layout-compatible in C++11 sense.
14319 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
14320   if (T1.isNull() || T2.isNull())
14321     return false;
14322 
14323   // C++11 [basic.types] p11:
14324   // If two types T1 and T2 are the same type, then T1 and T2 are
14325   // layout-compatible types.
14326   if (C.hasSameType(T1, T2))
14327     return true;
14328 
14329   T1 = T1.getCanonicalType().getUnqualifiedType();
14330   T2 = T2.getCanonicalType().getUnqualifiedType();
14331 
14332   const Type::TypeClass TC1 = T1->getTypeClass();
14333   const Type::TypeClass TC2 = T2->getTypeClass();
14334 
14335   if (TC1 != TC2)
14336     return false;
14337 
14338   if (TC1 == Type::Enum) {
14339     return isLayoutCompatible(C,
14340                               cast<EnumType>(T1)->getDecl(),
14341                               cast<EnumType>(T2)->getDecl());
14342   } else if (TC1 == Type::Record) {
14343     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
14344       return false;
14345 
14346     return isLayoutCompatible(C,
14347                               cast<RecordType>(T1)->getDecl(),
14348                               cast<RecordType>(T2)->getDecl());
14349   }
14350 
14351   return false;
14352 }
14353 
14354 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
14355 
14356 /// Given a type tag expression find the type tag itself.
14357 ///
14358 /// \param TypeExpr Type tag expression, as it appears in user's code.
14359 ///
14360 /// \param VD Declaration of an identifier that appears in a type tag.
14361 ///
14362 /// \param MagicValue Type tag magic value.
14363 ///
14364 /// \param isConstantEvaluated wether the evalaution should be performed in
14365 
14366 /// constant context.
14367 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
14368                             const ValueDecl **VD, uint64_t *MagicValue,
14369                             bool isConstantEvaluated) {
14370   while(true) {
14371     if (!TypeExpr)
14372       return false;
14373 
14374     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
14375 
14376     switch (TypeExpr->getStmtClass()) {
14377     case Stmt::UnaryOperatorClass: {
14378       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
14379       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
14380         TypeExpr = UO->getSubExpr();
14381         continue;
14382       }
14383       return false;
14384     }
14385 
14386     case Stmt::DeclRefExprClass: {
14387       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
14388       *VD = DRE->getDecl();
14389       return true;
14390     }
14391 
14392     case Stmt::IntegerLiteralClass: {
14393       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
14394       llvm::APInt MagicValueAPInt = IL->getValue();
14395       if (MagicValueAPInt.getActiveBits() <= 64) {
14396         *MagicValue = MagicValueAPInt.getZExtValue();
14397         return true;
14398       } else
14399         return false;
14400     }
14401 
14402     case Stmt::BinaryConditionalOperatorClass:
14403     case Stmt::ConditionalOperatorClass: {
14404       const AbstractConditionalOperator *ACO =
14405           cast<AbstractConditionalOperator>(TypeExpr);
14406       bool Result;
14407       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
14408                                                      isConstantEvaluated)) {
14409         if (Result)
14410           TypeExpr = ACO->getTrueExpr();
14411         else
14412           TypeExpr = ACO->getFalseExpr();
14413         continue;
14414       }
14415       return false;
14416     }
14417 
14418     case Stmt::BinaryOperatorClass: {
14419       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
14420       if (BO->getOpcode() == BO_Comma) {
14421         TypeExpr = BO->getRHS();
14422         continue;
14423       }
14424       return false;
14425     }
14426 
14427     default:
14428       return false;
14429     }
14430   }
14431 }
14432 
14433 /// Retrieve the C type corresponding to type tag TypeExpr.
14434 ///
14435 /// \param TypeExpr Expression that specifies a type tag.
14436 ///
14437 /// \param MagicValues Registered magic values.
14438 ///
14439 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
14440 ///        kind.
14441 ///
14442 /// \param TypeInfo Information about the corresponding C type.
14443 ///
14444 /// \param isConstantEvaluated wether the evalaution should be performed in
14445 /// constant context.
14446 ///
14447 /// \returns true if the corresponding C type was found.
14448 static bool GetMatchingCType(
14449     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
14450     const ASTContext &Ctx,
14451     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
14452         *MagicValues,
14453     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
14454     bool isConstantEvaluated) {
14455   FoundWrongKind = false;
14456 
14457   // Variable declaration that has type_tag_for_datatype attribute.
14458   const ValueDecl *VD = nullptr;
14459 
14460   uint64_t MagicValue;
14461 
14462   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
14463     return false;
14464 
14465   if (VD) {
14466     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
14467       if (I->getArgumentKind() != ArgumentKind) {
14468         FoundWrongKind = true;
14469         return false;
14470       }
14471       TypeInfo.Type = I->getMatchingCType();
14472       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
14473       TypeInfo.MustBeNull = I->getMustBeNull();
14474       return true;
14475     }
14476     return false;
14477   }
14478 
14479   if (!MagicValues)
14480     return false;
14481 
14482   llvm::DenseMap<Sema::TypeTagMagicValue,
14483                  Sema::TypeTagData>::const_iterator I =
14484       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
14485   if (I == MagicValues->end())
14486     return false;
14487 
14488   TypeInfo = I->second;
14489   return true;
14490 }
14491 
14492 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
14493                                       uint64_t MagicValue, QualType Type,
14494                                       bool LayoutCompatible,
14495                                       bool MustBeNull) {
14496   if (!TypeTagForDatatypeMagicValues)
14497     TypeTagForDatatypeMagicValues.reset(
14498         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
14499 
14500   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
14501   (*TypeTagForDatatypeMagicValues)[Magic] =
14502       TypeTagData(Type, LayoutCompatible, MustBeNull);
14503 }
14504 
14505 static bool IsSameCharType(QualType T1, QualType T2) {
14506   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
14507   if (!BT1)
14508     return false;
14509 
14510   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
14511   if (!BT2)
14512     return false;
14513 
14514   BuiltinType::Kind T1Kind = BT1->getKind();
14515   BuiltinType::Kind T2Kind = BT2->getKind();
14516 
14517   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
14518          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
14519          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
14520          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
14521 }
14522 
14523 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
14524                                     const ArrayRef<const Expr *> ExprArgs,
14525                                     SourceLocation CallSiteLoc) {
14526   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
14527   bool IsPointerAttr = Attr->getIsPointer();
14528 
14529   // Retrieve the argument representing the 'type_tag'.
14530   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
14531   if (TypeTagIdxAST >= ExprArgs.size()) {
14532     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
14533         << 0 << Attr->getTypeTagIdx().getSourceIndex();
14534     return;
14535   }
14536   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
14537   bool FoundWrongKind;
14538   TypeTagData TypeInfo;
14539   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
14540                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
14541                         TypeInfo, isConstantEvaluated())) {
14542     if (FoundWrongKind)
14543       Diag(TypeTagExpr->getExprLoc(),
14544            diag::warn_type_tag_for_datatype_wrong_kind)
14545         << TypeTagExpr->getSourceRange();
14546     return;
14547   }
14548 
14549   // Retrieve the argument representing the 'arg_idx'.
14550   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
14551   if (ArgumentIdxAST >= ExprArgs.size()) {
14552     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
14553         << 1 << Attr->getArgumentIdx().getSourceIndex();
14554     return;
14555   }
14556   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
14557   if (IsPointerAttr) {
14558     // Skip implicit cast of pointer to `void *' (as a function argument).
14559     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
14560       if (ICE->getType()->isVoidPointerType() &&
14561           ICE->getCastKind() == CK_BitCast)
14562         ArgumentExpr = ICE->getSubExpr();
14563   }
14564   QualType ArgumentType = ArgumentExpr->getType();
14565 
14566   // Passing a `void*' pointer shouldn't trigger a warning.
14567   if (IsPointerAttr && ArgumentType->isVoidPointerType())
14568     return;
14569 
14570   if (TypeInfo.MustBeNull) {
14571     // Type tag with matching void type requires a null pointer.
14572     if (!ArgumentExpr->isNullPointerConstant(Context,
14573                                              Expr::NPC_ValueDependentIsNotNull)) {
14574       Diag(ArgumentExpr->getExprLoc(),
14575            diag::warn_type_safety_null_pointer_required)
14576           << ArgumentKind->getName()
14577           << ArgumentExpr->getSourceRange()
14578           << TypeTagExpr->getSourceRange();
14579     }
14580     return;
14581   }
14582 
14583   QualType RequiredType = TypeInfo.Type;
14584   if (IsPointerAttr)
14585     RequiredType = Context.getPointerType(RequiredType);
14586 
14587   bool mismatch = false;
14588   if (!TypeInfo.LayoutCompatible) {
14589     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
14590 
14591     // C++11 [basic.fundamental] p1:
14592     // Plain char, signed char, and unsigned char are three distinct types.
14593     //
14594     // But we treat plain `char' as equivalent to `signed char' or `unsigned
14595     // char' depending on the current char signedness mode.
14596     if (mismatch)
14597       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
14598                                            RequiredType->getPointeeType())) ||
14599           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
14600         mismatch = false;
14601   } else
14602     if (IsPointerAttr)
14603       mismatch = !isLayoutCompatible(Context,
14604                                      ArgumentType->getPointeeType(),
14605                                      RequiredType->getPointeeType());
14606     else
14607       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
14608 
14609   if (mismatch)
14610     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
14611         << ArgumentType << ArgumentKind
14612         << TypeInfo.LayoutCompatible << RequiredType
14613         << ArgumentExpr->getSourceRange()
14614         << TypeTagExpr->getSourceRange();
14615 }
14616 
14617 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
14618                                          CharUnits Alignment) {
14619   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
14620 }
14621 
14622 void Sema::DiagnoseMisalignedMembers() {
14623   for (MisalignedMember &m : MisalignedMembers) {
14624     const NamedDecl *ND = m.RD;
14625     if (ND->getName().empty()) {
14626       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
14627         ND = TD;
14628     }
14629     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
14630         << m.MD << ND << m.E->getSourceRange();
14631   }
14632   MisalignedMembers.clear();
14633 }
14634 
14635 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
14636   E = E->IgnoreParens();
14637   if (!T->isPointerType() && !T->isIntegerType())
14638     return;
14639   if (isa<UnaryOperator>(E) &&
14640       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
14641     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
14642     if (isa<MemberExpr>(Op)) {
14643       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
14644       if (MA != MisalignedMembers.end() &&
14645           (T->isIntegerType() ||
14646            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
14647                                    Context.getTypeAlignInChars(
14648                                        T->getPointeeType()) <= MA->Alignment))))
14649         MisalignedMembers.erase(MA);
14650     }
14651   }
14652 }
14653 
14654 void Sema::RefersToMemberWithReducedAlignment(
14655     Expr *E,
14656     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
14657         Action) {
14658   const auto *ME = dyn_cast<MemberExpr>(E);
14659   if (!ME)
14660     return;
14661 
14662   // No need to check expressions with an __unaligned-qualified type.
14663   if (E->getType().getQualifiers().hasUnaligned())
14664     return;
14665 
14666   // For a chain of MemberExpr like "a.b.c.d" this list
14667   // will keep FieldDecl's like [d, c, b].
14668   SmallVector<FieldDecl *, 4> ReverseMemberChain;
14669   const MemberExpr *TopME = nullptr;
14670   bool AnyIsPacked = false;
14671   do {
14672     QualType BaseType = ME->getBase()->getType();
14673     if (BaseType->isDependentType())
14674       return;
14675     if (ME->isArrow())
14676       BaseType = BaseType->getPointeeType();
14677     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
14678     if (RD->isInvalidDecl())
14679       return;
14680 
14681     ValueDecl *MD = ME->getMemberDecl();
14682     auto *FD = dyn_cast<FieldDecl>(MD);
14683     // We do not care about non-data members.
14684     if (!FD || FD->isInvalidDecl())
14685       return;
14686 
14687     AnyIsPacked =
14688         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
14689     ReverseMemberChain.push_back(FD);
14690 
14691     TopME = ME;
14692     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
14693   } while (ME);
14694   assert(TopME && "We did not compute a topmost MemberExpr!");
14695 
14696   // Not the scope of this diagnostic.
14697   if (!AnyIsPacked)
14698     return;
14699 
14700   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
14701   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
14702   // TODO: The innermost base of the member expression may be too complicated.
14703   // For now, just disregard these cases. This is left for future
14704   // improvement.
14705   if (!DRE && !isa<CXXThisExpr>(TopBase))
14706       return;
14707 
14708   // Alignment expected by the whole expression.
14709   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
14710 
14711   // No need to do anything else with this case.
14712   if (ExpectedAlignment.isOne())
14713     return;
14714 
14715   // Synthesize offset of the whole access.
14716   CharUnits Offset;
14717   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
14718        I++) {
14719     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
14720   }
14721 
14722   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
14723   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
14724       ReverseMemberChain.back()->getParent()->getTypeForDecl());
14725 
14726   // The base expression of the innermost MemberExpr may give
14727   // stronger guarantees than the class containing the member.
14728   if (DRE && !TopME->isArrow()) {
14729     const ValueDecl *VD = DRE->getDecl();
14730     if (!VD->getType()->isReferenceType())
14731       CompleteObjectAlignment =
14732           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
14733   }
14734 
14735   // Check if the synthesized offset fulfills the alignment.
14736   if (Offset % ExpectedAlignment != 0 ||
14737       // It may fulfill the offset it but the effective alignment may still be
14738       // lower than the expected expression alignment.
14739       CompleteObjectAlignment < ExpectedAlignment) {
14740     // If this happens, we want to determine a sensible culprit of this.
14741     // Intuitively, watching the chain of member expressions from right to
14742     // left, we start with the required alignment (as required by the field
14743     // type) but some packed attribute in that chain has reduced the alignment.
14744     // It may happen that another packed structure increases it again. But if
14745     // we are here such increase has not been enough. So pointing the first
14746     // FieldDecl that either is packed or else its RecordDecl is,
14747     // seems reasonable.
14748     FieldDecl *FD = nullptr;
14749     CharUnits Alignment;
14750     for (FieldDecl *FDI : ReverseMemberChain) {
14751       if (FDI->hasAttr<PackedAttr>() ||
14752           FDI->getParent()->hasAttr<PackedAttr>()) {
14753         FD = FDI;
14754         Alignment = std::min(
14755             Context.getTypeAlignInChars(FD->getType()),
14756             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
14757         break;
14758       }
14759     }
14760     assert(FD && "We did not find a packed FieldDecl!");
14761     Action(E, FD->getParent(), FD, Alignment);
14762   }
14763 }
14764 
14765 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
14766   using namespace std::placeholders;
14767 
14768   RefersToMemberWithReducedAlignment(
14769       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
14770                      _2, _3, _4));
14771 }
14772