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 ExprResult
1380 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1381                                CallExpr *TheCall) {
1382   ExprResult TheCallResult(TheCall);
1383 
1384   // Find out if any arguments are required to be integer constant expressions.
1385   unsigned ICEArguments = 0;
1386   ASTContext::GetBuiltinTypeError Error;
1387   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1388   if (Error != ASTContext::GE_None)
1389     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
1390 
1391   // If any arguments are required to be ICE's, check and diagnose.
1392   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1393     // Skip arguments not required to be ICE's.
1394     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1395 
1396     llvm::APSInt Result;
1397     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1398       return true;
1399     ICEArguments &= ~(1 << ArgNo);
1400   }
1401 
1402   switch (BuiltinID) {
1403   case Builtin::BI__builtin___CFStringMakeConstantString:
1404     assert(TheCall->getNumArgs() == 1 &&
1405            "Wrong # arguments to builtin CFStringMakeConstantString");
1406     if (CheckObjCString(TheCall->getArg(0)))
1407       return ExprError();
1408     break;
1409   case Builtin::BI__builtin_ms_va_start:
1410   case Builtin::BI__builtin_stdarg_start:
1411   case Builtin::BI__builtin_va_start:
1412     if (SemaBuiltinVAStart(BuiltinID, TheCall))
1413       return ExprError();
1414     break;
1415   case Builtin::BI__va_start: {
1416     switch (Context.getTargetInfo().getTriple().getArch()) {
1417     case llvm::Triple::aarch64:
1418     case llvm::Triple::arm:
1419     case llvm::Triple::thumb:
1420       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1421         return ExprError();
1422       break;
1423     default:
1424       if (SemaBuiltinVAStart(BuiltinID, TheCall))
1425         return ExprError();
1426       break;
1427     }
1428     break;
1429   }
1430 
1431   // The acquire, release, and no fence variants are ARM and AArch64 only.
1432   case Builtin::BI_interlockedbittestandset_acq:
1433   case Builtin::BI_interlockedbittestandset_rel:
1434   case Builtin::BI_interlockedbittestandset_nf:
1435   case Builtin::BI_interlockedbittestandreset_acq:
1436   case Builtin::BI_interlockedbittestandreset_rel:
1437   case Builtin::BI_interlockedbittestandreset_nf:
1438     if (CheckBuiltinTargetSupport(
1439             *this, BuiltinID, TheCall,
1440             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1441       return ExprError();
1442     break;
1443 
1444   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1445   case Builtin::BI_bittest64:
1446   case Builtin::BI_bittestandcomplement64:
1447   case Builtin::BI_bittestandreset64:
1448   case Builtin::BI_bittestandset64:
1449   case Builtin::BI_interlockedbittestandreset64:
1450   case Builtin::BI_interlockedbittestandset64:
1451     if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1452                                   {llvm::Triple::x86_64, llvm::Triple::arm,
1453                                    llvm::Triple::thumb, llvm::Triple::aarch64}))
1454       return ExprError();
1455     break;
1456 
1457   case Builtin::BI__builtin_isgreater:
1458   case Builtin::BI__builtin_isgreaterequal:
1459   case Builtin::BI__builtin_isless:
1460   case Builtin::BI__builtin_islessequal:
1461   case Builtin::BI__builtin_islessgreater:
1462   case Builtin::BI__builtin_isunordered:
1463     if (SemaBuiltinUnorderedCompare(TheCall))
1464       return ExprError();
1465     break;
1466   case Builtin::BI__builtin_fpclassify:
1467     if (SemaBuiltinFPClassification(TheCall, 6))
1468       return ExprError();
1469     break;
1470   case Builtin::BI__builtin_isfinite:
1471   case Builtin::BI__builtin_isinf:
1472   case Builtin::BI__builtin_isinf_sign:
1473   case Builtin::BI__builtin_isnan:
1474   case Builtin::BI__builtin_isnormal:
1475   case Builtin::BI__builtin_signbit:
1476   case Builtin::BI__builtin_signbitf:
1477   case Builtin::BI__builtin_signbitl:
1478     if (SemaBuiltinFPClassification(TheCall, 1))
1479       return ExprError();
1480     break;
1481   case Builtin::BI__builtin_shufflevector:
1482     return SemaBuiltinShuffleVector(TheCall);
1483     // TheCall will be freed by the smart pointer here, but that's fine, since
1484     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1485   case Builtin::BI__builtin_prefetch:
1486     if (SemaBuiltinPrefetch(TheCall))
1487       return ExprError();
1488     break;
1489   case Builtin::BI__builtin_alloca_with_align:
1490     if (SemaBuiltinAllocaWithAlign(TheCall))
1491       return ExprError();
1492     LLVM_FALLTHROUGH;
1493   case Builtin::BI__builtin_alloca:
1494     Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1495         << TheCall->getDirectCallee();
1496     break;
1497   case Builtin::BI__assume:
1498   case Builtin::BI__builtin_assume:
1499     if (SemaBuiltinAssume(TheCall))
1500       return ExprError();
1501     break;
1502   case Builtin::BI__builtin_assume_aligned:
1503     if (SemaBuiltinAssumeAligned(TheCall))
1504       return ExprError();
1505     break;
1506   case Builtin::BI__builtin_dynamic_object_size:
1507   case Builtin::BI__builtin_object_size:
1508     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1509       return ExprError();
1510     break;
1511   case Builtin::BI__builtin_longjmp:
1512     if (SemaBuiltinLongjmp(TheCall))
1513       return ExprError();
1514     break;
1515   case Builtin::BI__builtin_setjmp:
1516     if (SemaBuiltinSetjmp(TheCall))
1517       return ExprError();
1518     break;
1519   case Builtin::BI_setjmp:
1520   case Builtin::BI_setjmpex:
1521     if (checkArgCount(*this, TheCall, 1))
1522       return true;
1523     break;
1524   case Builtin::BI__builtin_classify_type:
1525     if (checkArgCount(*this, TheCall, 1)) return true;
1526     TheCall->setType(Context.IntTy);
1527     break;
1528   case Builtin::BI__builtin_constant_p: {
1529     if (checkArgCount(*this, TheCall, 1)) return true;
1530     ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1531     if (Arg.isInvalid()) return true;
1532     TheCall->setArg(0, Arg.get());
1533     TheCall->setType(Context.IntTy);
1534     break;
1535   }
1536   case Builtin::BI__builtin_launder:
1537     return SemaBuiltinLaunder(*this, TheCall);
1538   case Builtin::BI__sync_fetch_and_add:
1539   case Builtin::BI__sync_fetch_and_add_1:
1540   case Builtin::BI__sync_fetch_and_add_2:
1541   case Builtin::BI__sync_fetch_and_add_4:
1542   case Builtin::BI__sync_fetch_and_add_8:
1543   case Builtin::BI__sync_fetch_and_add_16:
1544   case Builtin::BI__sync_fetch_and_sub:
1545   case Builtin::BI__sync_fetch_and_sub_1:
1546   case Builtin::BI__sync_fetch_and_sub_2:
1547   case Builtin::BI__sync_fetch_and_sub_4:
1548   case Builtin::BI__sync_fetch_and_sub_8:
1549   case Builtin::BI__sync_fetch_and_sub_16:
1550   case Builtin::BI__sync_fetch_and_or:
1551   case Builtin::BI__sync_fetch_and_or_1:
1552   case Builtin::BI__sync_fetch_and_or_2:
1553   case Builtin::BI__sync_fetch_and_or_4:
1554   case Builtin::BI__sync_fetch_and_or_8:
1555   case Builtin::BI__sync_fetch_and_or_16:
1556   case Builtin::BI__sync_fetch_and_and:
1557   case Builtin::BI__sync_fetch_and_and_1:
1558   case Builtin::BI__sync_fetch_and_and_2:
1559   case Builtin::BI__sync_fetch_and_and_4:
1560   case Builtin::BI__sync_fetch_and_and_8:
1561   case Builtin::BI__sync_fetch_and_and_16:
1562   case Builtin::BI__sync_fetch_and_xor:
1563   case Builtin::BI__sync_fetch_and_xor_1:
1564   case Builtin::BI__sync_fetch_and_xor_2:
1565   case Builtin::BI__sync_fetch_and_xor_4:
1566   case Builtin::BI__sync_fetch_and_xor_8:
1567   case Builtin::BI__sync_fetch_and_xor_16:
1568   case Builtin::BI__sync_fetch_and_nand:
1569   case Builtin::BI__sync_fetch_and_nand_1:
1570   case Builtin::BI__sync_fetch_and_nand_2:
1571   case Builtin::BI__sync_fetch_and_nand_4:
1572   case Builtin::BI__sync_fetch_and_nand_8:
1573   case Builtin::BI__sync_fetch_and_nand_16:
1574   case Builtin::BI__sync_add_and_fetch:
1575   case Builtin::BI__sync_add_and_fetch_1:
1576   case Builtin::BI__sync_add_and_fetch_2:
1577   case Builtin::BI__sync_add_and_fetch_4:
1578   case Builtin::BI__sync_add_and_fetch_8:
1579   case Builtin::BI__sync_add_and_fetch_16:
1580   case Builtin::BI__sync_sub_and_fetch:
1581   case Builtin::BI__sync_sub_and_fetch_1:
1582   case Builtin::BI__sync_sub_and_fetch_2:
1583   case Builtin::BI__sync_sub_and_fetch_4:
1584   case Builtin::BI__sync_sub_and_fetch_8:
1585   case Builtin::BI__sync_sub_and_fetch_16:
1586   case Builtin::BI__sync_and_and_fetch:
1587   case Builtin::BI__sync_and_and_fetch_1:
1588   case Builtin::BI__sync_and_and_fetch_2:
1589   case Builtin::BI__sync_and_and_fetch_4:
1590   case Builtin::BI__sync_and_and_fetch_8:
1591   case Builtin::BI__sync_and_and_fetch_16:
1592   case Builtin::BI__sync_or_and_fetch:
1593   case Builtin::BI__sync_or_and_fetch_1:
1594   case Builtin::BI__sync_or_and_fetch_2:
1595   case Builtin::BI__sync_or_and_fetch_4:
1596   case Builtin::BI__sync_or_and_fetch_8:
1597   case Builtin::BI__sync_or_and_fetch_16:
1598   case Builtin::BI__sync_xor_and_fetch:
1599   case Builtin::BI__sync_xor_and_fetch_1:
1600   case Builtin::BI__sync_xor_and_fetch_2:
1601   case Builtin::BI__sync_xor_and_fetch_4:
1602   case Builtin::BI__sync_xor_and_fetch_8:
1603   case Builtin::BI__sync_xor_and_fetch_16:
1604   case Builtin::BI__sync_nand_and_fetch:
1605   case Builtin::BI__sync_nand_and_fetch_1:
1606   case Builtin::BI__sync_nand_and_fetch_2:
1607   case Builtin::BI__sync_nand_and_fetch_4:
1608   case Builtin::BI__sync_nand_and_fetch_8:
1609   case Builtin::BI__sync_nand_and_fetch_16:
1610   case Builtin::BI__sync_val_compare_and_swap:
1611   case Builtin::BI__sync_val_compare_and_swap_1:
1612   case Builtin::BI__sync_val_compare_and_swap_2:
1613   case Builtin::BI__sync_val_compare_and_swap_4:
1614   case Builtin::BI__sync_val_compare_and_swap_8:
1615   case Builtin::BI__sync_val_compare_and_swap_16:
1616   case Builtin::BI__sync_bool_compare_and_swap:
1617   case Builtin::BI__sync_bool_compare_and_swap_1:
1618   case Builtin::BI__sync_bool_compare_and_swap_2:
1619   case Builtin::BI__sync_bool_compare_and_swap_4:
1620   case Builtin::BI__sync_bool_compare_and_swap_8:
1621   case Builtin::BI__sync_bool_compare_and_swap_16:
1622   case Builtin::BI__sync_lock_test_and_set:
1623   case Builtin::BI__sync_lock_test_and_set_1:
1624   case Builtin::BI__sync_lock_test_and_set_2:
1625   case Builtin::BI__sync_lock_test_and_set_4:
1626   case Builtin::BI__sync_lock_test_and_set_8:
1627   case Builtin::BI__sync_lock_test_and_set_16:
1628   case Builtin::BI__sync_lock_release:
1629   case Builtin::BI__sync_lock_release_1:
1630   case Builtin::BI__sync_lock_release_2:
1631   case Builtin::BI__sync_lock_release_4:
1632   case Builtin::BI__sync_lock_release_8:
1633   case Builtin::BI__sync_lock_release_16:
1634   case Builtin::BI__sync_swap:
1635   case Builtin::BI__sync_swap_1:
1636   case Builtin::BI__sync_swap_2:
1637   case Builtin::BI__sync_swap_4:
1638   case Builtin::BI__sync_swap_8:
1639   case Builtin::BI__sync_swap_16:
1640     return SemaBuiltinAtomicOverloaded(TheCallResult);
1641   case Builtin::BI__sync_synchronize:
1642     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1643         << TheCall->getCallee()->getSourceRange();
1644     break;
1645   case Builtin::BI__builtin_nontemporal_load:
1646   case Builtin::BI__builtin_nontemporal_store:
1647     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1648 #define BUILTIN(ID, TYPE, ATTRS)
1649 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1650   case Builtin::BI##ID: \
1651     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1652 #include "clang/Basic/Builtins.def"
1653   case Builtin::BI__annotation:
1654     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1655       return ExprError();
1656     break;
1657   case Builtin::BI__builtin_annotation:
1658     if (SemaBuiltinAnnotation(*this, TheCall))
1659       return ExprError();
1660     break;
1661   case Builtin::BI__builtin_addressof:
1662     if (SemaBuiltinAddressof(*this, TheCall))
1663       return ExprError();
1664     break;
1665   case Builtin::BI__builtin_is_aligned:
1666   case Builtin::BI__builtin_align_up:
1667   case Builtin::BI__builtin_align_down:
1668     if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
1669       return ExprError();
1670     break;
1671   case Builtin::BI__builtin_add_overflow:
1672   case Builtin::BI__builtin_sub_overflow:
1673   case Builtin::BI__builtin_mul_overflow:
1674     if (SemaBuiltinOverflow(*this, TheCall))
1675       return ExprError();
1676     break;
1677   case Builtin::BI__builtin_operator_new:
1678   case Builtin::BI__builtin_operator_delete: {
1679     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1680     ExprResult Res =
1681         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1682     if (Res.isInvalid())
1683       CorrectDelayedTyposInExpr(TheCallResult.get());
1684     return Res;
1685   }
1686   case Builtin::BI__builtin_dump_struct: {
1687     // We first want to ensure we are called with 2 arguments
1688     if (checkArgCount(*this, TheCall, 2))
1689       return ExprError();
1690     // Ensure that the first argument is of type 'struct XX *'
1691     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1692     const QualType PtrArgType = PtrArg->getType();
1693     if (!PtrArgType->isPointerType() ||
1694         !PtrArgType->getPointeeType()->isRecordType()) {
1695       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1696           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1697           << "structure pointer";
1698       return ExprError();
1699     }
1700 
1701     // Ensure that the second argument is of type 'FunctionType'
1702     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1703     const QualType FnPtrArgType = FnPtrArg->getType();
1704     if (!FnPtrArgType->isPointerType()) {
1705       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1706           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1707           << FnPtrArgType << "'int (*)(const char *, ...)'";
1708       return ExprError();
1709     }
1710 
1711     const auto *FuncType =
1712         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1713 
1714     if (!FuncType) {
1715       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1716           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1717           << FnPtrArgType << "'int (*)(const char *, ...)'";
1718       return ExprError();
1719     }
1720 
1721     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1722       if (!FT->getNumParams()) {
1723         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1724             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1725             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1726         return ExprError();
1727       }
1728       QualType PT = FT->getParamType(0);
1729       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1730           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1731           !PT->getPointeeType().isConstQualified()) {
1732         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1733             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1734             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1735         return ExprError();
1736       }
1737     }
1738 
1739     TheCall->setType(Context.IntTy);
1740     break;
1741   }
1742   case Builtin::BI__builtin_preserve_access_index:
1743     if (SemaBuiltinPreserveAI(*this, TheCall))
1744       return ExprError();
1745     break;
1746   case Builtin::BI__builtin_call_with_static_chain:
1747     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1748       return ExprError();
1749     break;
1750   case Builtin::BI__exception_code:
1751   case Builtin::BI_exception_code:
1752     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1753                                  diag::err_seh___except_block))
1754       return ExprError();
1755     break;
1756   case Builtin::BI__exception_info:
1757   case Builtin::BI_exception_info:
1758     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1759                                  diag::err_seh___except_filter))
1760       return ExprError();
1761     break;
1762   case Builtin::BI__GetExceptionInfo:
1763     if (checkArgCount(*this, TheCall, 1))
1764       return ExprError();
1765 
1766     if (CheckCXXThrowOperand(
1767             TheCall->getBeginLoc(),
1768             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1769             TheCall))
1770       return ExprError();
1771 
1772     TheCall->setType(Context.VoidPtrTy);
1773     break;
1774   // OpenCL v2.0, s6.13.16 - Pipe functions
1775   case Builtin::BIread_pipe:
1776   case Builtin::BIwrite_pipe:
1777     // Since those two functions are declared with var args, we need a semantic
1778     // check for the argument.
1779     if (SemaBuiltinRWPipe(*this, TheCall))
1780       return ExprError();
1781     break;
1782   case Builtin::BIreserve_read_pipe:
1783   case Builtin::BIreserve_write_pipe:
1784   case Builtin::BIwork_group_reserve_read_pipe:
1785   case Builtin::BIwork_group_reserve_write_pipe:
1786     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1787       return ExprError();
1788     break;
1789   case Builtin::BIsub_group_reserve_read_pipe:
1790   case Builtin::BIsub_group_reserve_write_pipe:
1791     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1792         SemaBuiltinReserveRWPipe(*this, TheCall))
1793       return ExprError();
1794     break;
1795   case Builtin::BIcommit_read_pipe:
1796   case Builtin::BIcommit_write_pipe:
1797   case Builtin::BIwork_group_commit_read_pipe:
1798   case Builtin::BIwork_group_commit_write_pipe:
1799     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1800       return ExprError();
1801     break;
1802   case Builtin::BIsub_group_commit_read_pipe:
1803   case Builtin::BIsub_group_commit_write_pipe:
1804     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1805         SemaBuiltinCommitRWPipe(*this, TheCall))
1806       return ExprError();
1807     break;
1808   case Builtin::BIget_pipe_num_packets:
1809   case Builtin::BIget_pipe_max_packets:
1810     if (SemaBuiltinPipePackets(*this, TheCall))
1811       return ExprError();
1812     break;
1813   case Builtin::BIto_global:
1814   case Builtin::BIto_local:
1815   case Builtin::BIto_private:
1816     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1817       return ExprError();
1818     break;
1819   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1820   case Builtin::BIenqueue_kernel:
1821     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1822       return ExprError();
1823     break;
1824   case Builtin::BIget_kernel_work_group_size:
1825   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1826     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1827       return ExprError();
1828     break;
1829   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1830   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1831     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1832       return ExprError();
1833     break;
1834   case Builtin::BI__builtin_os_log_format:
1835   case Builtin::BI__builtin_os_log_format_buffer_size:
1836     if (SemaBuiltinOSLogFormat(TheCall))
1837       return ExprError();
1838     break;
1839   }
1840 
1841   // Since the target specific builtins for each arch overlap, only check those
1842   // of the arch we are compiling for.
1843   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1844     switch (Context.getTargetInfo().getTriple().getArch()) {
1845       case llvm::Triple::arm:
1846       case llvm::Triple::armeb:
1847       case llvm::Triple::thumb:
1848       case llvm::Triple::thumbeb:
1849         if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1850           return ExprError();
1851         break;
1852       case llvm::Triple::aarch64:
1853       case llvm::Triple::aarch64_32:
1854       case llvm::Triple::aarch64_be:
1855         if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
1856           return ExprError();
1857         break;
1858       case llvm::Triple::bpfeb:
1859       case llvm::Triple::bpfel:
1860         if (CheckBPFBuiltinFunctionCall(BuiltinID, TheCall))
1861           return ExprError();
1862         break;
1863       case llvm::Triple::hexagon:
1864         if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall))
1865           return ExprError();
1866         break;
1867       case llvm::Triple::mips:
1868       case llvm::Triple::mipsel:
1869       case llvm::Triple::mips64:
1870       case llvm::Triple::mips64el:
1871         if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1872           return ExprError();
1873         break;
1874       case llvm::Triple::systemz:
1875         if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1876           return ExprError();
1877         break;
1878       case llvm::Triple::x86:
1879       case llvm::Triple::x86_64:
1880         if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1881           return ExprError();
1882         break;
1883       case llvm::Triple::ppc:
1884       case llvm::Triple::ppc64:
1885       case llvm::Triple::ppc64le:
1886         if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1887           return ExprError();
1888         break;
1889       default:
1890         break;
1891     }
1892   }
1893 
1894   return TheCallResult;
1895 }
1896 
1897 // Get the valid immediate range for the specified NEON type code.
1898 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1899   NeonTypeFlags Type(t);
1900   int IsQuad = ForceQuad ? true : Type.isQuad();
1901   switch (Type.getEltType()) {
1902   case NeonTypeFlags::Int8:
1903   case NeonTypeFlags::Poly8:
1904     return shift ? 7 : (8 << IsQuad) - 1;
1905   case NeonTypeFlags::Int16:
1906   case NeonTypeFlags::Poly16:
1907     return shift ? 15 : (4 << IsQuad) - 1;
1908   case NeonTypeFlags::Int32:
1909     return shift ? 31 : (2 << IsQuad) - 1;
1910   case NeonTypeFlags::Int64:
1911   case NeonTypeFlags::Poly64:
1912     return shift ? 63 : (1 << IsQuad) - 1;
1913   case NeonTypeFlags::Poly128:
1914     return shift ? 127 : (1 << IsQuad) - 1;
1915   case NeonTypeFlags::Float16:
1916     assert(!shift && "cannot shift float types!");
1917     return (4 << IsQuad) - 1;
1918   case NeonTypeFlags::Float32:
1919     assert(!shift && "cannot shift float types!");
1920     return (2 << IsQuad) - 1;
1921   case NeonTypeFlags::Float64:
1922     assert(!shift && "cannot shift float types!");
1923     return (1 << IsQuad) - 1;
1924   }
1925   llvm_unreachable("Invalid NeonTypeFlag!");
1926 }
1927 
1928 /// getNeonEltType - Return the QualType corresponding to the elements of
1929 /// the vector type specified by the NeonTypeFlags.  This is used to check
1930 /// the pointer arguments for Neon load/store intrinsics.
1931 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
1932                                bool IsPolyUnsigned, bool IsInt64Long) {
1933   switch (Flags.getEltType()) {
1934   case NeonTypeFlags::Int8:
1935     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1936   case NeonTypeFlags::Int16:
1937     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1938   case NeonTypeFlags::Int32:
1939     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1940   case NeonTypeFlags::Int64:
1941     if (IsInt64Long)
1942       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1943     else
1944       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1945                                 : Context.LongLongTy;
1946   case NeonTypeFlags::Poly8:
1947     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
1948   case NeonTypeFlags::Poly16:
1949     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
1950   case NeonTypeFlags::Poly64:
1951     if (IsInt64Long)
1952       return Context.UnsignedLongTy;
1953     else
1954       return Context.UnsignedLongLongTy;
1955   case NeonTypeFlags::Poly128:
1956     break;
1957   case NeonTypeFlags::Float16:
1958     return Context.HalfTy;
1959   case NeonTypeFlags::Float32:
1960     return Context.FloatTy;
1961   case NeonTypeFlags::Float64:
1962     return Context.DoubleTy;
1963   }
1964   llvm_unreachable("Invalid NeonTypeFlag!");
1965 }
1966 
1967 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1968   llvm::APSInt Result;
1969   uint64_t mask = 0;
1970   unsigned TV = 0;
1971   int PtrArgNum = -1;
1972   bool HasConstPtr = false;
1973   switch (BuiltinID) {
1974 #define GET_NEON_OVERLOAD_CHECK
1975 #include "clang/Basic/arm_neon.inc"
1976 #include "clang/Basic/arm_fp16.inc"
1977 #undef GET_NEON_OVERLOAD_CHECK
1978   }
1979 
1980   // For NEON intrinsics which are overloaded on vector element type, validate
1981   // the immediate which specifies which variant to emit.
1982   unsigned ImmArg = TheCall->getNumArgs()-1;
1983   if (mask) {
1984     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1985       return true;
1986 
1987     TV = Result.getLimitedValue(64);
1988     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1989       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
1990              << TheCall->getArg(ImmArg)->getSourceRange();
1991   }
1992 
1993   if (PtrArgNum >= 0) {
1994     // Check that pointer arguments have the specified type.
1995     Expr *Arg = TheCall->getArg(PtrArgNum);
1996     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1997       Arg = ICE->getSubExpr();
1998     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1999     QualType RHSTy = RHS.get()->getType();
2000 
2001     llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
2002     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2003                           Arch == llvm::Triple::aarch64_32 ||
2004                           Arch == llvm::Triple::aarch64_be;
2005     bool IsInt64Long =
2006         Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
2007     QualType EltTy =
2008         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2009     if (HasConstPtr)
2010       EltTy = EltTy.withConst();
2011     QualType LHSTy = Context.getPointerType(EltTy);
2012     AssignConvertType ConvTy;
2013     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2014     if (RHS.isInvalid())
2015       return true;
2016     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2017                                  RHS.get(), AA_Assigning))
2018       return true;
2019   }
2020 
2021   // For NEON intrinsics which take an immediate value as part of the
2022   // instruction, range check them here.
2023   unsigned i = 0, l = 0, u = 0;
2024   switch (BuiltinID) {
2025   default:
2026     return false;
2027   #define GET_NEON_IMMEDIATE_CHECK
2028   #include "clang/Basic/arm_neon.inc"
2029   #include "clang/Basic/arm_fp16.inc"
2030   #undef GET_NEON_IMMEDIATE_CHECK
2031   }
2032 
2033   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2034 }
2035 
2036 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2037   switch (BuiltinID) {
2038   default:
2039     return false;
2040   #include "clang/Basic/arm_mve_builtin_sema.inc"
2041   }
2042 }
2043 
2044 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2045                                         unsigned MaxWidth) {
2046   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
2047           BuiltinID == ARM::BI__builtin_arm_ldaex ||
2048           BuiltinID == ARM::BI__builtin_arm_strex ||
2049           BuiltinID == ARM::BI__builtin_arm_stlex ||
2050           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2051           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2052           BuiltinID == AArch64::BI__builtin_arm_strex ||
2053           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
2054          "unexpected ARM builtin");
2055   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2056                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
2057                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2058                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
2059 
2060   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2061 
2062   // Ensure that we have the proper number of arguments.
2063   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
2064     return true;
2065 
2066   // Inspect the pointer argument of the atomic builtin.  This should always be
2067   // a pointer type, whose element is an integral scalar or pointer type.
2068   // Because it is a pointer type, we don't have to worry about any implicit
2069   // casts here.
2070   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
2071   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
2072   if (PointerArgRes.isInvalid())
2073     return true;
2074   PointerArg = PointerArgRes.get();
2075 
2076   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2077   if (!pointerType) {
2078     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
2079         << PointerArg->getType() << PointerArg->getSourceRange();
2080     return true;
2081   }
2082 
2083   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
2084   // task is to insert the appropriate casts into the AST. First work out just
2085   // what the appropriate type is.
2086   QualType ValType = pointerType->getPointeeType();
2087   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
2088   if (IsLdrex)
2089     AddrType.addConst();
2090 
2091   // Issue a warning if the cast is dodgy.
2092   CastKind CastNeeded = CK_NoOp;
2093   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
2094     CastNeeded = CK_BitCast;
2095     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
2096         << PointerArg->getType() << Context.getPointerType(AddrType)
2097         << AA_Passing << PointerArg->getSourceRange();
2098   }
2099 
2100   // Finally, do the cast and replace the argument with the corrected version.
2101   AddrType = Context.getPointerType(AddrType);
2102   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
2103   if (PointerArgRes.isInvalid())
2104     return true;
2105   PointerArg = PointerArgRes.get();
2106 
2107   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
2108 
2109   // In general, we allow ints, floats and pointers to be loaded and stored.
2110   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2111       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
2112     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
2113         << PointerArg->getType() << PointerArg->getSourceRange();
2114     return true;
2115   }
2116 
2117   // But ARM doesn't have instructions to deal with 128-bit versions.
2118   if (Context.getTypeSize(ValType) > MaxWidth) {
2119     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
2120     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
2121         << PointerArg->getType() << PointerArg->getSourceRange();
2122     return true;
2123   }
2124 
2125   switch (ValType.getObjCLifetime()) {
2126   case Qualifiers::OCL_None:
2127   case Qualifiers::OCL_ExplicitNone:
2128     // okay
2129     break;
2130 
2131   case Qualifiers::OCL_Weak:
2132   case Qualifiers::OCL_Strong:
2133   case Qualifiers::OCL_Autoreleasing:
2134     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
2135         << ValType << PointerArg->getSourceRange();
2136     return true;
2137   }
2138 
2139   if (IsLdrex) {
2140     TheCall->setType(ValType);
2141     return false;
2142   }
2143 
2144   // Initialize the argument to be stored.
2145   ExprResult ValArg = TheCall->getArg(0);
2146   InitializedEntity Entity = InitializedEntity::InitializeParameter(
2147       Context, ValType, /*consume*/ false);
2148   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2149   if (ValArg.isInvalid())
2150     return true;
2151   TheCall->setArg(0, ValArg.get());
2152 
2153   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
2154   // but the custom checker bypasses all default analysis.
2155   TheCall->setType(Context.IntTy);
2156   return false;
2157 }
2158 
2159 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2160   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
2161       BuiltinID == ARM::BI__builtin_arm_ldaex ||
2162       BuiltinID == ARM::BI__builtin_arm_strex ||
2163       BuiltinID == ARM::BI__builtin_arm_stlex) {
2164     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
2165   }
2166 
2167   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
2168     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2169       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
2170   }
2171 
2172   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2173       BuiltinID == ARM::BI__builtin_arm_wsr64)
2174     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
2175 
2176   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
2177       BuiltinID == ARM::BI__builtin_arm_rsrp ||
2178       BuiltinID == ARM::BI__builtin_arm_wsr ||
2179       BuiltinID == ARM::BI__builtin_arm_wsrp)
2180     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2181 
2182   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
2183     return true;
2184   if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
2185     return true;
2186 
2187   // For intrinsics which take an immediate value as part of the instruction,
2188   // range check them here.
2189   // FIXME: VFP Intrinsics should error if VFP not present.
2190   switch (BuiltinID) {
2191   default: return false;
2192   case ARM::BI__builtin_arm_ssat:
2193     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
2194   case ARM::BI__builtin_arm_usat:
2195     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
2196   case ARM::BI__builtin_arm_ssat16:
2197     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
2198   case ARM::BI__builtin_arm_usat16:
2199     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2200   case ARM::BI__builtin_arm_vcvtr_f:
2201   case ARM::BI__builtin_arm_vcvtr_d:
2202     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2203   case ARM::BI__builtin_arm_dmb:
2204   case ARM::BI__builtin_arm_dsb:
2205   case ARM::BI__builtin_arm_isb:
2206   case ARM::BI__builtin_arm_dbg:
2207     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
2208   }
2209 }
2210 
2211 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
2212                                          CallExpr *TheCall) {
2213   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2214       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2215       BuiltinID == AArch64::BI__builtin_arm_strex ||
2216       BuiltinID == AArch64::BI__builtin_arm_stlex) {
2217     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
2218   }
2219 
2220   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
2221     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2222       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
2223       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2224       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2225   }
2226 
2227   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2228       BuiltinID == AArch64::BI__builtin_arm_wsr64)
2229     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2230 
2231   // Memory Tagging Extensions (MTE) Intrinsics
2232   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2233       BuiltinID == AArch64::BI__builtin_arm_addg ||
2234       BuiltinID == AArch64::BI__builtin_arm_gmi ||
2235       BuiltinID == AArch64::BI__builtin_arm_ldg ||
2236       BuiltinID == AArch64::BI__builtin_arm_stg ||
2237       BuiltinID == AArch64::BI__builtin_arm_subp) {
2238     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2239   }
2240 
2241   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2242       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2243       BuiltinID == AArch64::BI__builtin_arm_wsr ||
2244       BuiltinID == AArch64::BI__builtin_arm_wsrp)
2245     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2246 
2247   // Only check the valid encoding range. Any constant in this range would be
2248   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2249   // an exception for incorrect registers. This matches MSVC behavior.
2250   if (BuiltinID == AArch64::BI_ReadStatusReg ||
2251       BuiltinID == AArch64::BI_WriteStatusReg)
2252     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2253 
2254   if (BuiltinID == AArch64::BI__getReg)
2255     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2256 
2257   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
2258     return true;
2259 
2260   // For intrinsics which take an immediate value as part of the instruction,
2261   // range check them here.
2262   unsigned i = 0, l = 0, u = 0;
2263   switch (BuiltinID) {
2264   default: return false;
2265   case AArch64::BI__builtin_arm_dmb:
2266   case AArch64::BI__builtin_arm_dsb:
2267   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2268   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2269   }
2270 
2271   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2272 }
2273 
2274 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
2275                                        CallExpr *TheCall) {
2276   assert(BuiltinID == BPF::BI__builtin_preserve_field_info &&
2277          "unexpected ARM builtin");
2278 
2279   if (checkArgCount(*this, TheCall, 2))
2280     return true;
2281 
2282   // The first argument needs to be a record field access.
2283   // If it is an array element access, we delay decision
2284   // to BPF backend to check whether the access is a
2285   // field access or not.
2286   Expr *Arg = TheCall->getArg(0);
2287   if (Arg->getType()->getAsPlaceholderType() ||
2288       (Arg->IgnoreParens()->getObjectKind() != OK_BitField &&
2289        !dyn_cast<MemberExpr>(Arg->IgnoreParens()) &&
2290        !dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()))) {
2291     Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_field)
2292         << 1 << Arg->getSourceRange();
2293     return true;
2294   }
2295 
2296   // The second argument needs to be a constant int
2297   llvm::APSInt Value;
2298   if (!TheCall->getArg(1)->isIntegerConstantExpr(Value, Context)) {
2299     Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_const)
2300         << 2 << Arg->getSourceRange();
2301     return true;
2302   }
2303 
2304   TheCall->setType(Context.UnsignedIntTy);
2305   return false;
2306 }
2307 
2308 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2309   struct ArgInfo {
2310     uint8_t OpNum;
2311     bool IsSigned;
2312     uint8_t BitWidth;
2313     uint8_t Align;
2314   };
2315   struct BuiltinInfo {
2316     unsigned BuiltinID;
2317     ArgInfo Infos[2];
2318   };
2319 
2320   static BuiltinInfo Infos[] = {
2321     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2322     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2323     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2324     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  1 }} },
2325     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2326     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2327     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2328     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2329     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2330     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2331     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2332 
2333     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2334     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2335     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2336     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2337     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2338     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2339     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2340     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2341     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2342     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2343     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2344 
2345     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2346     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2347     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2348     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2349     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2350     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2351     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2352     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2353     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2354     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2355     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2356     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2357     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2358     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2359     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2360     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2361     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2362     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2363     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2364     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2365     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2366     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2367     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2368     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2369     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2370     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2371     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2372     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2373     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2374     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2375     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2376     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
2377     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
2378     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
2379     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
2380     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
2381     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
2382     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
2383     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
2384     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
2385     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
2386     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
2387     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
2388     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
2389     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
2390     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
2391     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
2392     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
2393     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
2394     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
2395     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
2396     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2397                                                       {{ 1, false, 6,  0 }} },
2398     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
2399     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
2400     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
2401     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
2402     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
2403     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
2404     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2405                                                       {{ 1, false, 5,  0 }} },
2406     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
2407     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
2408     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
2409     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
2410     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
2411     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
2412                                                        { 2, false, 5,  0 }} },
2413     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
2414                                                        { 2, false, 6,  0 }} },
2415     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
2416                                                        { 3, false, 5,  0 }} },
2417     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
2418                                                        { 3, false, 6,  0 }} },
2419     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
2420     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
2421     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
2422     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
2423     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
2424     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
2425     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
2426     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
2427     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
2428     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
2429     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
2430     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
2431     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
2432     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
2433     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
2434     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2435                                                       {{ 2, false, 4,  0 },
2436                                                        { 3, false, 5,  0 }} },
2437     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2438                                                       {{ 2, false, 4,  0 },
2439                                                        { 3, false, 5,  0 }} },
2440     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2441                                                       {{ 2, false, 4,  0 },
2442                                                        { 3, false, 5,  0 }} },
2443     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2444                                                       {{ 2, false, 4,  0 },
2445                                                        { 3, false, 5,  0 }} },
2446     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
2447     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
2448     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
2449     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
2450     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
2451     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
2452     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
2453     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
2454     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
2455     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
2456     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
2457                                                        { 2, false, 5,  0 }} },
2458     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
2459                                                        { 2, false, 6,  0 }} },
2460     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
2461     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
2462     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
2463     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
2464     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
2465     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
2466     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
2467     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
2468     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2469                                                       {{ 1, false, 4,  0 }} },
2470     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
2471     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2472                                                       {{ 1, false, 4,  0 }} },
2473     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
2474     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
2475     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
2476     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
2477     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
2478     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
2479     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
2480     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
2481     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
2482     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
2483     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
2484     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
2485     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
2486     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
2487     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
2488     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
2489     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
2490     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
2491     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
2492     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2493                                                       {{ 3, false, 1,  0 }} },
2494     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
2495     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
2496     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
2497     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2498                                                       {{ 3, false, 1,  0 }} },
2499     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
2500     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
2501     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
2502     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2503                                                       {{ 3, false, 1,  0 }} },
2504   };
2505 
2506   // Use a dynamically initialized static to sort the table exactly once on
2507   // first run.
2508   static const bool SortOnce =
2509       (llvm::sort(Infos,
2510                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
2511                    return LHS.BuiltinID < RHS.BuiltinID;
2512                  }),
2513        true);
2514   (void)SortOnce;
2515 
2516   const BuiltinInfo *F = llvm::partition_point(
2517       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
2518   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
2519     return false;
2520 
2521   bool Error = false;
2522 
2523   for (const ArgInfo &A : F->Infos) {
2524     // Ignore empty ArgInfo elements.
2525     if (A.BitWidth == 0)
2526       continue;
2527 
2528     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
2529     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
2530     if (!A.Align) {
2531       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2532     } else {
2533       unsigned M = 1 << A.Align;
2534       Min *= M;
2535       Max *= M;
2536       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
2537                SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
2538     }
2539   }
2540   return Error;
2541 }
2542 
2543 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
2544                                            CallExpr *TheCall) {
2545   return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
2546 }
2547 
2548 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2549   return CheckMipsBuiltinCpu(BuiltinID, TheCall) ||
2550          CheckMipsBuiltinArgument(BuiltinID, TheCall);
2551 }
2552 
2553 bool Sema::CheckMipsBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) {
2554   const TargetInfo &TI = Context.getTargetInfo();
2555 
2556   if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
2557       BuiltinID <= Mips::BI__builtin_mips_lwx) {
2558     if (!TI.hasFeature("dsp"))
2559       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
2560   }
2561 
2562   if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
2563       BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
2564     if (!TI.hasFeature("dspr2"))
2565       return Diag(TheCall->getBeginLoc(),
2566                   diag::err_mips_builtin_requires_dspr2);
2567   }
2568 
2569   if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
2570       BuiltinID <= Mips::BI__builtin_msa_xori_b) {
2571     if (!TI.hasFeature("msa"))
2572       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
2573   }
2574 
2575   return false;
2576 }
2577 
2578 // CheckMipsBuiltinArgument - Checks the constant value passed to the
2579 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
2580 // ordering for DSP is unspecified. MSA is ordered by the data format used
2581 // by the underlying instruction i.e., df/m, df/n and then by size.
2582 //
2583 // FIXME: The size tests here should instead be tablegen'd along with the
2584 //        definitions from include/clang/Basic/BuiltinsMips.def.
2585 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
2586 //        be too.
2587 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2588   unsigned i = 0, l = 0, u = 0, m = 0;
2589   switch (BuiltinID) {
2590   default: return false;
2591   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
2592   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
2593   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
2594   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
2595   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
2596   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
2597   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
2598   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
2599   // df/m field.
2600   // These intrinsics take an unsigned 3 bit immediate.
2601   case Mips::BI__builtin_msa_bclri_b:
2602   case Mips::BI__builtin_msa_bnegi_b:
2603   case Mips::BI__builtin_msa_bseti_b:
2604   case Mips::BI__builtin_msa_sat_s_b:
2605   case Mips::BI__builtin_msa_sat_u_b:
2606   case Mips::BI__builtin_msa_slli_b:
2607   case Mips::BI__builtin_msa_srai_b:
2608   case Mips::BI__builtin_msa_srari_b:
2609   case Mips::BI__builtin_msa_srli_b:
2610   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
2611   case Mips::BI__builtin_msa_binsli_b:
2612   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
2613   // These intrinsics take an unsigned 4 bit immediate.
2614   case Mips::BI__builtin_msa_bclri_h:
2615   case Mips::BI__builtin_msa_bnegi_h:
2616   case Mips::BI__builtin_msa_bseti_h:
2617   case Mips::BI__builtin_msa_sat_s_h:
2618   case Mips::BI__builtin_msa_sat_u_h:
2619   case Mips::BI__builtin_msa_slli_h:
2620   case Mips::BI__builtin_msa_srai_h:
2621   case Mips::BI__builtin_msa_srari_h:
2622   case Mips::BI__builtin_msa_srli_h:
2623   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
2624   case Mips::BI__builtin_msa_binsli_h:
2625   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
2626   // These intrinsics take an unsigned 5 bit immediate.
2627   // The first block of intrinsics actually have an unsigned 5 bit field,
2628   // not a df/n field.
2629   case Mips::BI__builtin_msa_cfcmsa:
2630   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
2631   case Mips::BI__builtin_msa_clei_u_b:
2632   case Mips::BI__builtin_msa_clei_u_h:
2633   case Mips::BI__builtin_msa_clei_u_w:
2634   case Mips::BI__builtin_msa_clei_u_d:
2635   case Mips::BI__builtin_msa_clti_u_b:
2636   case Mips::BI__builtin_msa_clti_u_h:
2637   case Mips::BI__builtin_msa_clti_u_w:
2638   case Mips::BI__builtin_msa_clti_u_d:
2639   case Mips::BI__builtin_msa_maxi_u_b:
2640   case Mips::BI__builtin_msa_maxi_u_h:
2641   case Mips::BI__builtin_msa_maxi_u_w:
2642   case Mips::BI__builtin_msa_maxi_u_d:
2643   case Mips::BI__builtin_msa_mini_u_b:
2644   case Mips::BI__builtin_msa_mini_u_h:
2645   case Mips::BI__builtin_msa_mini_u_w:
2646   case Mips::BI__builtin_msa_mini_u_d:
2647   case Mips::BI__builtin_msa_addvi_b:
2648   case Mips::BI__builtin_msa_addvi_h:
2649   case Mips::BI__builtin_msa_addvi_w:
2650   case Mips::BI__builtin_msa_addvi_d:
2651   case Mips::BI__builtin_msa_bclri_w:
2652   case Mips::BI__builtin_msa_bnegi_w:
2653   case Mips::BI__builtin_msa_bseti_w:
2654   case Mips::BI__builtin_msa_sat_s_w:
2655   case Mips::BI__builtin_msa_sat_u_w:
2656   case Mips::BI__builtin_msa_slli_w:
2657   case Mips::BI__builtin_msa_srai_w:
2658   case Mips::BI__builtin_msa_srari_w:
2659   case Mips::BI__builtin_msa_srli_w:
2660   case Mips::BI__builtin_msa_srlri_w:
2661   case Mips::BI__builtin_msa_subvi_b:
2662   case Mips::BI__builtin_msa_subvi_h:
2663   case Mips::BI__builtin_msa_subvi_w:
2664   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
2665   case Mips::BI__builtin_msa_binsli_w:
2666   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
2667   // These intrinsics take an unsigned 6 bit immediate.
2668   case Mips::BI__builtin_msa_bclri_d:
2669   case Mips::BI__builtin_msa_bnegi_d:
2670   case Mips::BI__builtin_msa_bseti_d:
2671   case Mips::BI__builtin_msa_sat_s_d:
2672   case Mips::BI__builtin_msa_sat_u_d:
2673   case Mips::BI__builtin_msa_slli_d:
2674   case Mips::BI__builtin_msa_srai_d:
2675   case Mips::BI__builtin_msa_srari_d:
2676   case Mips::BI__builtin_msa_srli_d:
2677   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
2678   case Mips::BI__builtin_msa_binsli_d:
2679   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
2680   // These intrinsics take a signed 5 bit immediate.
2681   case Mips::BI__builtin_msa_ceqi_b:
2682   case Mips::BI__builtin_msa_ceqi_h:
2683   case Mips::BI__builtin_msa_ceqi_w:
2684   case Mips::BI__builtin_msa_ceqi_d:
2685   case Mips::BI__builtin_msa_clti_s_b:
2686   case Mips::BI__builtin_msa_clti_s_h:
2687   case Mips::BI__builtin_msa_clti_s_w:
2688   case Mips::BI__builtin_msa_clti_s_d:
2689   case Mips::BI__builtin_msa_clei_s_b:
2690   case Mips::BI__builtin_msa_clei_s_h:
2691   case Mips::BI__builtin_msa_clei_s_w:
2692   case Mips::BI__builtin_msa_clei_s_d:
2693   case Mips::BI__builtin_msa_maxi_s_b:
2694   case Mips::BI__builtin_msa_maxi_s_h:
2695   case Mips::BI__builtin_msa_maxi_s_w:
2696   case Mips::BI__builtin_msa_maxi_s_d:
2697   case Mips::BI__builtin_msa_mini_s_b:
2698   case Mips::BI__builtin_msa_mini_s_h:
2699   case Mips::BI__builtin_msa_mini_s_w:
2700   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
2701   // These intrinsics take an unsigned 8 bit immediate.
2702   case Mips::BI__builtin_msa_andi_b:
2703   case Mips::BI__builtin_msa_nori_b:
2704   case Mips::BI__builtin_msa_ori_b:
2705   case Mips::BI__builtin_msa_shf_b:
2706   case Mips::BI__builtin_msa_shf_h:
2707   case Mips::BI__builtin_msa_shf_w:
2708   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
2709   case Mips::BI__builtin_msa_bseli_b:
2710   case Mips::BI__builtin_msa_bmnzi_b:
2711   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
2712   // df/n format
2713   // These intrinsics take an unsigned 4 bit immediate.
2714   case Mips::BI__builtin_msa_copy_s_b:
2715   case Mips::BI__builtin_msa_copy_u_b:
2716   case Mips::BI__builtin_msa_insve_b:
2717   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
2718   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
2719   // These intrinsics take an unsigned 3 bit immediate.
2720   case Mips::BI__builtin_msa_copy_s_h:
2721   case Mips::BI__builtin_msa_copy_u_h:
2722   case Mips::BI__builtin_msa_insve_h:
2723   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
2724   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
2725   // These intrinsics take an unsigned 2 bit immediate.
2726   case Mips::BI__builtin_msa_copy_s_w:
2727   case Mips::BI__builtin_msa_copy_u_w:
2728   case Mips::BI__builtin_msa_insve_w:
2729   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
2730   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
2731   // These intrinsics take an unsigned 1 bit immediate.
2732   case Mips::BI__builtin_msa_copy_s_d:
2733   case Mips::BI__builtin_msa_copy_u_d:
2734   case Mips::BI__builtin_msa_insve_d:
2735   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
2736   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
2737   // Memory offsets and immediate loads.
2738   // These intrinsics take a signed 10 bit immediate.
2739   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
2740   case Mips::BI__builtin_msa_ldi_h:
2741   case Mips::BI__builtin_msa_ldi_w:
2742   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
2743   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
2744   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
2745   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
2746   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
2747   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
2748   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
2749   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
2750   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
2751   }
2752 
2753   if (!m)
2754     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2755 
2756   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
2757          SemaBuiltinConstantArgMultiple(TheCall, i, m);
2758 }
2759 
2760 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2761   unsigned i = 0, l = 0, u = 0;
2762   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
2763                       BuiltinID == PPC::BI__builtin_divdeu ||
2764                       BuiltinID == PPC::BI__builtin_bpermd;
2765   bool IsTarget64Bit = Context.getTargetInfo()
2766                               .getTypeWidth(Context
2767                                             .getTargetInfo()
2768                                             .getIntPtrType()) == 64;
2769   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
2770                        BuiltinID == PPC::BI__builtin_divweu ||
2771                        BuiltinID == PPC::BI__builtin_divde ||
2772                        BuiltinID == PPC::BI__builtin_divdeu;
2773 
2774   if (Is64BitBltin && !IsTarget64Bit)
2775     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
2776            << TheCall->getSourceRange();
2777 
2778   if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
2779       (BuiltinID == PPC::BI__builtin_bpermd &&
2780        !Context.getTargetInfo().hasFeature("bpermd")))
2781     return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
2782            << TheCall->getSourceRange();
2783 
2784   auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
2785     if (!Context.getTargetInfo().hasFeature("vsx"))
2786       return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
2787              << TheCall->getSourceRange();
2788     return false;
2789   };
2790 
2791   switch (BuiltinID) {
2792   default: return false;
2793   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
2794   case PPC::BI__builtin_altivec_crypto_vshasigmad:
2795     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2796            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
2797   case PPC::BI__builtin_altivec_dss:
2798     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
2799   case PPC::BI__builtin_tbegin:
2800   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
2801   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
2802   case PPC::BI__builtin_tabortwc:
2803   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
2804   case PPC::BI__builtin_tabortwci:
2805   case PPC::BI__builtin_tabortdci:
2806     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
2807            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
2808   case PPC::BI__builtin_altivec_dst:
2809   case PPC::BI__builtin_altivec_dstt:
2810   case PPC::BI__builtin_altivec_dstst:
2811   case PPC::BI__builtin_altivec_dststt:
2812     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
2813   case PPC::BI__builtin_vsx_xxpermdi:
2814   case PPC::BI__builtin_vsx_xxsldwi:
2815     return SemaBuiltinVSX(TheCall);
2816   case PPC::BI__builtin_unpack_vector_int128:
2817     return SemaVSXCheck(TheCall) ||
2818            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2819   case PPC::BI__builtin_pack_vector_int128:
2820     return SemaVSXCheck(TheCall);
2821   }
2822   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2823 }
2824 
2825 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
2826                                            CallExpr *TheCall) {
2827   if (BuiltinID == SystemZ::BI__builtin_tabort) {
2828     Expr *Arg = TheCall->getArg(0);
2829     llvm::APSInt AbortCode(32);
2830     if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
2831         AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
2832       return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
2833              << Arg->getSourceRange();
2834   }
2835 
2836   // For intrinsics which take an immediate value as part of the instruction,
2837   // range check them here.
2838   unsigned i = 0, l = 0, u = 0;
2839   switch (BuiltinID) {
2840   default: return false;
2841   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
2842   case SystemZ::BI__builtin_s390_verimb:
2843   case SystemZ::BI__builtin_s390_verimh:
2844   case SystemZ::BI__builtin_s390_verimf:
2845   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
2846   case SystemZ::BI__builtin_s390_vfaeb:
2847   case SystemZ::BI__builtin_s390_vfaeh:
2848   case SystemZ::BI__builtin_s390_vfaef:
2849   case SystemZ::BI__builtin_s390_vfaebs:
2850   case SystemZ::BI__builtin_s390_vfaehs:
2851   case SystemZ::BI__builtin_s390_vfaefs:
2852   case SystemZ::BI__builtin_s390_vfaezb:
2853   case SystemZ::BI__builtin_s390_vfaezh:
2854   case SystemZ::BI__builtin_s390_vfaezf:
2855   case SystemZ::BI__builtin_s390_vfaezbs:
2856   case SystemZ::BI__builtin_s390_vfaezhs:
2857   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
2858   case SystemZ::BI__builtin_s390_vfisb:
2859   case SystemZ::BI__builtin_s390_vfidb:
2860     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
2861            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
2862   case SystemZ::BI__builtin_s390_vftcisb:
2863   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
2864   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
2865   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
2866   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
2867   case SystemZ::BI__builtin_s390_vstrcb:
2868   case SystemZ::BI__builtin_s390_vstrch:
2869   case SystemZ::BI__builtin_s390_vstrcf:
2870   case SystemZ::BI__builtin_s390_vstrczb:
2871   case SystemZ::BI__builtin_s390_vstrczh:
2872   case SystemZ::BI__builtin_s390_vstrczf:
2873   case SystemZ::BI__builtin_s390_vstrcbs:
2874   case SystemZ::BI__builtin_s390_vstrchs:
2875   case SystemZ::BI__builtin_s390_vstrcfs:
2876   case SystemZ::BI__builtin_s390_vstrczbs:
2877   case SystemZ::BI__builtin_s390_vstrczhs:
2878   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
2879   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
2880   case SystemZ::BI__builtin_s390_vfminsb:
2881   case SystemZ::BI__builtin_s390_vfmaxsb:
2882   case SystemZ::BI__builtin_s390_vfmindb:
2883   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
2884   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
2885   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
2886   }
2887   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2888 }
2889 
2890 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
2891 /// This checks that the target supports __builtin_cpu_supports and
2892 /// that the string argument is constant and valid.
2893 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
2894   Expr *Arg = TheCall->getArg(0);
2895 
2896   // Check if the argument is a string literal.
2897   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
2898     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
2899            << Arg->getSourceRange();
2900 
2901   // Check the contents of the string.
2902   StringRef Feature =
2903       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
2904   if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
2905     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
2906            << Arg->getSourceRange();
2907   return false;
2908 }
2909 
2910 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
2911 /// This checks that the target supports __builtin_cpu_is and
2912 /// that the string argument is constant and valid.
2913 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
2914   Expr *Arg = TheCall->getArg(0);
2915 
2916   // Check if the argument is a string literal.
2917   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
2918     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
2919            << Arg->getSourceRange();
2920 
2921   // Check the contents of the string.
2922   StringRef Feature =
2923       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
2924   if (!S.Context.getTargetInfo().validateCpuIs(Feature))
2925     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
2926            << Arg->getSourceRange();
2927   return false;
2928 }
2929 
2930 // Check if the rounding mode is legal.
2931 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
2932   // Indicates if this instruction has rounding control or just SAE.
2933   bool HasRC = false;
2934 
2935   unsigned ArgNum = 0;
2936   switch (BuiltinID) {
2937   default:
2938     return false;
2939   case X86::BI__builtin_ia32_vcvttsd2si32:
2940   case X86::BI__builtin_ia32_vcvttsd2si64:
2941   case X86::BI__builtin_ia32_vcvttsd2usi32:
2942   case X86::BI__builtin_ia32_vcvttsd2usi64:
2943   case X86::BI__builtin_ia32_vcvttss2si32:
2944   case X86::BI__builtin_ia32_vcvttss2si64:
2945   case X86::BI__builtin_ia32_vcvttss2usi32:
2946   case X86::BI__builtin_ia32_vcvttss2usi64:
2947     ArgNum = 1;
2948     break;
2949   case X86::BI__builtin_ia32_maxpd512:
2950   case X86::BI__builtin_ia32_maxps512:
2951   case X86::BI__builtin_ia32_minpd512:
2952   case X86::BI__builtin_ia32_minps512:
2953     ArgNum = 2;
2954     break;
2955   case X86::BI__builtin_ia32_cvtps2pd512_mask:
2956   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
2957   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
2958   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
2959   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
2960   case X86::BI__builtin_ia32_cvttps2dq512_mask:
2961   case X86::BI__builtin_ia32_cvttps2qq512_mask:
2962   case X86::BI__builtin_ia32_cvttps2udq512_mask:
2963   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
2964   case X86::BI__builtin_ia32_exp2pd_mask:
2965   case X86::BI__builtin_ia32_exp2ps_mask:
2966   case X86::BI__builtin_ia32_getexppd512_mask:
2967   case X86::BI__builtin_ia32_getexpps512_mask:
2968   case X86::BI__builtin_ia32_rcp28pd_mask:
2969   case X86::BI__builtin_ia32_rcp28ps_mask:
2970   case X86::BI__builtin_ia32_rsqrt28pd_mask:
2971   case X86::BI__builtin_ia32_rsqrt28ps_mask:
2972   case X86::BI__builtin_ia32_vcomisd:
2973   case X86::BI__builtin_ia32_vcomiss:
2974   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
2975     ArgNum = 3;
2976     break;
2977   case X86::BI__builtin_ia32_cmppd512_mask:
2978   case X86::BI__builtin_ia32_cmpps512_mask:
2979   case X86::BI__builtin_ia32_cmpsd_mask:
2980   case X86::BI__builtin_ia32_cmpss_mask:
2981   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
2982   case X86::BI__builtin_ia32_getexpsd128_round_mask:
2983   case X86::BI__builtin_ia32_getexpss128_round_mask:
2984   case X86::BI__builtin_ia32_getmantpd512_mask:
2985   case X86::BI__builtin_ia32_getmantps512_mask:
2986   case X86::BI__builtin_ia32_maxsd_round_mask:
2987   case X86::BI__builtin_ia32_maxss_round_mask:
2988   case X86::BI__builtin_ia32_minsd_round_mask:
2989   case X86::BI__builtin_ia32_minss_round_mask:
2990   case X86::BI__builtin_ia32_rcp28sd_round_mask:
2991   case X86::BI__builtin_ia32_rcp28ss_round_mask:
2992   case X86::BI__builtin_ia32_reducepd512_mask:
2993   case X86::BI__builtin_ia32_reduceps512_mask:
2994   case X86::BI__builtin_ia32_rndscalepd_mask:
2995   case X86::BI__builtin_ia32_rndscaleps_mask:
2996   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
2997   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
2998     ArgNum = 4;
2999     break;
3000   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3001   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3002   case X86::BI__builtin_ia32_fixupimmps512_mask:
3003   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3004   case X86::BI__builtin_ia32_fixupimmsd_mask:
3005   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3006   case X86::BI__builtin_ia32_fixupimmss_mask:
3007   case X86::BI__builtin_ia32_fixupimmss_maskz:
3008   case X86::BI__builtin_ia32_getmantsd_round_mask:
3009   case X86::BI__builtin_ia32_getmantss_round_mask:
3010   case X86::BI__builtin_ia32_rangepd512_mask:
3011   case X86::BI__builtin_ia32_rangeps512_mask:
3012   case X86::BI__builtin_ia32_rangesd128_round_mask:
3013   case X86::BI__builtin_ia32_rangess128_round_mask:
3014   case X86::BI__builtin_ia32_reducesd_mask:
3015   case X86::BI__builtin_ia32_reducess_mask:
3016   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3017   case X86::BI__builtin_ia32_rndscaless_round_mask:
3018     ArgNum = 5;
3019     break;
3020   case X86::BI__builtin_ia32_vcvtsd2si64:
3021   case X86::BI__builtin_ia32_vcvtsd2si32:
3022   case X86::BI__builtin_ia32_vcvtsd2usi32:
3023   case X86::BI__builtin_ia32_vcvtsd2usi64:
3024   case X86::BI__builtin_ia32_vcvtss2si32:
3025   case X86::BI__builtin_ia32_vcvtss2si64:
3026   case X86::BI__builtin_ia32_vcvtss2usi32:
3027   case X86::BI__builtin_ia32_vcvtss2usi64:
3028   case X86::BI__builtin_ia32_sqrtpd512:
3029   case X86::BI__builtin_ia32_sqrtps512:
3030     ArgNum = 1;
3031     HasRC = true;
3032     break;
3033   case X86::BI__builtin_ia32_addpd512:
3034   case X86::BI__builtin_ia32_addps512:
3035   case X86::BI__builtin_ia32_divpd512:
3036   case X86::BI__builtin_ia32_divps512:
3037   case X86::BI__builtin_ia32_mulpd512:
3038   case X86::BI__builtin_ia32_mulps512:
3039   case X86::BI__builtin_ia32_subpd512:
3040   case X86::BI__builtin_ia32_subps512:
3041   case X86::BI__builtin_ia32_cvtsi2sd64:
3042   case X86::BI__builtin_ia32_cvtsi2ss32:
3043   case X86::BI__builtin_ia32_cvtsi2ss64:
3044   case X86::BI__builtin_ia32_cvtusi2sd64:
3045   case X86::BI__builtin_ia32_cvtusi2ss32:
3046   case X86::BI__builtin_ia32_cvtusi2ss64:
3047     ArgNum = 2;
3048     HasRC = true;
3049     break;
3050   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3051   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3052   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
3053   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
3054   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3055   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
3056   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3057   case X86::BI__builtin_ia32_cvtps2dq512_mask:
3058   case X86::BI__builtin_ia32_cvtps2qq512_mask:
3059   case X86::BI__builtin_ia32_cvtps2udq512_mask:
3060   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3061   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3062   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3063   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3064   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3065     ArgNum = 3;
3066     HasRC = true;
3067     break;
3068   case X86::BI__builtin_ia32_addss_round_mask:
3069   case X86::BI__builtin_ia32_addsd_round_mask:
3070   case X86::BI__builtin_ia32_divss_round_mask:
3071   case X86::BI__builtin_ia32_divsd_round_mask:
3072   case X86::BI__builtin_ia32_mulss_round_mask:
3073   case X86::BI__builtin_ia32_mulsd_round_mask:
3074   case X86::BI__builtin_ia32_subss_round_mask:
3075   case X86::BI__builtin_ia32_subsd_round_mask:
3076   case X86::BI__builtin_ia32_scalefpd512_mask:
3077   case X86::BI__builtin_ia32_scalefps512_mask:
3078   case X86::BI__builtin_ia32_scalefsd_round_mask:
3079   case X86::BI__builtin_ia32_scalefss_round_mask:
3080   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3081   case X86::BI__builtin_ia32_sqrtsd_round_mask:
3082   case X86::BI__builtin_ia32_sqrtss_round_mask:
3083   case X86::BI__builtin_ia32_vfmaddsd3_mask:
3084   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3085   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
3086   case X86::BI__builtin_ia32_vfmaddss3_mask:
3087   case X86::BI__builtin_ia32_vfmaddss3_maskz:
3088   case X86::BI__builtin_ia32_vfmaddss3_mask3:
3089   case X86::BI__builtin_ia32_vfmaddpd512_mask:
3090   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
3091   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
3092   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
3093   case X86::BI__builtin_ia32_vfmaddps512_mask:
3094   case X86::BI__builtin_ia32_vfmaddps512_maskz:
3095   case X86::BI__builtin_ia32_vfmaddps512_mask3:
3096   case X86::BI__builtin_ia32_vfmsubps512_mask3:
3097   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
3098   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
3099   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
3100   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
3101   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
3102   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
3103   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
3104   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
3105     ArgNum = 4;
3106     HasRC = true;
3107     break;
3108   }
3109 
3110   llvm::APSInt Result;
3111 
3112   // We can't check the value of a dependent argument.
3113   Expr *Arg = TheCall->getArg(ArgNum);
3114   if (Arg->isTypeDependent() || Arg->isValueDependent())
3115     return false;
3116 
3117   // Check constant-ness first.
3118   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3119     return true;
3120 
3121   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
3122   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
3123   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
3124   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
3125   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
3126       Result == 8/*ROUND_NO_EXC*/ ||
3127       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
3128       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
3129     return false;
3130 
3131   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
3132          << Arg->getSourceRange();
3133 }
3134 
3135 // Check if the gather/scatter scale is legal.
3136 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
3137                                              CallExpr *TheCall) {
3138   unsigned ArgNum = 0;
3139   switch (BuiltinID) {
3140   default:
3141     return false;
3142   case X86::BI__builtin_ia32_gatherpfdpd:
3143   case X86::BI__builtin_ia32_gatherpfdps:
3144   case X86::BI__builtin_ia32_gatherpfqpd:
3145   case X86::BI__builtin_ia32_gatherpfqps:
3146   case X86::BI__builtin_ia32_scatterpfdpd:
3147   case X86::BI__builtin_ia32_scatterpfdps:
3148   case X86::BI__builtin_ia32_scatterpfqpd:
3149   case X86::BI__builtin_ia32_scatterpfqps:
3150     ArgNum = 3;
3151     break;
3152   case X86::BI__builtin_ia32_gatherd_pd:
3153   case X86::BI__builtin_ia32_gatherd_pd256:
3154   case X86::BI__builtin_ia32_gatherq_pd:
3155   case X86::BI__builtin_ia32_gatherq_pd256:
3156   case X86::BI__builtin_ia32_gatherd_ps:
3157   case X86::BI__builtin_ia32_gatherd_ps256:
3158   case X86::BI__builtin_ia32_gatherq_ps:
3159   case X86::BI__builtin_ia32_gatherq_ps256:
3160   case X86::BI__builtin_ia32_gatherd_q:
3161   case X86::BI__builtin_ia32_gatherd_q256:
3162   case X86::BI__builtin_ia32_gatherq_q:
3163   case X86::BI__builtin_ia32_gatherq_q256:
3164   case X86::BI__builtin_ia32_gatherd_d:
3165   case X86::BI__builtin_ia32_gatherd_d256:
3166   case X86::BI__builtin_ia32_gatherq_d:
3167   case X86::BI__builtin_ia32_gatherq_d256:
3168   case X86::BI__builtin_ia32_gather3div2df:
3169   case X86::BI__builtin_ia32_gather3div2di:
3170   case X86::BI__builtin_ia32_gather3div4df:
3171   case X86::BI__builtin_ia32_gather3div4di:
3172   case X86::BI__builtin_ia32_gather3div4sf:
3173   case X86::BI__builtin_ia32_gather3div4si:
3174   case X86::BI__builtin_ia32_gather3div8sf:
3175   case X86::BI__builtin_ia32_gather3div8si:
3176   case X86::BI__builtin_ia32_gather3siv2df:
3177   case X86::BI__builtin_ia32_gather3siv2di:
3178   case X86::BI__builtin_ia32_gather3siv4df:
3179   case X86::BI__builtin_ia32_gather3siv4di:
3180   case X86::BI__builtin_ia32_gather3siv4sf:
3181   case X86::BI__builtin_ia32_gather3siv4si:
3182   case X86::BI__builtin_ia32_gather3siv8sf:
3183   case X86::BI__builtin_ia32_gather3siv8si:
3184   case X86::BI__builtin_ia32_gathersiv8df:
3185   case X86::BI__builtin_ia32_gathersiv16sf:
3186   case X86::BI__builtin_ia32_gatherdiv8df:
3187   case X86::BI__builtin_ia32_gatherdiv16sf:
3188   case X86::BI__builtin_ia32_gathersiv8di:
3189   case X86::BI__builtin_ia32_gathersiv16si:
3190   case X86::BI__builtin_ia32_gatherdiv8di:
3191   case X86::BI__builtin_ia32_gatherdiv16si:
3192   case X86::BI__builtin_ia32_scatterdiv2df:
3193   case X86::BI__builtin_ia32_scatterdiv2di:
3194   case X86::BI__builtin_ia32_scatterdiv4df:
3195   case X86::BI__builtin_ia32_scatterdiv4di:
3196   case X86::BI__builtin_ia32_scatterdiv4sf:
3197   case X86::BI__builtin_ia32_scatterdiv4si:
3198   case X86::BI__builtin_ia32_scatterdiv8sf:
3199   case X86::BI__builtin_ia32_scatterdiv8si:
3200   case X86::BI__builtin_ia32_scattersiv2df:
3201   case X86::BI__builtin_ia32_scattersiv2di:
3202   case X86::BI__builtin_ia32_scattersiv4df:
3203   case X86::BI__builtin_ia32_scattersiv4di:
3204   case X86::BI__builtin_ia32_scattersiv4sf:
3205   case X86::BI__builtin_ia32_scattersiv4si:
3206   case X86::BI__builtin_ia32_scattersiv8sf:
3207   case X86::BI__builtin_ia32_scattersiv8si:
3208   case X86::BI__builtin_ia32_scattersiv8df:
3209   case X86::BI__builtin_ia32_scattersiv16sf:
3210   case X86::BI__builtin_ia32_scatterdiv8df:
3211   case X86::BI__builtin_ia32_scatterdiv16sf:
3212   case X86::BI__builtin_ia32_scattersiv8di:
3213   case X86::BI__builtin_ia32_scattersiv16si:
3214   case X86::BI__builtin_ia32_scatterdiv8di:
3215   case X86::BI__builtin_ia32_scatterdiv16si:
3216     ArgNum = 4;
3217     break;
3218   }
3219 
3220   llvm::APSInt Result;
3221 
3222   // We can't check the value of a dependent argument.
3223   Expr *Arg = TheCall->getArg(ArgNum);
3224   if (Arg->isTypeDependent() || Arg->isValueDependent())
3225     return false;
3226 
3227   // Check constant-ness first.
3228   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3229     return true;
3230 
3231   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
3232     return false;
3233 
3234   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
3235          << Arg->getSourceRange();
3236 }
3237 
3238 static bool isX86_32Builtin(unsigned BuiltinID) {
3239   // These builtins only work on x86-32 targets.
3240   switch (BuiltinID) {
3241   case X86::BI__builtin_ia32_readeflags_u32:
3242   case X86::BI__builtin_ia32_writeeflags_u32:
3243     return true;
3244   }
3245 
3246   return false;
3247 }
3248 
3249 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3250   if (BuiltinID == X86::BI__builtin_cpu_supports)
3251     return SemaBuiltinCpuSupports(*this, TheCall);
3252 
3253   if (BuiltinID == X86::BI__builtin_cpu_is)
3254     return SemaBuiltinCpuIs(*this, TheCall);
3255 
3256   // Check for 32-bit only builtins on a 64-bit target.
3257   const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3258   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
3259     return Diag(TheCall->getCallee()->getBeginLoc(),
3260                 diag::err_32_bit_builtin_64_bit_tgt);
3261 
3262   // If the intrinsic has rounding or SAE make sure its valid.
3263   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
3264     return true;
3265 
3266   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
3267   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
3268     return true;
3269 
3270   // For intrinsics which take an immediate value as part of the instruction,
3271   // range check them here.
3272   int i = 0, l = 0, u = 0;
3273   switch (BuiltinID) {
3274   default:
3275     return false;
3276   case X86::BI__builtin_ia32_vec_ext_v2si:
3277   case X86::BI__builtin_ia32_vec_ext_v2di:
3278   case X86::BI__builtin_ia32_vextractf128_pd256:
3279   case X86::BI__builtin_ia32_vextractf128_ps256:
3280   case X86::BI__builtin_ia32_vextractf128_si256:
3281   case X86::BI__builtin_ia32_extract128i256:
3282   case X86::BI__builtin_ia32_extractf64x4_mask:
3283   case X86::BI__builtin_ia32_extracti64x4_mask:
3284   case X86::BI__builtin_ia32_extractf32x8_mask:
3285   case X86::BI__builtin_ia32_extracti32x8_mask:
3286   case X86::BI__builtin_ia32_extractf64x2_256_mask:
3287   case X86::BI__builtin_ia32_extracti64x2_256_mask:
3288   case X86::BI__builtin_ia32_extractf32x4_256_mask:
3289   case X86::BI__builtin_ia32_extracti32x4_256_mask:
3290     i = 1; l = 0; u = 1;
3291     break;
3292   case X86::BI__builtin_ia32_vec_set_v2di:
3293   case X86::BI__builtin_ia32_vinsertf128_pd256:
3294   case X86::BI__builtin_ia32_vinsertf128_ps256:
3295   case X86::BI__builtin_ia32_vinsertf128_si256:
3296   case X86::BI__builtin_ia32_insert128i256:
3297   case X86::BI__builtin_ia32_insertf32x8:
3298   case X86::BI__builtin_ia32_inserti32x8:
3299   case X86::BI__builtin_ia32_insertf64x4:
3300   case X86::BI__builtin_ia32_inserti64x4:
3301   case X86::BI__builtin_ia32_insertf64x2_256:
3302   case X86::BI__builtin_ia32_inserti64x2_256:
3303   case X86::BI__builtin_ia32_insertf32x4_256:
3304   case X86::BI__builtin_ia32_inserti32x4_256:
3305     i = 2; l = 0; u = 1;
3306     break;
3307   case X86::BI__builtin_ia32_vpermilpd:
3308   case X86::BI__builtin_ia32_vec_ext_v4hi:
3309   case X86::BI__builtin_ia32_vec_ext_v4si:
3310   case X86::BI__builtin_ia32_vec_ext_v4sf:
3311   case X86::BI__builtin_ia32_vec_ext_v4di:
3312   case X86::BI__builtin_ia32_extractf32x4_mask:
3313   case X86::BI__builtin_ia32_extracti32x4_mask:
3314   case X86::BI__builtin_ia32_extractf64x2_512_mask:
3315   case X86::BI__builtin_ia32_extracti64x2_512_mask:
3316     i = 1; l = 0; u = 3;
3317     break;
3318   case X86::BI_mm_prefetch:
3319   case X86::BI__builtin_ia32_vec_ext_v8hi:
3320   case X86::BI__builtin_ia32_vec_ext_v8si:
3321     i = 1; l = 0; u = 7;
3322     break;
3323   case X86::BI__builtin_ia32_sha1rnds4:
3324   case X86::BI__builtin_ia32_blendpd:
3325   case X86::BI__builtin_ia32_shufpd:
3326   case X86::BI__builtin_ia32_vec_set_v4hi:
3327   case X86::BI__builtin_ia32_vec_set_v4si:
3328   case X86::BI__builtin_ia32_vec_set_v4di:
3329   case X86::BI__builtin_ia32_shuf_f32x4_256:
3330   case X86::BI__builtin_ia32_shuf_f64x2_256:
3331   case X86::BI__builtin_ia32_shuf_i32x4_256:
3332   case X86::BI__builtin_ia32_shuf_i64x2_256:
3333   case X86::BI__builtin_ia32_insertf64x2_512:
3334   case X86::BI__builtin_ia32_inserti64x2_512:
3335   case X86::BI__builtin_ia32_insertf32x4:
3336   case X86::BI__builtin_ia32_inserti32x4:
3337     i = 2; l = 0; u = 3;
3338     break;
3339   case X86::BI__builtin_ia32_vpermil2pd:
3340   case X86::BI__builtin_ia32_vpermil2pd256:
3341   case X86::BI__builtin_ia32_vpermil2ps:
3342   case X86::BI__builtin_ia32_vpermil2ps256:
3343     i = 3; l = 0; u = 3;
3344     break;
3345   case X86::BI__builtin_ia32_cmpb128_mask:
3346   case X86::BI__builtin_ia32_cmpw128_mask:
3347   case X86::BI__builtin_ia32_cmpd128_mask:
3348   case X86::BI__builtin_ia32_cmpq128_mask:
3349   case X86::BI__builtin_ia32_cmpb256_mask:
3350   case X86::BI__builtin_ia32_cmpw256_mask:
3351   case X86::BI__builtin_ia32_cmpd256_mask:
3352   case X86::BI__builtin_ia32_cmpq256_mask:
3353   case X86::BI__builtin_ia32_cmpb512_mask:
3354   case X86::BI__builtin_ia32_cmpw512_mask:
3355   case X86::BI__builtin_ia32_cmpd512_mask:
3356   case X86::BI__builtin_ia32_cmpq512_mask:
3357   case X86::BI__builtin_ia32_ucmpb128_mask:
3358   case X86::BI__builtin_ia32_ucmpw128_mask:
3359   case X86::BI__builtin_ia32_ucmpd128_mask:
3360   case X86::BI__builtin_ia32_ucmpq128_mask:
3361   case X86::BI__builtin_ia32_ucmpb256_mask:
3362   case X86::BI__builtin_ia32_ucmpw256_mask:
3363   case X86::BI__builtin_ia32_ucmpd256_mask:
3364   case X86::BI__builtin_ia32_ucmpq256_mask:
3365   case X86::BI__builtin_ia32_ucmpb512_mask:
3366   case X86::BI__builtin_ia32_ucmpw512_mask:
3367   case X86::BI__builtin_ia32_ucmpd512_mask:
3368   case X86::BI__builtin_ia32_ucmpq512_mask:
3369   case X86::BI__builtin_ia32_vpcomub:
3370   case X86::BI__builtin_ia32_vpcomuw:
3371   case X86::BI__builtin_ia32_vpcomud:
3372   case X86::BI__builtin_ia32_vpcomuq:
3373   case X86::BI__builtin_ia32_vpcomb:
3374   case X86::BI__builtin_ia32_vpcomw:
3375   case X86::BI__builtin_ia32_vpcomd:
3376   case X86::BI__builtin_ia32_vpcomq:
3377   case X86::BI__builtin_ia32_vec_set_v8hi:
3378   case X86::BI__builtin_ia32_vec_set_v8si:
3379     i = 2; l = 0; u = 7;
3380     break;
3381   case X86::BI__builtin_ia32_vpermilpd256:
3382   case X86::BI__builtin_ia32_roundps:
3383   case X86::BI__builtin_ia32_roundpd:
3384   case X86::BI__builtin_ia32_roundps256:
3385   case X86::BI__builtin_ia32_roundpd256:
3386   case X86::BI__builtin_ia32_getmantpd128_mask:
3387   case X86::BI__builtin_ia32_getmantpd256_mask:
3388   case X86::BI__builtin_ia32_getmantps128_mask:
3389   case X86::BI__builtin_ia32_getmantps256_mask:
3390   case X86::BI__builtin_ia32_getmantpd512_mask:
3391   case X86::BI__builtin_ia32_getmantps512_mask:
3392   case X86::BI__builtin_ia32_vec_ext_v16qi:
3393   case X86::BI__builtin_ia32_vec_ext_v16hi:
3394     i = 1; l = 0; u = 15;
3395     break;
3396   case X86::BI__builtin_ia32_pblendd128:
3397   case X86::BI__builtin_ia32_blendps:
3398   case X86::BI__builtin_ia32_blendpd256:
3399   case X86::BI__builtin_ia32_shufpd256:
3400   case X86::BI__builtin_ia32_roundss:
3401   case X86::BI__builtin_ia32_roundsd:
3402   case X86::BI__builtin_ia32_rangepd128_mask:
3403   case X86::BI__builtin_ia32_rangepd256_mask:
3404   case X86::BI__builtin_ia32_rangepd512_mask:
3405   case X86::BI__builtin_ia32_rangeps128_mask:
3406   case X86::BI__builtin_ia32_rangeps256_mask:
3407   case X86::BI__builtin_ia32_rangeps512_mask:
3408   case X86::BI__builtin_ia32_getmantsd_round_mask:
3409   case X86::BI__builtin_ia32_getmantss_round_mask:
3410   case X86::BI__builtin_ia32_vec_set_v16qi:
3411   case X86::BI__builtin_ia32_vec_set_v16hi:
3412     i = 2; l = 0; u = 15;
3413     break;
3414   case X86::BI__builtin_ia32_vec_ext_v32qi:
3415     i = 1; l = 0; u = 31;
3416     break;
3417   case X86::BI__builtin_ia32_cmpps:
3418   case X86::BI__builtin_ia32_cmpss:
3419   case X86::BI__builtin_ia32_cmppd:
3420   case X86::BI__builtin_ia32_cmpsd:
3421   case X86::BI__builtin_ia32_cmpps256:
3422   case X86::BI__builtin_ia32_cmppd256:
3423   case X86::BI__builtin_ia32_cmpps128_mask:
3424   case X86::BI__builtin_ia32_cmppd128_mask:
3425   case X86::BI__builtin_ia32_cmpps256_mask:
3426   case X86::BI__builtin_ia32_cmppd256_mask:
3427   case X86::BI__builtin_ia32_cmpps512_mask:
3428   case X86::BI__builtin_ia32_cmppd512_mask:
3429   case X86::BI__builtin_ia32_cmpsd_mask:
3430   case X86::BI__builtin_ia32_cmpss_mask:
3431   case X86::BI__builtin_ia32_vec_set_v32qi:
3432     i = 2; l = 0; u = 31;
3433     break;
3434   case X86::BI__builtin_ia32_permdf256:
3435   case X86::BI__builtin_ia32_permdi256:
3436   case X86::BI__builtin_ia32_permdf512:
3437   case X86::BI__builtin_ia32_permdi512:
3438   case X86::BI__builtin_ia32_vpermilps:
3439   case X86::BI__builtin_ia32_vpermilps256:
3440   case X86::BI__builtin_ia32_vpermilpd512:
3441   case X86::BI__builtin_ia32_vpermilps512:
3442   case X86::BI__builtin_ia32_pshufd:
3443   case X86::BI__builtin_ia32_pshufd256:
3444   case X86::BI__builtin_ia32_pshufd512:
3445   case X86::BI__builtin_ia32_pshufhw:
3446   case X86::BI__builtin_ia32_pshufhw256:
3447   case X86::BI__builtin_ia32_pshufhw512:
3448   case X86::BI__builtin_ia32_pshuflw:
3449   case X86::BI__builtin_ia32_pshuflw256:
3450   case X86::BI__builtin_ia32_pshuflw512:
3451   case X86::BI__builtin_ia32_vcvtps2ph:
3452   case X86::BI__builtin_ia32_vcvtps2ph_mask:
3453   case X86::BI__builtin_ia32_vcvtps2ph256:
3454   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
3455   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
3456   case X86::BI__builtin_ia32_rndscaleps_128_mask:
3457   case X86::BI__builtin_ia32_rndscalepd_128_mask:
3458   case X86::BI__builtin_ia32_rndscaleps_256_mask:
3459   case X86::BI__builtin_ia32_rndscalepd_256_mask:
3460   case X86::BI__builtin_ia32_rndscaleps_mask:
3461   case X86::BI__builtin_ia32_rndscalepd_mask:
3462   case X86::BI__builtin_ia32_reducepd128_mask:
3463   case X86::BI__builtin_ia32_reducepd256_mask:
3464   case X86::BI__builtin_ia32_reducepd512_mask:
3465   case X86::BI__builtin_ia32_reduceps128_mask:
3466   case X86::BI__builtin_ia32_reduceps256_mask:
3467   case X86::BI__builtin_ia32_reduceps512_mask:
3468   case X86::BI__builtin_ia32_prold512:
3469   case X86::BI__builtin_ia32_prolq512:
3470   case X86::BI__builtin_ia32_prold128:
3471   case X86::BI__builtin_ia32_prold256:
3472   case X86::BI__builtin_ia32_prolq128:
3473   case X86::BI__builtin_ia32_prolq256:
3474   case X86::BI__builtin_ia32_prord512:
3475   case X86::BI__builtin_ia32_prorq512:
3476   case X86::BI__builtin_ia32_prord128:
3477   case X86::BI__builtin_ia32_prord256:
3478   case X86::BI__builtin_ia32_prorq128:
3479   case X86::BI__builtin_ia32_prorq256:
3480   case X86::BI__builtin_ia32_fpclasspd128_mask:
3481   case X86::BI__builtin_ia32_fpclasspd256_mask:
3482   case X86::BI__builtin_ia32_fpclassps128_mask:
3483   case X86::BI__builtin_ia32_fpclassps256_mask:
3484   case X86::BI__builtin_ia32_fpclassps512_mask:
3485   case X86::BI__builtin_ia32_fpclasspd512_mask:
3486   case X86::BI__builtin_ia32_fpclasssd_mask:
3487   case X86::BI__builtin_ia32_fpclassss_mask:
3488   case X86::BI__builtin_ia32_pslldqi128_byteshift:
3489   case X86::BI__builtin_ia32_pslldqi256_byteshift:
3490   case X86::BI__builtin_ia32_pslldqi512_byteshift:
3491   case X86::BI__builtin_ia32_psrldqi128_byteshift:
3492   case X86::BI__builtin_ia32_psrldqi256_byteshift:
3493   case X86::BI__builtin_ia32_psrldqi512_byteshift:
3494   case X86::BI__builtin_ia32_kshiftliqi:
3495   case X86::BI__builtin_ia32_kshiftlihi:
3496   case X86::BI__builtin_ia32_kshiftlisi:
3497   case X86::BI__builtin_ia32_kshiftlidi:
3498   case X86::BI__builtin_ia32_kshiftriqi:
3499   case X86::BI__builtin_ia32_kshiftrihi:
3500   case X86::BI__builtin_ia32_kshiftrisi:
3501   case X86::BI__builtin_ia32_kshiftridi:
3502     i = 1; l = 0; u = 255;
3503     break;
3504   case X86::BI__builtin_ia32_vperm2f128_pd256:
3505   case X86::BI__builtin_ia32_vperm2f128_ps256:
3506   case X86::BI__builtin_ia32_vperm2f128_si256:
3507   case X86::BI__builtin_ia32_permti256:
3508   case X86::BI__builtin_ia32_pblendw128:
3509   case X86::BI__builtin_ia32_pblendw256:
3510   case X86::BI__builtin_ia32_blendps256:
3511   case X86::BI__builtin_ia32_pblendd256:
3512   case X86::BI__builtin_ia32_palignr128:
3513   case X86::BI__builtin_ia32_palignr256:
3514   case X86::BI__builtin_ia32_palignr512:
3515   case X86::BI__builtin_ia32_alignq512:
3516   case X86::BI__builtin_ia32_alignd512:
3517   case X86::BI__builtin_ia32_alignd128:
3518   case X86::BI__builtin_ia32_alignd256:
3519   case X86::BI__builtin_ia32_alignq128:
3520   case X86::BI__builtin_ia32_alignq256:
3521   case X86::BI__builtin_ia32_vcomisd:
3522   case X86::BI__builtin_ia32_vcomiss:
3523   case X86::BI__builtin_ia32_shuf_f32x4:
3524   case X86::BI__builtin_ia32_shuf_f64x2:
3525   case X86::BI__builtin_ia32_shuf_i32x4:
3526   case X86::BI__builtin_ia32_shuf_i64x2:
3527   case X86::BI__builtin_ia32_shufpd512:
3528   case X86::BI__builtin_ia32_shufps:
3529   case X86::BI__builtin_ia32_shufps256:
3530   case X86::BI__builtin_ia32_shufps512:
3531   case X86::BI__builtin_ia32_dbpsadbw128:
3532   case X86::BI__builtin_ia32_dbpsadbw256:
3533   case X86::BI__builtin_ia32_dbpsadbw512:
3534   case X86::BI__builtin_ia32_vpshldd128:
3535   case X86::BI__builtin_ia32_vpshldd256:
3536   case X86::BI__builtin_ia32_vpshldd512:
3537   case X86::BI__builtin_ia32_vpshldq128:
3538   case X86::BI__builtin_ia32_vpshldq256:
3539   case X86::BI__builtin_ia32_vpshldq512:
3540   case X86::BI__builtin_ia32_vpshldw128:
3541   case X86::BI__builtin_ia32_vpshldw256:
3542   case X86::BI__builtin_ia32_vpshldw512:
3543   case X86::BI__builtin_ia32_vpshrdd128:
3544   case X86::BI__builtin_ia32_vpshrdd256:
3545   case X86::BI__builtin_ia32_vpshrdd512:
3546   case X86::BI__builtin_ia32_vpshrdq128:
3547   case X86::BI__builtin_ia32_vpshrdq256:
3548   case X86::BI__builtin_ia32_vpshrdq512:
3549   case X86::BI__builtin_ia32_vpshrdw128:
3550   case X86::BI__builtin_ia32_vpshrdw256:
3551   case X86::BI__builtin_ia32_vpshrdw512:
3552     i = 2; l = 0; u = 255;
3553     break;
3554   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3555   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3556   case X86::BI__builtin_ia32_fixupimmps512_mask:
3557   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3558   case X86::BI__builtin_ia32_fixupimmsd_mask:
3559   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3560   case X86::BI__builtin_ia32_fixupimmss_mask:
3561   case X86::BI__builtin_ia32_fixupimmss_maskz:
3562   case X86::BI__builtin_ia32_fixupimmpd128_mask:
3563   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
3564   case X86::BI__builtin_ia32_fixupimmpd256_mask:
3565   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
3566   case X86::BI__builtin_ia32_fixupimmps128_mask:
3567   case X86::BI__builtin_ia32_fixupimmps128_maskz:
3568   case X86::BI__builtin_ia32_fixupimmps256_mask:
3569   case X86::BI__builtin_ia32_fixupimmps256_maskz:
3570   case X86::BI__builtin_ia32_pternlogd512_mask:
3571   case X86::BI__builtin_ia32_pternlogd512_maskz:
3572   case X86::BI__builtin_ia32_pternlogq512_mask:
3573   case X86::BI__builtin_ia32_pternlogq512_maskz:
3574   case X86::BI__builtin_ia32_pternlogd128_mask:
3575   case X86::BI__builtin_ia32_pternlogd128_maskz:
3576   case X86::BI__builtin_ia32_pternlogd256_mask:
3577   case X86::BI__builtin_ia32_pternlogd256_maskz:
3578   case X86::BI__builtin_ia32_pternlogq128_mask:
3579   case X86::BI__builtin_ia32_pternlogq128_maskz:
3580   case X86::BI__builtin_ia32_pternlogq256_mask:
3581   case X86::BI__builtin_ia32_pternlogq256_maskz:
3582     i = 3; l = 0; u = 255;
3583     break;
3584   case X86::BI__builtin_ia32_gatherpfdpd:
3585   case X86::BI__builtin_ia32_gatherpfdps:
3586   case X86::BI__builtin_ia32_gatherpfqpd:
3587   case X86::BI__builtin_ia32_gatherpfqps:
3588   case X86::BI__builtin_ia32_scatterpfdpd:
3589   case X86::BI__builtin_ia32_scatterpfdps:
3590   case X86::BI__builtin_ia32_scatterpfqpd:
3591   case X86::BI__builtin_ia32_scatterpfqps:
3592     i = 4; l = 2; u = 3;
3593     break;
3594   case X86::BI__builtin_ia32_reducesd_mask:
3595   case X86::BI__builtin_ia32_reducess_mask:
3596   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3597   case X86::BI__builtin_ia32_rndscaless_round_mask:
3598     i = 4; l = 0; u = 255;
3599     break;
3600   }
3601 
3602   // Note that we don't force a hard error on the range check here, allowing
3603   // template-generated or macro-generated dead code to potentially have out-of-
3604   // range values. These need to code generate, but don't need to necessarily
3605   // make any sense. We use a warning that defaults to an error.
3606   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
3607 }
3608 
3609 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
3610 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
3611 /// Returns true when the format fits the function and the FormatStringInfo has
3612 /// been populated.
3613 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
3614                                FormatStringInfo *FSI) {
3615   FSI->HasVAListArg = Format->getFirstArg() == 0;
3616   FSI->FormatIdx = Format->getFormatIdx() - 1;
3617   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
3618 
3619   // The way the format attribute works in GCC, the implicit this argument
3620   // of member functions is counted. However, it doesn't appear in our own
3621   // lists, so decrement format_idx in that case.
3622   if (IsCXXMember) {
3623     if(FSI->FormatIdx == 0)
3624       return false;
3625     --FSI->FormatIdx;
3626     if (FSI->FirstDataArg != 0)
3627       --FSI->FirstDataArg;
3628   }
3629   return true;
3630 }
3631 
3632 /// Checks if a the given expression evaluates to null.
3633 ///
3634 /// Returns true if the value evaluates to null.
3635 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
3636   // If the expression has non-null type, it doesn't evaluate to null.
3637   if (auto nullability
3638         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
3639     if (*nullability == NullabilityKind::NonNull)
3640       return false;
3641   }
3642 
3643   // As a special case, transparent unions initialized with zero are
3644   // considered null for the purposes of the nonnull attribute.
3645   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
3646     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
3647       if (const CompoundLiteralExpr *CLE =
3648           dyn_cast<CompoundLiteralExpr>(Expr))
3649         if (const InitListExpr *ILE =
3650             dyn_cast<InitListExpr>(CLE->getInitializer()))
3651           Expr = ILE->getInit(0);
3652   }
3653 
3654   bool Result;
3655   return (!Expr->isValueDependent() &&
3656           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
3657           !Result);
3658 }
3659 
3660 static void CheckNonNullArgument(Sema &S,
3661                                  const Expr *ArgExpr,
3662                                  SourceLocation CallSiteLoc) {
3663   if (CheckNonNullExpr(S, ArgExpr))
3664     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
3665                           S.PDiag(diag::warn_null_arg)
3666                               << ArgExpr->getSourceRange());
3667 }
3668 
3669 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
3670   FormatStringInfo FSI;
3671   if ((GetFormatStringType(Format) == FST_NSString) &&
3672       getFormatStringInfo(Format, false, &FSI)) {
3673     Idx = FSI.FormatIdx;
3674     return true;
3675   }
3676   return false;
3677 }
3678 
3679 /// Diagnose use of %s directive in an NSString which is being passed
3680 /// as formatting string to formatting method.
3681 static void
3682 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
3683                                         const NamedDecl *FDecl,
3684                                         Expr **Args,
3685                                         unsigned NumArgs) {
3686   unsigned Idx = 0;
3687   bool Format = false;
3688   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
3689   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
3690     Idx = 2;
3691     Format = true;
3692   }
3693   else
3694     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
3695       if (S.GetFormatNSStringIdx(I, Idx)) {
3696         Format = true;
3697         break;
3698       }
3699     }
3700   if (!Format || NumArgs <= Idx)
3701     return;
3702   const Expr *FormatExpr = Args[Idx];
3703   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
3704     FormatExpr = CSCE->getSubExpr();
3705   const StringLiteral *FormatString;
3706   if (const ObjCStringLiteral *OSL =
3707       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
3708     FormatString = OSL->getString();
3709   else
3710     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
3711   if (!FormatString)
3712     return;
3713   if (S.FormatStringHasSArg(FormatString)) {
3714     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
3715       << "%s" << 1 << 1;
3716     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
3717       << FDecl->getDeclName();
3718   }
3719 }
3720 
3721 /// Determine whether the given type has a non-null nullability annotation.
3722 static bool isNonNullType(ASTContext &ctx, QualType type) {
3723   if (auto nullability = type->getNullability(ctx))
3724     return *nullability == NullabilityKind::NonNull;
3725 
3726   return false;
3727 }
3728 
3729 static void CheckNonNullArguments(Sema &S,
3730                                   const NamedDecl *FDecl,
3731                                   const FunctionProtoType *Proto,
3732                                   ArrayRef<const Expr *> Args,
3733                                   SourceLocation CallSiteLoc) {
3734   assert((FDecl || Proto) && "Need a function declaration or prototype");
3735 
3736   // Already checked by by constant evaluator.
3737   if (S.isConstantEvaluated())
3738     return;
3739   // Check the attributes attached to the method/function itself.
3740   llvm::SmallBitVector NonNullArgs;
3741   if (FDecl) {
3742     // Handle the nonnull attribute on the function/method declaration itself.
3743     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
3744       if (!NonNull->args_size()) {
3745         // Easy case: all pointer arguments are nonnull.
3746         for (const auto *Arg : Args)
3747           if (S.isValidPointerAttrType(Arg->getType()))
3748             CheckNonNullArgument(S, Arg, CallSiteLoc);
3749         return;
3750       }
3751 
3752       for (const ParamIdx &Idx : NonNull->args()) {
3753         unsigned IdxAST = Idx.getASTIndex();
3754         if (IdxAST >= Args.size())
3755           continue;
3756         if (NonNullArgs.empty())
3757           NonNullArgs.resize(Args.size());
3758         NonNullArgs.set(IdxAST);
3759       }
3760     }
3761   }
3762 
3763   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
3764     // Handle the nonnull attribute on the parameters of the
3765     // function/method.
3766     ArrayRef<ParmVarDecl*> parms;
3767     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
3768       parms = FD->parameters();
3769     else
3770       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
3771 
3772     unsigned ParamIndex = 0;
3773     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
3774          I != E; ++I, ++ParamIndex) {
3775       const ParmVarDecl *PVD = *I;
3776       if (PVD->hasAttr<NonNullAttr>() ||
3777           isNonNullType(S.Context, PVD->getType())) {
3778         if (NonNullArgs.empty())
3779           NonNullArgs.resize(Args.size());
3780 
3781         NonNullArgs.set(ParamIndex);
3782       }
3783     }
3784   } else {
3785     // If we have a non-function, non-method declaration but no
3786     // function prototype, try to dig out the function prototype.
3787     if (!Proto) {
3788       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
3789         QualType type = VD->getType().getNonReferenceType();
3790         if (auto pointerType = type->getAs<PointerType>())
3791           type = pointerType->getPointeeType();
3792         else if (auto blockType = type->getAs<BlockPointerType>())
3793           type = blockType->getPointeeType();
3794         // FIXME: data member pointers?
3795 
3796         // Dig out the function prototype, if there is one.
3797         Proto = type->getAs<FunctionProtoType>();
3798       }
3799     }
3800 
3801     // Fill in non-null argument information from the nullability
3802     // information on the parameter types (if we have them).
3803     if (Proto) {
3804       unsigned Index = 0;
3805       for (auto paramType : Proto->getParamTypes()) {
3806         if (isNonNullType(S.Context, paramType)) {
3807           if (NonNullArgs.empty())
3808             NonNullArgs.resize(Args.size());
3809 
3810           NonNullArgs.set(Index);
3811         }
3812 
3813         ++Index;
3814       }
3815     }
3816   }
3817 
3818   // Check for non-null arguments.
3819   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
3820        ArgIndex != ArgIndexEnd; ++ArgIndex) {
3821     if (NonNullArgs[ArgIndex])
3822       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
3823   }
3824 }
3825 
3826 /// Handles the checks for format strings, non-POD arguments to vararg
3827 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
3828 /// attributes.
3829 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
3830                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
3831                      bool IsMemberFunction, SourceLocation Loc,
3832                      SourceRange Range, VariadicCallType CallType) {
3833   // FIXME: We should check as much as we can in the template definition.
3834   if (CurContext->isDependentContext())
3835     return;
3836 
3837   // Printf and scanf checking.
3838   llvm::SmallBitVector CheckedVarArgs;
3839   if (FDecl) {
3840     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
3841       // Only create vector if there are format attributes.
3842       CheckedVarArgs.resize(Args.size());
3843 
3844       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
3845                            CheckedVarArgs);
3846     }
3847   }
3848 
3849   // Refuse POD arguments that weren't caught by the format string
3850   // checks above.
3851   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
3852   if (CallType != VariadicDoesNotApply &&
3853       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
3854     unsigned NumParams = Proto ? Proto->getNumParams()
3855                        : FDecl && isa<FunctionDecl>(FDecl)
3856                            ? cast<FunctionDecl>(FDecl)->getNumParams()
3857                        : FDecl && isa<ObjCMethodDecl>(FDecl)
3858                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
3859                        : 0;
3860 
3861     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
3862       // Args[ArgIdx] can be null in malformed code.
3863       if (const Expr *Arg = Args[ArgIdx]) {
3864         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
3865           checkVariadicArgument(Arg, CallType);
3866       }
3867     }
3868   }
3869 
3870   if (FDecl || Proto) {
3871     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
3872 
3873     // Type safety checking.
3874     if (FDecl) {
3875       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
3876         CheckArgumentWithTypeTag(I, Args, Loc);
3877     }
3878   }
3879 
3880   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
3881     auto *AA = FDecl->getAttr<AllocAlignAttr>();
3882     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
3883     if (!Arg->isValueDependent()) {
3884       llvm::APSInt I(64);
3885       if (Arg->isIntegerConstantExpr(I, Context)) {
3886         if (!I.isPowerOf2()) {
3887           Diag(Arg->getExprLoc(), diag::err_alignment_not_power_of_two)
3888               << Arg->getSourceRange();
3889           return;
3890         }
3891 
3892         if (I > Sema::MaximumAlignment)
3893           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
3894               << Arg->getSourceRange() << Sema::MaximumAlignment;
3895       }
3896     }
3897   }
3898 
3899   if (FD)
3900     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
3901 }
3902 
3903 /// CheckConstructorCall - Check a constructor call for correctness and safety
3904 /// properties not enforced by the C type system.
3905 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
3906                                 ArrayRef<const Expr *> Args,
3907                                 const FunctionProtoType *Proto,
3908                                 SourceLocation Loc) {
3909   VariadicCallType CallType =
3910     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
3911   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
3912             Loc, SourceRange(), CallType);
3913 }
3914 
3915 /// CheckFunctionCall - Check a direct function call for various correctness
3916 /// and safety properties not strictly enforced by the C type system.
3917 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
3918                              const FunctionProtoType *Proto) {
3919   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
3920                               isa<CXXMethodDecl>(FDecl);
3921   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
3922                           IsMemberOperatorCall;
3923   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
3924                                                   TheCall->getCallee());
3925   Expr** Args = TheCall->getArgs();
3926   unsigned NumArgs = TheCall->getNumArgs();
3927 
3928   Expr *ImplicitThis = nullptr;
3929   if (IsMemberOperatorCall) {
3930     // If this is a call to a member operator, hide the first argument
3931     // from checkCall.
3932     // FIXME: Our choice of AST representation here is less than ideal.
3933     ImplicitThis = Args[0];
3934     ++Args;
3935     --NumArgs;
3936   } else if (IsMemberFunction)
3937     ImplicitThis =
3938         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
3939 
3940   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
3941             IsMemberFunction, TheCall->getRParenLoc(),
3942             TheCall->getCallee()->getSourceRange(), CallType);
3943 
3944   IdentifierInfo *FnInfo = FDecl->getIdentifier();
3945   // None of the checks below are needed for functions that don't have
3946   // simple names (e.g., C++ conversion functions).
3947   if (!FnInfo)
3948     return false;
3949 
3950   CheckAbsoluteValueFunction(TheCall, FDecl);
3951   CheckMaxUnsignedZero(TheCall, FDecl);
3952 
3953   if (getLangOpts().ObjC)
3954     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
3955 
3956   unsigned CMId = FDecl->getMemoryFunctionKind();
3957   if (CMId == 0)
3958     return false;
3959 
3960   // Handle memory setting and copying functions.
3961   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
3962     CheckStrlcpycatArguments(TheCall, FnInfo);
3963   else if (CMId == Builtin::BIstrncat)
3964     CheckStrncatArguments(TheCall, FnInfo);
3965   else
3966     CheckMemaccessArguments(TheCall, CMId, FnInfo);
3967 
3968   return false;
3969 }
3970 
3971 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
3972                                ArrayRef<const Expr *> Args) {
3973   VariadicCallType CallType =
3974       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
3975 
3976   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
3977             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
3978             CallType);
3979 
3980   return false;
3981 }
3982 
3983 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
3984                             const FunctionProtoType *Proto) {
3985   QualType Ty;
3986   if (const auto *V = dyn_cast<VarDecl>(NDecl))
3987     Ty = V->getType().getNonReferenceType();
3988   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
3989     Ty = F->getType().getNonReferenceType();
3990   else
3991     return false;
3992 
3993   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
3994       !Ty->isFunctionProtoType())
3995     return false;
3996 
3997   VariadicCallType CallType;
3998   if (!Proto || !Proto->isVariadic()) {
3999     CallType = VariadicDoesNotApply;
4000   } else if (Ty->isBlockPointerType()) {
4001     CallType = VariadicBlock;
4002   } else { // Ty->isFunctionPointerType()
4003     CallType = VariadicFunction;
4004   }
4005 
4006   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4007             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4008             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4009             TheCall->getCallee()->getSourceRange(), CallType);
4010 
4011   return false;
4012 }
4013 
4014 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
4015 /// such as function pointers returned from functions.
4016 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4017   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4018                                                   TheCall->getCallee());
4019   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4020             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4021             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4022             TheCall->getCallee()->getSourceRange(), CallType);
4023 
4024   return false;
4025 }
4026 
4027 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4028   if (!llvm::isValidAtomicOrderingCABI(Ordering))
4029     return false;
4030 
4031   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4032   switch (Op) {
4033   case AtomicExpr::AO__c11_atomic_init:
4034   case AtomicExpr::AO__opencl_atomic_init:
4035     llvm_unreachable("There is no ordering argument for an init");
4036 
4037   case AtomicExpr::AO__c11_atomic_load:
4038   case AtomicExpr::AO__opencl_atomic_load:
4039   case AtomicExpr::AO__atomic_load_n:
4040   case AtomicExpr::AO__atomic_load:
4041     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4042            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4043 
4044   case AtomicExpr::AO__c11_atomic_store:
4045   case AtomicExpr::AO__opencl_atomic_store:
4046   case AtomicExpr::AO__atomic_store:
4047   case AtomicExpr::AO__atomic_store_n:
4048     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4049            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4050            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4051 
4052   default:
4053     return true;
4054   }
4055 }
4056 
4057 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
4058                                          AtomicExpr::AtomicOp Op) {
4059   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4060   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4061   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4062   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
4063                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
4064                          Op);
4065 }
4066 
4067 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
4068                                  SourceLocation RParenLoc, MultiExprArg Args,
4069                                  AtomicExpr::AtomicOp Op,
4070                                  AtomicArgumentOrder ArgOrder) {
4071   // All the non-OpenCL operations take one of the following forms.
4072   // The OpenCL operations take the __c11 forms with one extra argument for
4073   // synchronization scope.
4074   enum {
4075     // C    __c11_atomic_init(A *, C)
4076     Init,
4077 
4078     // C    __c11_atomic_load(A *, int)
4079     Load,
4080 
4081     // void __atomic_load(A *, CP, int)
4082     LoadCopy,
4083 
4084     // void __atomic_store(A *, CP, int)
4085     Copy,
4086 
4087     // C    __c11_atomic_add(A *, M, int)
4088     Arithmetic,
4089 
4090     // C    __atomic_exchange_n(A *, CP, int)
4091     Xchg,
4092 
4093     // void __atomic_exchange(A *, C *, CP, int)
4094     GNUXchg,
4095 
4096     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4097     C11CmpXchg,
4098 
4099     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4100     GNUCmpXchg
4101   } Form = Init;
4102 
4103   const unsigned NumForm = GNUCmpXchg + 1;
4104   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
4105   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
4106   // where:
4107   //   C is an appropriate type,
4108   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4109   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4110   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4111   //   the int parameters are for orderings.
4112 
4113   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4114       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4115       "need to update code for modified forms");
4116   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
4117                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
4118                         AtomicExpr::AO__atomic_load,
4119                 "need to update code for modified C11 atomics");
4120   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
4121                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
4122   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
4123                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
4124                IsOpenCL;
4125   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4126              Op == AtomicExpr::AO__atomic_store_n ||
4127              Op == AtomicExpr::AO__atomic_exchange_n ||
4128              Op == AtomicExpr::AO__atomic_compare_exchange_n;
4129   bool IsAddSub = false;
4130 
4131   switch (Op) {
4132   case AtomicExpr::AO__c11_atomic_init:
4133   case AtomicExpr::AO__opencl_atomic_init:
4134     Form = Init;
4135     break;
4136 
4137   case AtomicExpr::AO__c11_atomic_load:
4138   case AtomicExpr::AO__opencl_atomic_load:
4139   case AtomicExpr::AO__atomic_load_n:
4140     Form = Load;
4141     break;
4142 
4143   case AtomicExpr::AO__atomic_load:
4144     Form = LoadCopy;
4145     break;
4146 
4147   case AtomicExpr::AO__c11_atomic_store:
4148   case AtomicExpr::AO__opencl_atomic_store:
4149   case AtomicExpr::AO__atomic_store:
4150   case AtomicExpr::AO__atomic_store_n:
4151     Form = Copy;
4152     break;
4153 
4154   case AtomicExpr::AO__c11_atomic_fetch_add:
4155   case AtomicExpr::AO__c11_atomic_fetch_sub:
4156   case AtomicExpr::AO__opencl_atomic_fetch_add:
4157   case AtomicExpr::AO__opencl_atomic_fetch_sub:
4158   case AtomicExpr::AO__atomic_fetch_add:
4159   case AtomicExpr::AO__atomic_fetch_sub:
4160   case AtomicExpr::AO__atomic_add_fetch:
4161   case AtomicExpr::AO__atomic_sub_fetch:
4162     IsAddSub = true;
4163     LLVM_FALLTHROUGH;
4164   case AtomicExpr::AO__c11_atomic_fetch_and:
4165   case AtomicExpr::AO__c11_atomic_fetch_or:
4166   case AtomicExpr::AO__c11_atomic_fetch_xor:
4167   case AtomicExpr::AO__opencl_atomic_fetch_and:
4168   case AtomicExpr::AO__opencl_atomic_fetch_or:
4169   case AtomicExpr::AO__opencl_atomic_fetch_xor:
4170   case AtomicExpr::AO__atomic_fetch_and:
4171   case AtomicExpr::AO__atomic_fetch_or:
4172   case AtomicExpr::AO__atomic_fetch_xor:
4173   case AtomicExpr::AO__atomic_fetch_nand:
4174   case AtomicExpr::AO__atomic_and_fetch:
4175   case AtomicExpr::AO__atomic_or_fetch:
4176   case AtomicExpr::AO__atomic_xor_fetch:
4177   case AtomicExpr::AO__atomic_nand_fetch:
4178   case AtomicExpr::AO__c11_atomic_fetch_min:
4179   case AtomicExpr::AO__c11_atomic_fetch_max:
4180   case AtomicExpr::AO__opencl_atomic_fetch_min:
4181   case AtomicExpr::AO__opencl_atomic_fetch_max:
4182   case AtomicExpr::AO__atomic_min_fetch:
4183   case AtomicExpr::AO__atomic_max_fetch:
4184   case AtomicExpr::AO__atomic_fetch_min:
4185   case AtomicExpr::AO__atomic_fetch_max:
4186     Form = Arithmetic;
4187     break;
4188 
4189   case AtomicExpr::AO__c11_atomic_exchange:
4190   case AtomicExpr::AO__opencl_atomic_exchange:
4191   case AtomicExpr::AO__atomic_exchange_n:
4192     Form = Xchg;
4193     break;
4194 
4195   case AtomicExpr::AO__atomic_exchange:
4196     Form = GNUXchg;
4197     break;
4198 
4199   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4200   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4201   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4202   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4203     Form = C11CmpXchg;
4204     break;
4205 
4206   case AtomicExpr::AO__atomic_compare_exchange:
4207   case AtomicExpr::AO__atomic_compare_exchange_n:
4208     Form = GNUCmpXchg;
4209     break;
4210   }
4211 
4212   unsigned AdjustedNumArgs = NumArgs[Form];
4213   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
4214     ++AdjustedNumArgs;
4215   // Check we have the right number of arguments.
4216   if (Args.size() < AdjustedNumArgs) {
4217     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
4218         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4219         << ExprRange;
4220     return ExprError();
4221   } else if (Args.size() > AdjustedNumArgs) {
4222     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
4223          diag::err_typecheck_call_too_many_args)
4224         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4225         << ExprRange;
4226     return ExprError();
4227   }
4228 
4229   // Inspect the first argument of the atomic operation.
4230   Expr *Ptr = Args[0];
4231   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
4232   if (ConvertedPtr.isInvalid())
4233     return ExprError();
4234 
4235   Ptr = ConvertedPtr.get();
4236   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4237   if (!pointerType) {
4238     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
4239         << Ptr->getType() << Ptr->getSourceRange();
4240     return ExprError();
4241   }
4242 
4243   // For a __c11 builtin, this should be a pointer to an _Atomic type.
4244   QualType AtomTy = pointerType->getPointeeType(); // 'A'
4245   QualType ValType = AtomTy; // 'C'
4246   if (IsC11) {
4247     if (!AtomTy->isAtomicType()) {
4248       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
4249           << Ptr->getType() << Ptr->getSourceRange();
4250       return ExprError();
4251     }
4252     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
4253         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
4254       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
4255           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4256           << Ptr->getSourceRange();
4257       return ExprError();
4258     }
4259     ValType = AtomTy->castAs<AtomicType>()->getValueType();
4260   } else if (Form != Load && Form != LoadCopy) {
4261     if (ValType.isConstQualified()) {
4262       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
4263           << Ptr->getType() << Ptr->getSourceRange();
4264       return ExprError();
4265     }
4266   }
4267 
4268   // For an arithmetic operation, the implied arithmetic must be well-formed.
4269   if (Form == Arithmetic) {
4270     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
4271     if (IsAddSub && !ValType->isIntegerType()
4272         && !ValType->isPointerType()) {
4273       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4274           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4275       return ExprError();
4276     }
4277     if (!IsAddSub && !ValType->isIntegerType()) {
4278       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
4279           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4280       return ExprError();
4281     }
4282     if (IsC11 && ValType->isPointerType() &&
4283         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
4284                             diag::err_incomplete_type)) {
4285       return ExprError();
4286     }
4287   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
4288     // For __atomic_*_n operations, the value type must be a scalar integral or
4289     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
4290     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4291         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4292     return ExprError();
4293   }
4294 
4295   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4296       !AtomTy->isScalarType()) {
4297     // For GNU atomics, require a trivially-copyable type. This is not part of
4298     // the GNU atomics specification, but we enforce it for sanity.
4299     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
4300         << Ptr->getType() << Ptr->getSourceRange();
4301     return ExprError();
4302   }
4303 
4304   switch (ValType.getObjCLifetime()) {
4305   case Qualifiers::OCL_None:
4306   case Qualifiers::OCL_ExplicitNone:
4307     // okay
4308     break;
4309 
4310   case Qualifiers::OCL_Weak:
4311   case Qualifiers::OCL_Strong:
4312   case Qualifiers::OCL_Autoreleasing:
4313     // FIXME: Can this happen? By this point, ValType should be known
4314     // to be trivially copyable.
4315     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
4316         << ValType << Ptr->getSourceRange();
4317     return ExprError();
4318   }
4319 
4320   // All atomic operations have an overload which takes a pointer to a volatile
4321   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
4322   // into the result or the other operands. Similarly atomic_load takes a
4323   // pointer to a const 'A'.
4324   ValType.removeLocalVolatile();
4325   ValType.removeLocalConst();
4326   QualType ResultType = ValType;
4327   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
4328       Form == Init)
4329     ResultType = Context.VoidTy;
4330   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
4331     ResultType = Context.BoolTy;
4332 
4333   // The type of a parameter passed 'by value'. In the GNU atomics, such
4334   // arguments are actually passed as pointers.
4335   QualType ByValType = ValType; // 'CP'
4336   bool IsPassedByAddress = false;
4337   if (!IsC11 && !IsN) {
4338     ByValType = Ptr->getType();
4339     IsPassedByAddress = true;
4340   }
4341 
4342   SmallVector<Expr *, 5> APIOrderedArgs;
4343   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
4344     APIOrderedArgs.push_back(Args[0]);
4345     switch (Form) {
4346     case Init:
4347     case Load:
4348       APIOrderedArgs.push_back(Args[1]); // Val1/Order
4349       break;
4350     case LoadCopy:
4351     case Copy:
4352     case Arithmetic:
4353     case Xchg:
4354       APIOrderedArgs.push_back(Args[2]); // Val1
4355       APIOrderedArgs.push_back(Args[1]); // Order
4356       break;
4357     case GNUXchg:
4358       APIOrderedArgs.push_back(Args[2]); // Val1
4359       APIOrderedArgs.push_back(Args[3]); // Val2
4360       APIOrderedArgs.push_back(Args[1]); // Order
4361       break;
4362     case C11CmpXchg:
4363       APIOrderedArgs.push_back(Args[2]); // Val1
4364       APIOrderedArgs.push_back(Args[4]); // Val2
4365       APIOrderedArgs.push_back(Args[1]); // Order
4366       APIOrderedArgs.push_back(Args[3]); // OrderFail
4367       break;
4368     case GNUCmpXchg:
4369       APIOrderedArgs.push_back(Args[2]); // Val1
4370       APIOrderedArgs.push_back(Args[4]); // Val2
4371       APIOrderedArgs.push_back(Args[5]); // Weak
4372       APIOrderedArgs.push_back(Args[1]); // Order
4373       APIOrderedArgs.push_back(Args[3]); // OrderFail
4374       break;
4375     }
4376   } else
4377     APIOrderedArgs.append(Args.begin(), Args.end());
4378 
4379   // The first argument's non-CV pointer type is used to deduce the type of
4380   // subsequent arguments, except for:
4381   //  - weak flag (always converted to bool)
4382   //  - memory order (always converted to int)
4383   //  - scope  (always converted to int)
4384   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
4385     QualType Ty;
4386     if (i < NumVals[Form] + 1) {
4387       switch (i) {
4388       case 0:
4389         // The first argument is always a pointer. It has a fixed type.
4390         // It is always dereferenced, a nullptr is undefined.
4391         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4392         // Nothing else to do: we already know all we want about this pointer.
4393         continue;
4394       case 1:
4395         // The second argument is the non-atomic operand. For arithmetic, this
4396         // is always passed by value, and for a compare_exchange it is always
4397         // passed by address. For the rest, GNU uses by-address and C11 uses
4398         // by-value.
4399         assert(Form != Load);
4400         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
4401           Ty = ValType;
4402         else if (Form == Copy || Form == Xchg) {
4403           if (IsPassedByAddress) {
4404             // The value pointer is always dereferenced, a nullptr is undefined.
4405             CheckNonNullArgument(*this, APIOrderedArgs[i],
4406                                  ExprRange.getBegin());
4407           }
4408           Ty = ByValType;
4409         } else if (Form == Arithmetic)
4410           Ty = Context.getPointerDiffType();
4411         else {
4412           Expr *ValArg = APIOrderedArgs[i];
4413           // The value pointer is always dereferenced, a nullptr is undefined.
4414           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
4415           LangAS AS = LangAS::Default;
4416           // Keep address space of non-atomic pointer type.
4417           if (const PointerType *PtrTy =
4418                   ValArg->getType()->getAs<PointerType>()) {
4419             AS = PtrTy->getPointeeType().getAddressSpace();
4420           }
4421           Ty = Context.getPointerType(
4422               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
4423         }
4424         break;
4425       case 2:
4426         // The third argument to compare_exchange / GNU exchange is the desired
4427         // value, either by-value (for the C11 and *_n variant) or as a pointer.
4428         if (IsPassedByAddress)
4429           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4430         Ty = ByValType;
4431         break;
4432       case 3:
4433         // The fourth argument to GNU compare_exchange is a 'weak' flag.
4434         Ty = Context.BoolTy;
4435         break;
4436       }
4437     } else {
4438       // The order(s) and scope are always converted to int.
4439       Ty = Context.IntTy;
4440     }
4441 
4442     InitializedEntity Entity =
4443         InitializedEntity::InitializeParameter(Context, Ty, false);
4444     ExprResult Arg = APIOrderedArgs[i];
4445     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4446     if (Arg.isInvalid())
4447       return true;
4448     APIOrderedArgs[i] = Arg.get();
4449   }
4450 
4451   // Permute the arguments into a 'consistent' order.
4452   SmallVector<Expr*, 5> SubExprs;
4453   SubExprs.push_back(Ptr);
4454   switch (Form) {
4455   case Init:
4456     // Note, AtomicExpr::getVal1() has a special case for this atomic.
4457     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4458     break;
4459   case Load:
4460     SubExprs.push_back(APIOrderedArgs[1]); // Order
4461     break;
4462   case LoadCopy:
4463   case Copy:
4464   case Arithmetic:
4465   case Xchg:
4466     SubExprs.push_back(APIOrderedArgs[2]); // Order
4467     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4468     break;
4469   case GNUXchg:
4470     // Note, AtomicExpr::getVal2() has a special case for this atomic.
4471     SubExprs.push_back(APIOrderedArgs[3]); // Order
4472     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4473     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4474     break;
4475   case C11CmpXchg:
4476     SubExprs.push_back(APIOrderedArgs[3]); // Order
4477     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4478     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
4479     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4480     break;
4481   case GNUCmpXchg:
4482     SubExprs.push_back(APIOrderedArgs[4]); // Order
4483     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4484     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
4485     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4486     SubExprs.push_back(APIOrderedArgs[3]); // Weak
4487     break;
4488   }
4489 
4490   if (SubExprs.size() >= 2 && Form != Init) {
4491     llvm::APSInt Result(32);
4492     if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
4493         !isValidOrderingForOp(Result.getSExtValue(), Op))
4494       Diag(SubExprs[1]->getBeginLoc(),
4495            diag::warn_atomic_op_has_invalid_memory_order)
4496           << SubExprs[1]->getSourceRange();
4497   }
4498 
4499   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
4500     auto *Scope = Args[Args.size() - 1];
4501     llvm::APSInt Result(32);
4502     if (Scope->isIntegerConstantExpr(Result, Context) &&
4503         !ScopeModel->isValid(Result.getZExtValue())) {
4504       Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
4505           << Scope->getSourceRange();
4506     }
4507     SubExprs.push_back(Scope);
4508   }
4509 
4510   AtomicExpr *AE = new (Context)
4511       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
4512 
4513   if ((Op == AtomicExpr::AO__c11_atomic_load ||
4514        Op == AtomicExpr::AO__c11_atomic_store ||
4515        Op == AtomicExpr::AO__opencl_atomic_load ||
4516        Op == AtomicExpr::AO__opencl_atomic_store ) &&
4517       Context.AtomicUsesUnsupportedLibcall(AE))
4518     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
4519         << ((Op == AtomicExpr::AO__c11_atomic_load ||
4520              Op == AtomicExpr::AO__opencl_atomic_load)
4521                 ? 0
4522                 : 1);
4523 
4524   return AE;
4525 }
4526 
4527 /// checkBuiltinArgument - Given a call to a builtin function, perform
4528 /// normal type-checking on the given argument, updating the call in
4529 /// place.  This is useful when a builtin function requires custom
4530 /// type-checking for some of its arguments but not necessarily all of
4531 /// them.
4532 ///
4533 /// Returns true on error.
4534 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
4535   FunctionDecl *Fn = E->getDirectCallee();
4536   assert(Fn && "builtin call without direct callee!");
4537 
4538   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
4539   InitializedEntity Entity =
4540     InitializedEntity::InitializeParameter(S.Context, Param);
4541 
4542   ExprResult Arg = E->getArg(0);
4543   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
4544   if (Arg.isInvalid())
4545     return true;
4546 
4547   E->setArg(ArgIndex, Arg.get());
4548   return false;
4549 }
4550 
4551 /// We have a call to a function like __sync_fetch_and_add, which is an
4552 /// overloaded function based on the pointer type of its first argument.
4553 /// The main BuildCallExpr routines have already promoted the types of
4554 /// arguments because all of these calls are prototyped as void(...).
4555 ///
4556 /// This function goes through and does final semantic checking for these
4557 /// builtins, as well as generating any warnings.
4558 ExprResult
4559 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
4560   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
4561   Expr *Callee = TheCall->getCallee();
4562   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
4563   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4564 
4565   // Ensure that we have at least one argument to do type inference from.
4566   if (TheCall->getNumArgs() < 1) {
4567     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
4568         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
4569     return ExprError();
4570   }
4571 
4572   // Inspect the first argument of the atomic builtin.  This should always be
4573   // a pointer type, whose element is an integral scalar or pointer type.
4574   // Because it is a pointer type, we don't have to worry about any implicit
4575   // casts here.
4576   // FIXME: We don't allow floating point scalars as input.
4577   Expr *FirstArg = TheCall->getArg(0);
4578   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
4579   if (FirstArgResult.isInvalid())
4580     return ExprError();
4581   FirstArg = FirstArgResult.get();
4582   TheCall->setArg(0, FirstArg);
4583 
4584   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
4585   if (!pointerType) {
4586     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
4587         << FirstArg->getType() << FirstArg->getSourceRange();
4588     return ExprError();
4589   }
4590 
4591   QualType ValType = pointerType->getPointeeType();
4592   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
4593       !ValType->isBlockPointerType()) {
4594     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
4595         << FirstArg->getType() << FirstArg->getSourceRange();
4596     return ExprError();
4597   }
4598 
4599   if (ValType.isConstQualified()) {
4600     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
4601         << FirstArg->getType() << FirstArg->getSourceRange();
4602     return ExprError();
4603   }
4604 
4605   switch (ValType.getObjCLifetime()) {
4606   case Qualifiers::OCL_None:
4607   case Qualifiers::OCL_ExplicitNone:
4608     // okay
4609     break;
4610 
4611   case Qualifiers::OCL_Weak:
4612   case Qualifiers::OCL_Strong:
4613   case Qualifiers::OCL_Autoreleasing:
4614     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
4615         << ValType << FirstArg->getSourceRange();
4616     return ExprError();
4617   }
4618 
4619   // Strip any qualifiers off ValType.
4620   ValType = ValType.getUnqualifiedType();
4621 
4622   // The majority of builtins return a value, but a few have special return
4623   // types, so allow them to override appropriately below.
4624   QualType ResultType = ValType;
4625 
4626   // We need to figure out which concrete builtin this maps onto.  For example,
4627   // __sync_fetch_and_add with a 2 byte object turns into
4628   // __sync_fetch_and_add_2.
4629 #define BUILTIN_ROW(x) \
4630   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
4631     Builtin::BI##x##_8, Builtin::BI##x##_16 }
4632 
4633   static const unsigned BuiltinIndices[][5] = {
4634     BUILTIN_ROW(__sync_fetch_and_add),
4635     BUILTIN_ROW(__sync_fetch_and_sub),
4636     BUILTIN_ROW(__sync_fetch_and_or),
4637     BUILTIN_ROW(__sync_fetch_and_and),
4638     BUILTIN_ROW(__sync_fetch_and_xor),
4639     BUILTIN_ROW(__sync_fetch_and_nand),
4640 
4641     BUILTIN_ROW(__sync_add_and_fetch),
4642     BUILTIN_ROW(__sync_sub_and_fetch),
4643     BUILTIN_ROW(__sync_and_and_fetch),
4644     BUILTIN_ROW(__sync_or_and_fetch),
4645     BUILTIN_ROW(__sync_xor_and_fetch),
4646     BUILTIN_ROW(__sync_nand_and_fetch),
4647 
4648     BUILTIN_ROW(__sync_val_compare_and_swap),
4649     BUILTIN_ROW(__sync_bool_compare_and_swap),
4650     BUILTIN_ROW(__sync_lock_test_and_set),
4651     BUILTIN_ROW(__sync_lock_release),
4652     BUILTIN_ROW(__sync_swap)
4653   };
4654 #undef BUILTIN_ROW
4655 
4656   // Determine the index of the size.
4657   unsigned SizeIndex;
4658   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
4659   case 1: SizeIndex = 0; break;
4660   case 2: SizeIndex = 1; break;
4661   case 4: SizeIndex = 2; break;
4662   case 8: SizeIndex = 3; break;
4663   case 16: SizeIndex = 4; break;
4664   default:
4665     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
4666         << FirstArg->getType() << FirstArg->getSourceRange();
4667     return ExprError();
4668   }
4669 
4670   // Each of these builtins has one pointer argument, followed by some number of
4671   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
4672   // that we ignore.  Find out which row of BuiltinIndices to read from as well
4673   // as the number of fixed args.
4674   unsigned BuiltinID = FDecl->getBuiltinID();
4675   unsigned BuiltinIndex, NumFixed = 1;
4676   bool WarnAboutSemanticsChange = false;
4677   switch (BuiltinID) {
4678   default: llvm_unreachable("Unknown overloaded atomic builtin!");
4679   case Builtin::BI__sync_fetch_and_add:
4680   case Builtin::BI__sync_fetch_and_add_1:
4681   case Builtin::BI__sync_fetch_and_add_2:
4682   case Builtin::BI__sync_fetch_and_add_4:
4683   case Builtin::BI__sync_fetch_and_add_8:
4684   case Builtin::BI__sync_fetch_and_add_16:
4685     BuiltinIndex = 0;
4686     break;
4687 
4688   case Builtin::BI__sync_fetch_and_sub:
4689   case Builtin::BI__sync_fetch_and_sub_1:
4690   case Builtin::BI__sync_fetch_and_sub_2:
4691   case Builtin::BI__sync_fetch_and_sub_4:
4692   case Builtin::BI__sync_fetch_and_sub_8:
4693   case Builtin::BI__sync_fetch_and_sub_16:
4694     BuiltinIndex = 1;
4695     break;
4696 
4697   case Builtin::BI__sync_fetch_and_or:
4698   case Builtin::BI__sync_fetch_and_or_1:
4699   case Builtin::BI__sync_fetch_and_or_2:
4700   case Builtin::BI__sync_fetch_and_or_4:
4701   case Builtin::BI__sync_fetch_and_or_8:
4702   case Builtin::BI__sync_fetch_and_or_16:
4703     BuiltinIndex = 2;
4704     break;
4705 
4706   case Builtin::BI__sync_fetch_and_and:
4707   case Builtin::BI__sync_fetch_and_and_1:
4708   case Builtin::BI__sync_fetch_and_and_2:
4709   case Builtin::BI__sync_fetch_and_and_4:
4710   case Builtin::BI__sync_fetch_and_and_8:
4711   case Builtin::BI__sync_fetch_and_and_16:
4712     BuiltinIndex = 3;
4713     break;
4714 
4715   case Builtin::BI__sync_fetch_and_xor:
4716   case Builtin::BI__sync_fetch_and_xor_1:
4717   case Builtin::BI__sync_fetch_and_xor_2:
4718   case Builtin::BI__sync_fetch_and_xor_4:
4719   case Builtin::BI__sync_fetch_and_xor_8:
4720   case Builtin::BI__sync_fetch_and_xor_16:
4721     BuiltinIndex = 4;
4722     break;
4723 
4724   case Builtin::BI__sync_fetch_and_nand:
4725   case Builtin::BI__sync_fetch_and_nand_1:
4726   case Builtin::BI__sync_fetch_and_nand_2:
4727   case Builtin::BI__sync_fetch_and_nand_4:
4728   case Builtin::BI__sync_fetch_and_nand_8:
4729   case Builtin::BI__sync_fetch_and_nand_16:
4730     BuiltinIndex = 5;
4731     WarnAboutSemanticsChange = true;
4732     break;
4733 
4734   case Builtin::BI__sync_add_and_fetch:
4735   case Builtin::BI__sync_add_and_fetch_1:
4736   case Builtin::BI__sync_add_and_fetch_2:
4737   case Builtin::BI__sync_add_and_fetch_4:
4738   case Builtin::BI__sync_add_and_fetch_8:
4739   case Builtin::BI__sync_add_and_fetch_16:
4740     BuiltinIndex = 6;
4741     break;
4742 
4743   case Builtin::BI__sync_sub_and_fetch:
4744   case Builtin::BI__sync_sub_and_fetch_1:
4745   case Builtin::BI__sync_sub_and_fetch_2:
4746   case Builtin::BI__sync_sub_and_fetch_4:
4747   case Builtin::BI__sync_sub_and_fetch_8:
4748   case Builtin::BI__sync_sub_and_fetch_16:
4749     BuiltinIndex = 7;
4750     break;
4751 
4752   case Builtin::BI__sync_and_and_fetch:
4753   case Builtin::BI__sync_and_and_fetch_1:
4754   case Builtin::BI__sync_and_and_fetch_2:
4755   case Builtin::BI__sync_and_and_fetch_4:
4756   case Builtin::BI__sync_and_and_fetch_8:
4757   case Builtin::BI__sync_and_and_fetch_16:
4758     BuiltinIndex = 8;
4759     break;
4760 
4761   case Builtin::BI__sync_or_and_fetch:
4762   case Builtin::BI__sync_or_and_fetch_1:
4763   case Builtin::BI__sync_or_and_fetch_2:
4764   case Builtin::BI__sync_or_and_fetch_4:
4765   case Builtin::BI__sync_or_and_fetch_8:
4766   case Builtin::BI__sync_or_and_fetch_16:
4767     BuiltinIndex = 9;
4768     break;
4769 
4770   case Builtin::BI__sync_xor_and_fetch:
4771   case Builtin::BI__sync_xor_and_fetch_1:
4772   case Builtin::BI__sync_xor_and_fetch_2:
4773   case Builtin::BI__sync_xor_and_fetch_4:
4774   case Builtin::BI__sync_xor_and_fetch_8:
4775   case Builtin::BI__sync_xor_and_fetch_16:
4776     BuiltinIndex = 10;
4777     break;
4778 
4779   case Builtin::BI__sync_nand_and_fetch:
4780   case Builtin::BI__sync_nand_and_fetch_1:
4781   case Builtin::BI__sync_nand_and_fetch_2:
4782   case Builtin::BI__sync_nand_and_fetch_4:
4783   case Builtin::BI__sync_nand_and_fetch_8:
4784   case Builtin::BI__sync_nand_and_fetch_16:
4785     BuiltinIndex = 11;
4786     WarnAboutSemanticsChange = true;
4787     break;
4788 
4789   case Builtin::BI__sync_val_compare_and_swap:
4790   case Builtin::BI__sync_val_compare_and_swap_1:
4791   case Builtin::BI__sync_val_compare_and_swap_2:
4792   case Builtin::BI__sync_val_compare_and_swap_4:
4793   case Builtin::BI__sync_val_compare_and_swap_8:
4794   case Builtin::BI__sync_val_compare_and_swap_16:
4795     BuiltinIndex = 12;
4796     NumFixed = 2;
4797     break;
4798 
4799   case Builtin::BI__sync_bool_compare_and_swap:
4800   case Builtin::BI__sync_bool_compare_and_swap_1:
4801   case Builtin::BI__sync_bool_compare_and_swap_2:
4802   case Builtin::BI__sync_bool_compare_and_swap_4:
4803   case Builtin::BI__sync_bool_compare_and_swap_8:
4804   case Builtin::BI__sync_bool_compare_and_swap_16:
4805     BuiltinIndex = 13;
4806     NumFixed = 2;
4807     ResultType = Context.BoolTy;
4808     break;
4809 
4810   case Builtin::BI__sync_lock_test_and_set:
4811   case Builtin::BI__sync_lock_test_and_set_1:
4812   case Builtin::BI__sync_lock_test_and_set_2:
4813   case Builtin::BI__sync_lock_test_and_set_4:
4814   case Builtin::BI__sync_lock_test_and_set_8:
4815   case Builtin::BI__sync_lock_test_and_set_16:
4816     BuiltinIndex = 14;
4817     break;
4818 
4819   case Builtin::BI__sync_lock_release:
4820   case Builtin::BI__sync_lock_release_1:
4821   case Builtin::BI__sync_lock_release_2:
4822   case Builtin::BI__sync_lock_release_4:
4823   case Builtin::BI__sync_lock_release_8:
4824   case Builtin::BI__sync_lock_release_16:
4825     BuiltinIndex = 15;
4826     NumFixed = 0;
4827     ResultType = Context.VoidTy;
4828     break;
4829 
4830   case Builtin::BI__sync_swap:
4831   case Builtin::BI__sync_swap_1:
4832   case Builtin::BI__sync_swap_2:
4833   case Builtin::BI__sync_swap_4:
4834   case Builtin::BI__sync_swap_8:
4835   case Builtin::BI__sync_swap_16:
4836     BuiltinIndex = 16;
4837     break;
4838   }
4839 
4840   // Now that we know how many fixed arguments we expect, first check that we
4841   // have at least that many.
4842   if (TheCall->getNumArgs() < 1+NumFixed) {
4843     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
4844         << 0 << 1 + NumFixed << TheCall->getNumArgs()
4845         << Callee->getSourceRange();
4846     return ExprError();
4847   }
4848 
4849   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
4850       << Callee->getSourceRange();
4851 
4852   if (WarnAboutSemanticsChange) {
4853     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
4854         << Callee->getSourceRange();
4855   }
4856 
4857   // Get the decl for the concrete builtin from this, we can tell what the
4858   // concrete integer type we should convert to is.
4859   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
4860   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
4861   FunctionDecl *NewBuiltinDecl;
4862   if (NewBuiltinID == BuiltinID)
4863     NewBuiltinDecl = FDecl;
4864   else {
4865     // Perform builtin lookup to avoid redeclaring it.
4866     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
4867     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
4868     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
4869     assert(Res.getFoundDecl());
4870     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
4871     if (!NewBuiltinDecl)
4872       return ExprError();
4873   }
4874 
4875   // The first argument --- the pointer --- has a fixed type; we
4876   // deduce the types of the rest of the arguments accordingly.  Walk
4877   // the remaining arguments, converting them to the deduced value type.
4878   for (unsigned i = 0; i != NumFixed; ++i) {
4879     ExprResult Arg = TheCall->getArg(i+1);
4880 
4881     // GCC does an implicit conversion to the pointer or integer ValType.  This
4882     // can fail in some cases (1i -> int**), check for this error case now.
4883     // Initialize the argument.
4884     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4885                                                    ValType, /*consume*/ false);
4886     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4887     if (Arg.isInvalid())
4888       return ExprError();
4889 
4890     // Okay, we have something that *can* be converted to the right type.  Check
4891     // to see if there is a potentially weird extension going on here.  This can
4892     // happen when you do an atomic operation on something like an char* and
4893     // pass in 42.  The 42 gets converted to char.  This is even more strange
4894     // for things like 45.123 -> char, etc.
4895     // FIXME: Do this check.
4896     TheCall->setArg(i+1, Arg.get());
4897   }
4898 
4899   // Create a new DeclRefExpr to refer to the new decl.
4900   DeclRefExpr *NewDRE = DeclRefExpr::Create(
4901       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
4902       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
4903       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
4904 
4905   // Set the callee in the CallExpr.
4906   // FIXME: This loses syntactic information.
4907   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
4908   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
4909                                               CK_BuiltinFnToFnPtr);
4910   TheCall->setCallee(PromotedCall.get());
4911 
4912   // Change the result type of the call to match the original value type. This
4913   // is arbitrary, but the codegen for these builtins ins design to handle it
4914   // gracefully.
4915   TheCall->setType(ResultType);
4916 
4917   return TheCallResult;
4918 }
4919 
4920 /// SemaBuiltinNontemporalOverloaded - We have a call to
4921 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
4922 /// overloaded function based on the pointer type of its last argument.
4923 ///
4924 /// This function goes through and does final semantic checking for these
4925 /// builtins.
4926 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
4927   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
4928   DeclRefExpr *DRE =
4929       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4930   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4931   unsigned BuiltinID = FDecl->getBuiltinID();
4932   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
4933           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
4934          "Unexpected nontemporal load/store builtin!");
4935   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
4936   unsigned numArgs = isStore ? 2 : 1;
4937 
4938   // Ensure that we have the proper number of arguments.
4939   if (checkArgCount(*this, TheCall, numArgs))
4940     return ExprError();
4941 
4942   // Inspect the last argument of the nontemporal builtin.  This should always
4943   // be a pointer type, from which we imply the type of the memory access.
4944   // Because it is a pointer type, we don't have to worry about any implicit
4945   // casts here.
4946   Expr *PointerArg = TheCall->getArg(numArgs - 1);
4947   ExprResult PointerArgResult =
4948       DefaultFunctionArrayLvalueConversion(PointerArg);
4949 
4950   if (PointerArgResult.isInvalid())
4951     return ExprError();
4952   PointerArg = PointerArgResult.get();
4953   TheCall->setArg(numArgs - 1, PointerArg);
4954 
4955   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
4956   if (!pointerType) {
4957     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
4958         << PointerArg->getType() << PointerArg->getSourceRange();
4959     return ExprError();
4960   }
4961 
4962   QualType ValType = pointerType->getPointeeType();
4963 
4964   // Strip any qualifiers off ValType.
4965   ValType = ValType.getUnqualifiedType();
4966   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
4967       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
4968       !ValType->isVectorType()) {
4969     Diag(DRE->getBeginLoc(),
4970          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
4971         << PointerArg->getType() << PointerArg->getSourceRange();
4972     return ExprError();
4973   }
4974 
4975   if (!isStore) {
4976     TheCall->setType(ValType);
4977     return TheCallResult;
4978   }
4979 
4980   ExprResult ValArg = TheCall->getArg(0);
4981   InitializedEntity Entity = InitializedEntity::InitializeParameter(
4982       Context, ValType, /*consume*/ false);
4983   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
4984   if (ValArg.isInvalid())
4985     return ExprError();
4986 
4987   TheCall->setArg(0, ValArg.get());
4988   TheCall->setType(Context.VoidTy);
4989   return TheCallResult;
4990 }
4991 
4992 /// CheckObjCString - Checks that the argument to the builtin
4993 /// CFString constructor is correct
4994 /// Note: It might also make sense to do the UTF-16 conversion here (would
4995 /// simplify the backend).
4996 bool Sema::CheckObjCString(Expr *Arg) {
4997   Arg = Arg->IgnoreParenCasts();
4998   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
4999 
5000   if (!Literal || !Literal->isAscii()) {
5001     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
5002         << Arg->getSourceRange();
5003     return true;
5004   }
5005 
5006   if (Literal->containsNonAsciiOrNull()) {
5007     StringRef String = Literal->getString();
5008     unsigned NumBytes = String.size();
5009     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
5010     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5011     llvm::UTF16 *ToPtr = &ToBuf[0];
5012 
5013     llvm::ConversionResult Result =
5014         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5015                                  ToPtr + NumBytes, llvm::strictConversion);
5016     // Check for conversion failure.
5017     if (Result != llvm::conversionOK)
5018       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
5019           << Arg->getSourceRange();
5020   }
5021   return false;
5022 }
5023 
5024 /// CheckObjCString - Checks that the format string argument to the os_log()
5025 /// and os_trace() functions is correct, and converts it to const char *.
5026 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5027   Arg = Arg->IgnoreParenCasts();
5028   auto *Literal = dyn_cast<StringLiteral>(Arg);
5029   if (!Literal) {
5030     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5031       Literal = ObjcLiteral->getString();
5032     }
5033   }
5034 
5035   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
5036     return ExprError(
5037         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5038         << Arg->getSourceRange());
5039   }
5040 
5041   ExprResult Result(Literal);
5042   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5043   InitializedEntity Entity =
5044       InitializedEntity::InitializeParameter(Context, ResultTy, false);
5045   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5046   return Result;
5047 }
5048 
5049 /// Check that the user is calling the appropriate va_start builtin for the
5050 /// target and calling convention.
5051 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5052   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5053   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5054   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
5055                     TT.getArch() == llvm::Triple::aarch64_32);
5056   bool IsWindows = TT.isOSWindows();
5057   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5058   if (IsX64 || IsAArch64) {
5059     CallingConv CC = CC_C;
5060     if (const FunctionDecl *FD = S.getCurFunctionDecl())
5061       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
5062     if (IsMSVAStart) {
5063       // Don't allow this in System V ABI functions.
5064       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
5065         return S.Diag(Fn->getBeginLoc(),
5066                       diag::err_ms_va_start_used_in_sysv_function);
5067     } else {
5068       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5069       // On x64 Windows, don't allow this in System V ABI functions.
5070       // (Yes, that means there's no corresponding way to support variadic
5071       // System V ABI functions on Windows.)
5072       if ((IsWindows && CC == CC_X86_64SysV) ||
5073           (!IsWindows && CC == CC_Win64))
5074         return S.Diag(Fn->getBeginLoc(),
5075                       diag::err_va_start_used_in_wrong_abi_function)
5076                << !IsWindows;
5077     }
5078     return false;
5079   }
5080 
5081   if (IsMSVAStart)
5082     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5083   return false;
5084 }
5085 
5086 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
5087                                              ParmVarDecl **LastParam = nullptr) {
5088   // Determine whether the current function, block, or obj-c method is variadic
5089   // and get its parameter list.
5090   bool IsVariadic = false;
5091   ArrayRef<ParmVarDecl *> Params;
5092   DeclContext *Caller = S.CurContext;
5093   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5094     IsVariadic = Block->isVariadic();
5095     Params = Block->parameters();
5096   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5097     IsVariadic = FD->isVariadic();
5098     Params = FD->parameters();
5099   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5100     IsVariadic = MD->isVariadic();
5101     // FIXME: This isn't correct for methods (results in bogus warning).
5102     Params = MD->parameters();
5103   } else if (isa<CapturedDecl>(Caller)) {
5104     // We don't support va_start in a CapturedDecl.
5105     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5106     return true;
5107   } else {
5108     // This must be some other declcontext that parses exprs.
5109     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5110     return true;
5111   }
5112 
5113   if (!IsVariadic) {
5114     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
5115     return true;
5116   }
5117 
5118   if (LastParam)
5119     *LastParam = Params.empty() ? nullptr : Params.back();
5120 
5121   return false;
5122 }
5123 
5124 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
5125 /// for validity.  Emit an error and return true on failure; return false
5126 /// on success.
5127 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5128   Expr *Fn = TheCall->getCallee();
5129 
5130   if (checkVAStartABI(*this, BuiltinID, Fn))
5131     return true;
5132 
5133   if (TheCall->getNumArgs() > 2) {
5134     Diag(TheCall->getArg(2)->getBeginLoc(),
5135          diag::err_typecheck_call_too_many_args)
5136         << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5137         << Fn->getSourceRange()
5138         << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5139                        (*(TheCall->arg_end() - 1))->getEndLoc());
5140     return true;
5141   }
5142 
5143   if (TheCall->getNumArgs() < 2) {
5144     return Diag(TheCall->getEndLoc(),
5145                 diag::err_typecheck_call_too_few_args_at_least)
5146            << 0 /*function call*/ << 2 << TheCall->getNumArgs();
5147   }
5148 
5149   // Type-check the first argument normally.
5150   if (checkBuiltinArgument(*this, TheCall, 0))
5151     return true;
5152 
5153   // Check that the current function is variadic, and get its last parameter.
5154   ParmVarDecl *LastParam;
5155   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5156     return true;
5157 
5158   // Verify that the second argument to the builtin is the last argument of the
5159   // current function or method.
5160   bool SecondArgIsLastNamedArgument = false;
5161   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5162 
5163   // These are valid if SecondArgIsLastNamedArgument is false after the next
5164   // block.
5165   QualType Type;
5166   SourceLocation ParamLoc;
5167   bool IsCRegister = false;
5168 
5169   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5170     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5171       SecondArgIsLastNamedArgument = PV == LastParam;
5172 
5173       Type = PV->getType();
5174       ParamLoc = PV->getLocation();
5175       IsCRegister =
5176           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5177     }
5178   }
5179 
5180   if (!SecondArgIsLastNamedArgument)
5181     Diag(TheCall->getArg(1)->getBeginLoc(),
5182          diag::warn_second_arg_of_va_start_not_last_named_param);
5183   else if (IsCRegister || Type->isReferenceType() ||
5184            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5185              // Promotable integers are UB, but enumerations need a bit of
5186              // extra checking to see what their promotable type actually is.
5187              if (!Type->isPromotableIntegerType())
5188                return false;
5189              if (!Type->isEnumeralType())
5190                return true;
5191              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
5192              return !(ED &&
5193                       Context.typesAreCompatible(ED->getPromotionType(), Type));
5194            }()) {
5195     unsigned Reason = 0;
5196     if (Type->isReferenceType())  Reason = 1;
5197     else if (IsCRegister)         Reason = 2;
5198     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
5199     Diag(ParamLoc, diag::note_parameter_type) << Type;
5200   }
5201 
5202   TheCall->setType(Context.VoidTy);
5203   return false;
5204 }
5205 
5206 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
5207   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5208   //                 const char *named_addr);
5209 
5210   Expr *Func = Call->getCallee();
5211 
5212   if (Call->getNumArgs() < 3)
5213     return Diag(Call->getEndLoc(),
5214                 diag::err_typecheck_call_too_few_args_at_least)
5215            << 0 /*function call*/ << 3 << Call->getNumArgs();
5216 
5217   // Type-check the first argument normally.
5218   if (checkBuiltinArgument(*this, Call, 0))
5219     return true;
5220 
5221   // Check that the current function is variadic.
5222   if (checkVAStartIsInVariadicFunction(*this, Func))
5223     return true;
5224 
5225   // __va_start on Windows does not validate the parameter qualifiers
5226 
5227   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5228   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5229 
5230   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5231   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5232 
5233   const QualType &ConstCharPtrTy =
5234       Context.getPointerType(Context.CharTy.withConst());
5235   if (!Arg1Ty->isPointerType() ||
5236       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
5237     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5238         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5239         << 0                                      /* qualifier difference */
5240         << 3                                      /* parameter mismatch */
5241         << 2 << Arg1->getType() << ConstCharPtrTy;
5242 
5243   const QualType SizeTy = Context.getSizeType();
5244   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
5245     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5246         << Arg2->getType() << SizeTy << 1 /* different class */
5247         << 0                              /* qualifier difference */
5248         << 3                              /* parameter mismatch */
5249         << 3 << Arg2->getType() << SizeTy;
5250 
5251   return false;
5252 }
5253 
5254 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
5255 /// friends.  This is declared to take (...), so we have to check everything.
5256 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
5257   if (TheCall->getNumArgs() < 2)
5258     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5259            << 0 << 2 << TheCall->getNumArgs() /*function call*/;
5260   if (TheCall->getNumArgs() > 2)
5261     return Diag(TheCall->getArg(2)->getBeginLoc(),
5262                 diag::err_typecheck_call_too_many_args)
5263            << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5264            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5265                           (*(TheCall->arg_end() - 1))->getEndLoc());
5266 
5267   ExprResult OrigArg0 = TheCall->getArg(0);
5268   ExprResult OrigArg1 = TheCall->getArg(1);
5269 
5270   // Do standard promotions between the two arguments, returning their common
5271   // type.
5272   QualType Res = UsualArithmeticConversions(
5273       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
5274   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5275     return true;
5276 
5277   // Make sure any conversions are pushed back into the call; this is
5278   // type safe since unordered compare builtins are declared as "_Bool
5279   // foo(...)".
5280   TheCall->setArg(0, OrigArg0.get());
5281   TheCall->setArg(1, OrigArg1.get());
5282 
5283   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5284     return false;
5285 
5286   // If the common type isn't a real floating type, then the arguments were
5287   // invalid for this operation.
5288   if (Res.isNull() || !Res->isRealFloatingType())
5289     return Diag(OrigArg0.get()->getBeginLoc(),
5290                 diag::err_typecheck_call_invalid_ordered_compare)
5291            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5292            << SourceRange(OrigArg0.get()->getBeginLoc(),
5293                           OrigArg1.get()->getEndLoc());
5294 
5295   return false;
5296 }
5297 
5298 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
5299 /// __builtin_isnan and friends.  This is declared to take (...), so we have
5300 /// to check everything. We expect the last argument to be a floating point
5301 /// value.
5302 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
5303   if (TheCall->getNumArgs() < NumArgs)
5304     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5305            << 0 << NumArgs << TheCall->getNumArgs() /*function call*/;
5306   if (TheCall->getNumArgs() > NumArgs)
5307     return Diag(TheCall->getArg(NumArgs)->getBeginLoc(),
5308                 diag::err_typecheck_call_too_many_args)
5309            << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
5310            << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(),
5311                           (*(TheCall->arg_end() - 1))->getEndLoc());
5312 
5313   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
5314   // on all preceding parameters just being int.  Try all of those.
5315   for (unsigned i = 0; i < NumArgs - 1; ++i) {
5316     Expr *Arg = TheCall->getArg(i);
5317 
5318     if (Arg->isTypeDependent())
5319       return false;
5320 
5321     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
5322 
5323     if (Res.isInvalid())
5324       return true;
5325     TheCall->setArg(i, Res.get());
5326   }
5327 
5328   Expr *OrigArg = TheCall->getArg(NumArgs-1);
5329 
5330   if (OrigArg->isTypeDependent())
5331     return false;
5332 
5333   // Usual Unary Conversions will convert half to float, which we want for
5334   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
5335   // type how it is, but do normal L->Rvalue conversions.
5336   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
5337     OrigArg = UsualUnaryConversions(OrigArg).get();
5338   else
5339     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
5340   TheCall->setArg(NumArgs - 1, OrigArg);
5341 
5342   // This operation requires a non-_Complex floating-point number.
5343   if (!OrigArg->getType()->isRealFloatingType())
5344     return Diag(OrigArg->getBeginLoc(),
5345                 diag::err_typecheck_call_invalid_unary_fp)
5346            << OrigArg->getType() << OrigArg->getSourceRange();
5347 
5348   return false;
5349 }
5350 
5351 // Customized Sema Checking for VSX builtins that have the following signature:
5352 // vector [...] builtinName(vector [...], vector [...], const int);
5353 // Which takes the same type of vectors (any legal vector type) for the first
5354 // two arguments and takes compile time constant for the third argument.
5355 // Example builtins are :
5356 // vector double vec_xxpermdi(vector double, vector double, int);
5357 // vector short vec_xxsldwi(vector short, vector short, int);
5358 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
5359   unsigned ExpectedNumArgs = 3;
5360   if (TheCall->getNumArgs() < ExpectedNumArgs)
5361     return Diag(TheCall->getEndLoc(),
5362                 diag::err_typecheck_call_too_few_args_at_least)
5363            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5364            << TheCall->getSourceRange();
5365 
5366   if (TheCall->getNumArgs() > ExpectedNumArgs)
5367     return Diag(TheCall->getEndLoc(),
5368                 diag::err_typecheck_call_too_many_args_at_most)
5369            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5370            << TheCall->getSourceRange();
5371 
5372   // Check the third argument is a compile time constant
5373   llvm::APSInt Value;
5374   if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
5375     return Diag(TheCall->getBeginLoc(),
5376                 diag::err_vsx_builtin_nonconstant_argument)
5377            << 3 /* argument index */ << TheCall->getDirectCallee()
5378            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5379                           TheCall->getArg(2)->getEndLoc());
5380 
5381   QualType Arg1Ty = TheCall->getArg(0)->getType();
5382   QualType Arg2Ty = TheCall->getArg(1)->getType();
5383 
5384   // Check the type of argument 1 and argument 2 are vectors.
5385   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
5386   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
5387       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
5388     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
5389            << TheCall->getDirectCallee()
5390            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5391                           TheCall->getArg(1)->getEndLoc());
5392   }
5393 
5394   // Check the first two arguments are the same type.
5395   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
5396     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
5397            << TheCall->getDirectCallee()
5398            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5399                           TheCall->getArg(1)->getEndLoc());
5400   }
5401 
5402   // When default clang type checking is turned off and the customized type
5403   // checking is used, the returning type of the function must be explicitly
5404   // set. Otherwise it is _Bool by default.
5405   TheCall->setType(Arg1Ty);
5406 
5407   return false;
5408 }
5409 
5410 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
5411 // This is declared to take (...), so we have to check everything.
5412 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
5413   if (TheCall->getNumArgs() < 2)
5414     return ExprError(Diag(TheCall->getEndLoc(),
5415                           diag::err_typecheck_call_too_few_args_at_least)
5416                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5417                      << TheCall->getSourceRange());
5418 
5419   // Determine which of the following types of shufflevector we're checking:
5420   // 1) unary, vector mask: (lhs, mask)
5421   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
5422   QualType resType = TheCall->getArg(0)->getType();
5423   unsigned numElements = 0;
5424 
5425   if (!TheCall->getArg(0)->isTypeDependent() &&
5426       !TheCall->getArg(1)->isTypeDependent()) {
5427     QualType LHSType = TheCall->getArg(0)->getType();
5428     QualType RHSType = TheCall->getArg(1)->getType();
5429 
5430     if (!LHSType->isVectorType() || !RHSType->isVectorType())
5431       return ExprError(
5432           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
5433           << TheCall->getDirectCallee()
5434           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5435                          TheCall->getArg(1)->getEndLoc()));
5436 
5437     numElements = LHSType->castAs<VectorType>()->getNumElements();
5438     unsigned numResElements = TheCall->getNumArgs() - 2;
5439 
5440     // Check to see if we have a call with 2 vector arguments, the unary shuffle
5441     // with mask.  If so, verify that RHS is an integer vector type with the
5442     // same number of elts as lhs.
5443     if (TheCall->getNumArgs() == 2) {
5444       if (!RHSType->hasIntegerRepresentation() ||
5445           RHSType->castAs<VectorType>()->getNumElements() != numElements)
5446         return ExprError(Diag(TheCall->getBeginLoc(),
5447                               diag::err_vec_builtin_incompatible_vector)
5448                          << TheCall->getDirectCallee()
5449                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
5450                                         TheCall->getArg(1)->getEndLoc()));
5451     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
5452       return ExprError(Diag(TheCall->getBeginLoc(),
5453                             diag::err_vec_builtin_incompatible_vector)
5454                        << TheCall->getDirectCallee()
5455                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5456                                       TheCall->getArg(1)->getEndLoc()));
5457     } else if (numElements != numResElements) {
5458       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
5459       resType = Context.getVectorType(eltType, numResElements,
5460                                       VectorType::GenericVector);
5461     }
5462   }
5463 
5464   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
5465     if (TheCall->getArg(i)->isTypeDependent() ||
5466         TheCall->getArg(i)->isValueDependent())
5467       continue;
5468 
5469     llvm::APSInt Result(32);
5470     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
5471       return ExprError(Diag(TheCall->getBeginLoc(),
5472                             diag::err_shufflevector_nonconstant_argument)
5473                        << TheCall->getArg(i)->getSourceRange());
5474 
5475     // Allow -1 which will be translated to undef in the IR.
5476     if (Result.isSigned() && Result.isAllOnesValue())
5477       continue;
5478 
5479     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
5480       return ExprError(Diag(TheCall->getBeginLoc(),
5481                             diag::err_shufflevector_argument_too_large)
5482                        << TheCall->getArg(i)->getSourceRange());
5483   }
5484 
5485   SmallVector<Expr*, 32> exprs;
5486 
5487   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
5488     exprs.push_back(TheCall->getArg(i));
5489     TheCall->setArg(i, nullptr);
5490   }
5491 
5492   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
5493                                          TheCall->getCallee()->getBeginLoc(),
5494                                          TheCall->getRParenLoc());
5495 }
5496 
5497 /// SemaConvertVectorExpr - Handle __builtin_convertvector
5498 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
5499                                        SourceLocation BuiltinLoc,
5500                                        SourceLocation RParenLoc) {
5501   ExprValueKind VK = VK_RValue;
5502   ExprObjectKind OK = OK_Ordinary;
5503   QualType DstTy = TInfo->getType();
5504   QualType SrcTy = E->getType();
5505 
5506   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
5507     return ExprError(Diag(BuiltinLoc,
5508                           diag::err_convertvector_non_vector)
5509                      << E->getSourceRange());
5510   if (!DstTy->isVectorType() && !DstTy->isDependentType())
5511     return ExprError(Diag(BuiltinLoc,
5512                           diag::err_convertvector_non_vector_type));
5513 
5514   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
5515     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
5516     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
5517     if (SrcElts != DstElts)
5518       return ExprError(Diag(BuiltinLoc,
5519                             diag::err_convertvector_incompatible_vector)
5520                        << E->getSourceRange());
5521   }
5522 
5523   return new (Context)
5524       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5525 }
5526 
5527 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
5528 // This is declared to take (const void*, ...) and can take two
5529 // optional constant int args.
5530 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
5531   unsigned NumArgs = TheCall->getNumArgs();
5532 
5533   if (NumArgs > 3)
5534     return Diag(TheCall->getEndLoc(),
5535                 diag::err_typecheck_call_too_many_args_at_most)
5536            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
5537 
5538   // Argument 0 is checked for us and the remaining arguments must be
5539   // constant integers.
5540   for (unsigned i = 1; i != NumArgs; ++i)
5541     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
5542       return true;
5543 
5544   return false;
5545 }
5546 
5547 /// SemaBuiltinAssume - Handle __assume (MS Extension).
5548 // __assume does not evaluate its arguments, and should warn if its argument
5549 // has side effects.
5550 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
5551   Expr *Arg = TheCall->getArg(0);
5552   if (Arg->isInstantiationDependent()) return false;
5553 
5554   if (Arg->HasSideEffects(Context))
5555     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
5556         << Arg->getSourceRange()
5557         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
5558 
5559   return false;
5560 }
5561 
5562 /// Handle __builtin_alloca_with_align. This is declared
5563 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
5564 /// than 8.
5565 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
5566   // The alignment must be a constant integer.
5567   Expr *Arg = TheCall->getArg(1);
5568 
5569   // We can't check the value of a dependent argument.
5570   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5571     if (const auto *UE =
5572             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
5573       if (UE->getKind() == UETT_AlignOf ||
5574           UE->getKind() == UETT_PreferredAlignOf)
5575         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
5576             << Arg->getSourceRange();
5577 
5578     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
5579 
5580     if (!Result.isPowerOf2())
5581       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5582              << Arg->getSourceRange();
5583 
5584     if (Result < Context.getCharWidth())
5585       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
5586              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
5587 
5588     if (Result > std::numeric_limits<int32_t>::max())
5589       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
5590              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
5591   }
5592 
5593   return false;
5594 }
5595 
5596 /// Handle __builtin_assume_aligned. This is declared
5597 /// as (const void*, size_t, ...) and can take one optional constant int arg.
5598 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
5599   unsigned NumArgs = TheCall->getNumArgs();
5600 
5601   if (NumArgs > 3)
5602     return Diag(TheCall->getEndLoc(),
5603                 diag::err_typecheck_call_too_many_args_at_most)
5604            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
5605 
5606   // The alignment must be a constant integer.
5607   Expr *Arg = TheCall->getArg(1);
5608 
5609   // We can't check the value of a dependent argument.
5610   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5611     llvm::APSInt Result;
5612     if (SemaBuiltinConstantArg(TheCall, 1, Result))
5613       return true;
5614 
5615     if (!Result.isPowerOf2())
5616       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5617              << Arg->getSourceRange();
5618 
5619     if (Result > Sema::MaximumAlignment)
5620       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
5621           << Arg->getSourceRange() << Sema::MaximumAlignment;
5622   }
5623 
5624   if (NumArgs > 2) {
5625     ExprResult Arg(TheCall->getArg(2));
5626     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5627       Context.getSizeType(), false);
5628     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5629     if (Arg.isInvalid()) return true;
5630     TheCall->setArg(2, Arg.get());
5631   }
5632 
5633   return false;
5634 }
5635 
5636 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
5637   unsigned BuiltinID =
5638       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
5639   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
5640 
5641   unsigned NumArgs = TheCall->getNumArgs();
5642   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
5643   if (NumArgs < NumRequiredArgs) {
5644     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5645            << 0 /* function call */ << NumRequiredArgs << NumArgs
5646            << TheCall->getSourceRange();
5647   }
5648   if (NumArgs >= NumRequiredArgs + 0x100) {
5649     return Diag(TheCall->getEndLoc(),
5650                 diag::err_typecheck_call_too_many_args_at_most)
5651            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
5652            << TheCall->getSourceRange();
5653   }
5654   unsigned i = 0;
5655 
5656   // For formatting call, check buffer arg.
5657   if (!IsSizeCall) {
5658     ExprResult Arg(TheCall->getArg(i));
5659     InitializedEntity Entity = InitializedEntity::InitializeParameter(
5660         Context, Context.VoidPtrTy, false);
5661     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5662     if (Arg.isInvalid())
5663       return true;
5664     TheCall->setArg(i, Arg.get());
5665     i++;
5666   }
5667 
5668   // Check string literal arg.
5669   unsigned FormatIdx = i;
5670   {
5671     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
5672     if (Arg.isInvalid())
5673       return true;
5674     TheCall->setArg(i, Arg.get());
5675     i++;
5676   }
5677 
5678   // Make sure variadic args are scalar.
5679   unsigned FirstDataArg = i;
5680   while (i < NumArgs) {
5681     ExprResult Arg = DefaultVariadicArgumentPromotion(
5682         TheCall->getArg(i), VariadicFunction, nullptr);
5683     if (Arg.isInvalid())
5684       return true;
5685     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
5686     if (ArgSize.getQuantity() >= 0x100) {
5687       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
5688              << i << (int)ArgSize.getQuantity() << 0xff
5689              << TheCall->getSourceRange();
5690     }
5691     TheCall->setArg(i, Arg.get());
5692     i++;
5693   }
5694 
5695   // Check formatting specifiers. NOTE: We're only doing this for the non-size
5696   // call to avoid duplicate diagnostics.
5697   if (!IsSizeCall) {
5698     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
5699     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
5700     bool Success = CheckFormatArguments(
5701         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
5702         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
5703         CheckedVarArgs);
5704     if (!Success)
5705       return true;
5706   }
5707 
5708   if (IsSizeCall) {
5709     TheCall->setType(Context.getSizeType());
5710   } else {
5711     TheCall->setType(Context.VoidPtrTy);
5712   }
5713   return false;
5714 }
5715 
5716 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
5717 /// TheCall is a constant expression.
5718 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
5719                                   llvm::APSInt &Result) {
5720   Expr *Arg = TheCall->getArg(ArgNum);
5721   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5722   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5723 
5724   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
5725 
5726   if (!Arg->isIntegerConstantExpr(Result, Context))
5727     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
5728            << FDecl->getDeclName() << Arg->getSourceRange();
5729 
5730   return false;
5731 }
5732 
5733 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
5734 /// TheCall is a constant expression in the range [Low, High].
5735 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
5736                                        int Low, int High, bool RangeIsError) {
5737   if (isConstantEvaluated())
5738     return false;
5739   llvm::APSInt Result;
5740 
5741   // We can't check the value of a dependent argument.
5742   Expr *Arg = TheCall->getArg(ArgNum);
5743   if (Arg->isTypeDependent() || Arg->isValueDependent())
5744     return false;
5745 
5746   // Check constant-ness first.
5747   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
5748     return true;
5749 
5750   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
5751     if (RangeIsError)
5752       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
5753              << Result.toString(10) << Low << High << Arg->getSourceRange();
5754     else
5755       // Defer the warning until we know if the code will be emitted so that
5756       // dead code can ignore this.
5757       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
5758                           PDiag(diag::warn_argument_invalid_range)
5759                               << Result.toString(10) << Low << High
5760                               << Arg->getSourceRange());
5761   }
5762 
5763   return false;
5764 }
5765 
5766 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
5767 /// TheCall is a constant expression is a multiple of Num..
5768 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
5769                                           unsigned Num) {
5770   llvm::APSInt Result;
5771 
5772   // We can't check the value of a dependent argument.
5773   Expr *Arg = TheCall->getArg(ArgNum);
5774   if (Arg->isTypeDependent() || Arg->isValueDependent())
5775     return false;
5776 
5777   // Check constant-ness first.
5778   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
5779     return true;
5780 
5781   if (Result.getSExtValue() % Num != 0)
5782     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
5783            << Num << Arg->getSourceRange();
5784 
5785   return false;
5786 }
5787 
5788 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
5789 /// constant expression representing a power of 2.
5790 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
5791   llvm::APSInt Result;
5792 
5793   // We can't check the value of a dependent argument.
5794   Expr *Arg = TheCall->getArg(ArgNum);
5795   if (Arg->isTypeDependent() || Arg->isValueDependent())
5796     return false;
5797 
5798   // Check constant-ness first.
5799   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
5800     return true;
5801 
5802   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
5803   // and only if x is a power of 2.
5804   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
5805     return false;
5806 
5807   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
5808          << Arg->getSourceRange();
5809 }
5810 
5811 static bool IsShiftedByte(llvm::APSInt Value) {
5812   if (Value.isNegative())
5813     return false;
5814 
5815   // Check if it's a shifted byte, by shifting it down
5816   while (true) {
5817     // If the value fits in the bottom byte, the check passes.
5818     if (Value < 0x100)
5819       return true;
5820 
5821     // Otherwise, if the value has _any_ bits in the bottom byte, the check
5822     // fails.
5823     if ((Value & 0xFF) != 0)
5824       return false;
5825 
5826     // If the bottom 8 bits are all 0, but something above that is nonzero,
5827     // then shifting the value right by 8 bits won't affect whether it's a
5828     // shifted byte or not. So do that, and go round again.
5829     Value >>= 8;
5830   }
5831 }
5832 
5833 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
5834 /// a constant expression representing an arbitrary byte value shifted left by
5835 /// a multiple of 8 bits.
5836 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
5837                                              unsigned ArgBits) {
5838   llvm::APSInt Result;
5839 
5840   // We can't check the value of a dependent argument.
5841   Expr *Arg = TheCall->getArg(ArgNum);
5842   if (Arg->isTypeDependent() || Arg->isValueDependent())
5843     return false;
5844 
5845   // Check constant-ness first.
5846   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
5847     return true;
5848 
5849   // Truncate to the given size.
5850   Result = Result.getLoBits(ArgBits);
5851   Result.setIsUnsigned(true);
5852 
5853   if (IsShiftedByte(Result))
5854     return false;
5855 
5856   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
5857          << Arg->getSourceRange();
5858 }
5859 
5860 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
5861 /// TheCall is a constant expression representing either a shifted byte value,
5862 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
5863 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
5864 /// Arm MVE intrinsics.
5865 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
5866                                                    int ArgNum,
5867                                                    unsigned ArgBits) {
5868   llvm::APSInt Result;
5869 
5870   // We can't check the value of a dependent argument.
5871   Expr *Arg = TheCall->getArg(ArgNum);
5872   if (Arg->isTypeDependent() || Arg->isValueDependent())
5873     return false;
5874 
5875   // Check constant-ness first.
5876   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
5877     return true;
5878 
5879   // Truncate to the given size.
5880   Result = Result.getLoBits(ArgBits);
5881   Result.setIsUnsigned(true);
5882 
5883   // Check to see if it's in either of the required forms.
5884   if (IsShiftedByte(Result) ||
5885       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
5886     return false;
5887 
5888   return Diag(TheCall->getBeginLoc(),
5889               diag::err_argument_not_shifted_byte_or_xxff)
5890          << Arg->getSourceRange();
5891 }
5892 
5893 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
5894 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
5895   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
5896     if (checkArgCount(*this, TheCall, 2))
5897       return true;
5898     Expr *Arg0 = TheCall->getArg(0);
5899     Expr *Arg1 = TheCall->getArg(1);
5900 
5901     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
5902     if (FirstArg.isInvalid())
5903       return true;
5904     QualType FirstArgType = FirstArg.get()->getType();
5905     if (!FirstArgType->isAnyPointerType())
5906       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
5907                << "first" << FirstArgType << Arg0->getSourceRange();
5908     TheCall->setArg(0, FirstArg.get());
5909 
5910     ExprResult SecArg = DefaultLvalueConversion(Arg1);
5911     if (SecArg.isInvalid())
5912       return true;
5913     QualType SecArgType = SecArg.get()->getType();
5914     if (!SecArgType->isIntegerType())
5915       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
5916                << "second" << SecArgType << Arg1->getSourceRange();
5917 
5918     // Derive the return type from the pointer argument.
5919     TheCall->setType(FirstArgType);
5920     return false;
5921   }
5922 
5923   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
5924     if (checkArgCount(*this, TheCall, 2))
5925       return true;
5926 
5927     Expr *Arg0 = TheCall->getArg(0);
5928     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
5929     if (FirstArg.isInvalid())
5930       return true;
5931     QualType FirstArgType = FirstArg.get()->getType();
5932     if (!FirstArgType->isAnyPointerType())
5933       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
5934                << "first" << FirstArgType << Arg0->getSourceRange();
5935     TheCall->setArg(0, FirstArg.get());
5936 
5937     // Derive the return type from the pointer argument.
5938     TheCall->setType(FirstArgType);
5939 
5940     // Second arg must be an constant in range [0,15]
5941     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
5942   }
5943 
5944   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
5945     if (checkArgCount(*this, TheCall, 2))
5946       return true;
5947     Expr *Arg0 = TheCall->getArg(0);
5948     Expr *Arg1 = TheCall->getArg(1);
5949 
5950     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
5951     if (FirstArg.isInvalid())
5952       return true;
5953     QualType FirstArgType = FirstArg.get()->getType();
5954     if (!FirstArgType->isAnyPointerType())
5955       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
5956                << "first" << FirstArgType << Arg0->getSourceRange();
5957 
5958     QualType SecArgType = Arg1->getType();
5959     if (!SecArgType->isIntegerType())
5960       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
5961                << "second" << SecArgType << Arg1->getSourceRange();
5962     TheCall->setType(Context.IntTy);
5963     return false;
5964   }
5965 
5966   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
5967       BuiltinID == AArch64::BI__builtin_arm_stg) {
5968     if (checkArgCount(*this, TheCall, 1))
5969       return true;
5970     Expr *Arg0 = TheCall->getArg(0);
5971     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
5972     if (FirstArg.isInvalid())
5973       return true;
5974 
5975     QualType FirstArgType = FirstArg.get()->getType();
5976     if (!FirstArgType->isAnyPointerType())
5977       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
5978                << "first" << FirstArgType << Arg0->getSourceRange();
5979     TheCall->setArg(0, FirstArg.get());
5980 
5981     // Derive the return type from the pointer argument.
5982     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
5983       TheCall->setType(FirstArgType);
5984     return false;
5985   }
5986 
5987   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
5988     Expr *ArgA = TheCall->getArg(0);
5989     Expr *ArgB = TheCall->getArg(1);
5990 
5991     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
5992     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
5993 
5994     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
5995       return true;
5996 
5997     QualType ArgTypeA = ArgExprA.get()->getType();
5998     QualType ArgTypeB = ArgExprB.get()->getType();
5999 
6000     auto isNull = [&] (Expr *E) -> bool {
6001       return E->isNullPointerConstant(
6002                         Context, Expr::NPC_ValueDependentIsNotNull); };
6003 
6004     // argument should be either a pointer or null
6005     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
6006       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6007         << "first" << ArgTypeA << ArgA->getSourceRange();
6008 
6009     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
6010       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6011         << "second" << ArgTypeB << ArgB->getSourceRange();
6012 
6013     // Ensure Pointee types are compatible
6014     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
6015         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
6016       QualType pointeeA = ArgTypeA->getPointeeType();
6017       QualType pointeeB = ArgTypeB->getPointeeType();
6018       if (!Context.typesAreCompatible(
6019              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
6020              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
6021         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
6022           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
6023           << ArgB->getSourceRange();
6024       }
6025     }
6026 
6027     // at least one argument should be pointer type
6028     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
6029       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
6030         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
6031 
6032     if (isNull(ArgA)) // adopt type of the other pointer
6033       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
6034 
6035     if (isNull(ArgB))
6036       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
6037 
6038     TheCall->setArg(0, ArgExprA.get());
6039     TheCall->setArg(1, ArgExprB.get());
6040     TheCall->setType(Context.LongLongTy);
6041     return false;
6042   }
6043   assert(false && "Unhandled ARM MTE intrinsic");
6044   return true;
6045 }
6046 
6047 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
6048 /// TheCall is an ARM/AArch64 special register string literal.
6049 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
6050                                     int ArgNum, unsigned ExpectedFieldNum,
6051                                     bool AllowName) {
6052   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
6053                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
6054                       BuiltinID == ARM::BI__builtin_arm_rsr ||
6055                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
6056                       BuiltinID == ARM::BI__builtin_arm_wsr ||
6057                       BuiltinID == ARM::BI__builtin_arm_wsrp;
6058   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
6059                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
6060                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
6061                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
6062                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
6063                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
6064   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
6065 
6066   // We can't check the value of a dependent argument.
6067   Expr *Arg = TheCall->getArg(ArgNum);
6068   if (Arg->isTypeDependent() || Arg->isValueDependent())
6069     return false;
6070 
6071   // Check if the argument is a string literal.
6072   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
6073     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
6074            << Arg->getSourceRange();
6075 
6076   // Check the type of special register given.
6077   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
6078   SmallVector<StringRef, 6> Fields;
6079   Reg.split(Fields, ":");
6080 
6081   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
6082     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6083            << Arg->getSourceRange();
6084 
6085   // If the string is the name of a register then we cannot check that it is
6086   // valid here but if the string is of one the forms described in ACLE then we
6087   // can check that the supplied fields are integers and within the valid
6088   // ranges.
6089   if (Fields.size() > 1) {
6090     bool FiveFields = Fields.size() == 5;
6091 
6092     bool ValidString = true;
6093     if (IsARMBuiltin) {
6094       ValidString &= Fields[0].startswith_lower("cp") ||
6095                      Fields[0].startswith_lower("p");
6096       if (ValidString)
6097         Fields[0] =
6098           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
6099 
6100       ValidString &= Fields[2].startswith_lower("c");
6101       if (ValidString)
6102         Fields[2] = Fields[2].drop_front(1);
6103 
6104       if (FiveFields) {
6105         ValidString &= Fields[3].startswith_lower("c");
6106         if (ValidString)
6107           Fields[3] = Fields[3].drop_front(1);
6108       }
6109     }
6110 
6111     SmallVector<int, 5> Ranges;
6112     if (FiveFields)
6113       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
6114     else
6115       Ranges.append({15, 7, 15});
6116 
6117     for (unsigned i=0; i<Fields.size(); ++i) {
6118       int IntField;
6119       ValidString &= !Fields[i].getAsInteger(10, IntField);
6120       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
6121     }
6122 
6123     if (!ValidString)
6124       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6125              << Arg->getSourceRange();
6126   } else if (IsAArch64Builtin && Fields.size() == 1) {
6127     // If the register name is one of those that appear in the condition below
6128     // and the special register builtin being used is one of the write builtins,
6129     // then we require that the argument provided for writing to the register
6130     // is an integer constant expression. This is because it will be lowered to
6131     // an MSR (immediate) instruction, so we need to know the immediate at
6132     // compile time.
6133     if (TheCall->getNumArgs() != 2)
6134       return false;
6135 
6136     std::string RegLower = Reg.lower();
6137     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
6138         RegLower != "pan" && RegLower != "uao")
6139       return false;
6140 
6141     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6142   }
6143 
6144   return false;
6145 }
6146 
6147 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
6148 /// This checks that the target supports __builtin_longjmp and
6149 /// that val is a constant 1.
6150 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
6151   if (!Context.getTargetInfo().hasSjLjLowering())
6152     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
6153            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6154 
6155   Expr *Arg = TheCall->getArg(1);
6156   llvm::APSInt Result;
6157 
6158   // TODO: This is less than ideal. Overload this to take a value.
6159   if (SemaBuiltinConstantArg(TheCall, 1, Result))
6160     return true;
6161 
6162   if (Result != 1)
6163     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
6164            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6165 
6166   return false;
6167 }
6168 
6169 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
6170 /// This checks that the target supports __builtin_setjmp.
6171 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
6172   if (!Context.getTargetInfo().hasSjLjLowering())
6173     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
6174            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6175   return false;
6176 }
6177 
6178 namespace {
6179 
6180 class UncoveredArgHandler {
6181   enum { Unknown = -1, AllCovered = -2 };
6182 
6183   signed FirstUncoveredArg = Unknown;
6184   SmallVector<const Expr *, 4> DiagnosticExprs;
6185 
6186 public:
6187   UncoveredArgHandler() = default;
6188 
6189   bool hasUncoveredArg() const {
6190     return (FirstUncoveredArg >= 0);
6191   }
6192 
6193   unsigned getUncoveredArg() const {
6194     assert(hasUncoveredArg() && "no uncovered argument");
6195     return FirstUncoveredArg;
6196   }
6197 
6198   void setAllCovered() {
6199     // A string has been found with all arguments covered, so clear out
6200     // the diagnostics.
6201     DiagnosticExprs.clear();
6202     FirstUncoveredArg = AllCovered;
6203   }
6204 
6205   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6206     assert(NewFirstUncoveredArg >= 0 && "Outside range");
6207 
6208     // Don't update if a previous string covers all arguments.
6209     if (FirstUncoveredArg == AllCovered)
6210       return;
6211 
6212     // UncoveredArgHandler tracks the highest uncovered argument index
6213     // and with it all the strings that match this index.
6214     if (NewFirstUncoveredArg == FirstUncoveredArg)
6215       DiagnosticExprs.push_back(StrExpr);
6216     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6217       DiagnosticExprs.clear();
6218       DiagnosticExprs.push_back(StrExpr);
6219       FirstUncoveredArg = NewFirstUncoveredArg;
6220     }
6221   }
6222 
6223   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6224 };
6225 
6226 enum StringLiteralCheckType {
6227   SLCT_NotALiteral,
6228   SLCT_UncheckedLiteral,
6229   SLCT_CheckedLiteral
6230 };
6231 
6232 } // namespace
6233 
6234 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6235                                      BinaryOperatorKind BinOpKind,
6236                                      bool AddendIsRight) {
6237   unsigned BitWidth = Offset.getBitWidth();
6238   unsigned AddendBitWidth = Addend.getBitWidth();
6239   // There might be negative interim results.
6240   if (Addend.isUnsigned()) {
6241     Addend = Addend.zext(++AddendBitWidth);
6242     Addend.setIsSigned(true);
6243   }
6244   // Adjust the bit width of the APSInts.
6245   if (AddendBitWidth > BitWidth) {
6246     Offset = Offset.sext(AddendBitWidth);
6247     BitWidth = AddendBitWidth;
6248   } else if (BitWidth > AddendBitWidth) {
6249     Addend = Addend.sext(BitWidth);
6250   }
6251 
6252   bool Ov = false;
6253   llvm::APSInt ResOffset = Offset;
6254   if (BinOpKind == BO_Add)
6255     ResOffset = Offset.sadd_ov(Addend, Ov);
6256   else {
6257     assert(AddendIsRight && BinOpKind == BO_Sub &&
6258            "operator must be add or sub with addend on the right");
6259     ResOffset = Offset.ssub_ov(Addend, Ov);
6260   }
6261 
6262   // We add an offset to a pointer here so we should support an offset as big as
6263   // possible.
6264   if (Ov) {
6265     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6266            "index (intermediate) result too big");
6267     Offset = Offset.sext(2 * BitWidth);
6268     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6269     return;
6270   }
6271 
6272   Offset = ResOffset;
6273 }
6274 
6275 namespace {
6276 
6277 // This is a wrapper class around StringLiteral to support offsetted string
6278 // literals as format strings. It takes the offset into account when returning
6279 // the string and its length or the source locations to display notes correctly.
6280 class FormatStringLiteral {
6281   const StringLiteral *FExpr;
6282   int64_t Offset;
6283 
6284  public:
6285   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
6286       : FExpr(fexpr), Offset(Offset) {}
6287 
6288   StringRef getString() const {
6289     return FExpr->getString().drop_front(Offset);
6290   }
6291 
6292   unsigned getByteLength() const {
6293     return FExpr->getByteLength() - getCharByteWidth() * Offset;
6294   }
6295 
6296   unsigned getLength() const { return FExpr->getLength() - Offset; }
6297   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
6298 
6299   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
6300 
6301   QualType getType() const { return FExpr->getType(); }
6302 
6303   bool isAscii() const { return FExpr->isAscii(); }
6304   bool isWide() const { return FExpr->isWide(); }
6305   bool isUTF8() const { return FExpr->isUTF8(); }
6306   bool isUTF16() const { return FExpr->isUTF16(); }
6307   bool isUTF32() const { return FExpr->isUTF32(); }
6308   bool isPascal() const { return FExpr->isPascal(); }
6309 
6310   SourceLocation getLocationOfByte(
6311       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
6312       const TargetInfo &Target, unsigned *StartToken = nullptr,
6313       unsigned *StartTokenByteOffset = nullptr) const {
6314     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
6315                                     StartToken, StartTokenByteOffset);
6316   }
6317 
6318   SourceLocation getBeginLoc() const LLVM_READONLY {
6319     return FExpr->getBeginLoc().getLocWithOffset(Offset);
6320   }
6321 
6322   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
6323 };
6324 
6325 }  // namespace
6326 
6327 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
6328                               const Expr *OrigFormatExpr,
6329                               ArrayRef<const Expr *> Args,
6330                               bool HasVAListArg, unsigned format_idx,
6331                               unsigned firstDataArg,
6332                               Sema::FormatStringType Type,
6333                               bool inFunctionCall,
6334                               Sema::VariadicCallType CallType,
6335                               llvm::SmallBitVector &CheckedVarArgs,
6336                               UncoveredArgHandler &UncoveredArg,
6337                               bool IgnoreStringsWithoutSpecifiers);
6338 
6339 // Determine if an expression is a string literal or constant string.
6340 // If this function returns false on the arguments to a function expecting a
6341 // format string, we will usually need to emit a warning.
6342 // True string literals are then checked by CheckFormatString.
6343 static StringLiteralCheckType
6344 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
6345                       bool HasVAListArg, unsigned format_idx,
6346                       unsigned firstDataArg, Sema::FormatStringType Type,
6347                       Sema::VariadicCallType CallType, bool InFunctionCall,
6348                       llvm::SmallBitVector &CheckedVarArgs,
6349                       UncoveredArgHandler &UncoveredArg,
6350                       llvm::APSInt Offset,
6351                       bool IgnoreStringsWithoutSpecifiers = false) {
6352   if (S.isConstantEvaluated())
6353     return SLCT_NotALiteral;
6354  tryAgain:
6355   assert(Offset.isSigned() && "invalid offset");
6356 
6357   if (E->isTypeDependent() || E->isValueDependent())
6358     return SLCT_NotALiteral;
6359 
6360   E = E->IgnoreParenCasts();
6361 
6362   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
6363     // Technically -Wformat-nonliteral does not warn about this case.
6364     // The behavior of printf and friends in this case is implementation
6365     // dependent.  Ideally if the format string cannot be null then
6366     // it should have a 'nonnull' attribute in the function prototype.
6367     return SLCT_UncheckedLiteral;
6368 
6369   switch (E->getStmtClass()) {
6370   case Stmt::BinaryConditionalOperatorClass:
6371   case Stmt::ConditionalOperatorClass: {
6372     // The expression is a literal if both sub-expressions were, and it was
6373     // completely checked only if both sub-expressions were checked.
6374     const AbstractConditionalOperator *C =
6375         cast<AbstractConditionalOperator>(E);
6376 
6377     // Determine whether it is necessary to check both sub-expressions, for
6378     // example, because the condition expression is a constant that can be
6379     // evaluated at compile time.
6380     bool CheckLeft = true, CheckRight = true;
6381 
6382     bool Cond;
6383     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
6384                                                  S.isConstantEvaluated())) {
6385       if (Cond)
6386         CheckRight = false;
6387       else
6388         CheckLeft = false;
6389     }
6390 
6391     // We need to maintain the offsets for the right and the left hand side
6392     // separately to check if every possible indexed expression is a valid
6393     // string literal. They might have different offsets for different string
6394     // literals in the end.
6395     StringLiteralCheckType Left;
6396     if (!CheckLeft)
6397       Left = SLCT_UncheckedLiteral;
6398     else {
6399       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
6400                                    HasVAListArg, format_idx, firstDataArg,
6401                                    Type, CallType, InFunctionCall,
6402                                    CheckedVarArgs, UncoveredArg, Offset,
6403                                    IgnoreStringsWithoutSpecifiers);
6404       if (Left == SLCT_NotALiteral || !CheckRight) {
6405         return Left;
6406       }
6407     }
6408 
6409     StringLiteralCheckType Right = checkFormatStringExpr(
6410         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
6411         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6412         IgnoreStringsWithoutSpecifiers);
6413 
6414     return (CheckLeft && Left < Right) ? Left : Right;
6415   }
6416 
6417   case Stmt::ImplicitCastExprClass:
6418     E = cast<ImplicitCastExpr>(E)->getSubExpr();
6419     goto tryAgain;
6420 
6421   case Stmt::OpaqueValueExprClass:
6422     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
6423       E = src;
6424       goto tryAgain;
6425     }
6426     return SLCT_NotALiteral;
6427 
6428   case Stmt::PredefinedExprClass:
6429     // While __func__, etc., are technically not string literals, they
6430     // cannot contain format specifiers and thus are not a security
6431     // liability.
6432     return SLCT_UncheckedLiteral;
6433 
6434   case Stmt::DeclRefExprClass: {
6435     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6436 
6437     // As an exception, do not flag errors for variables binding to
6438     // const string literals.
6439     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
6440       bool isConstant = false;
6441       QualType T = DR->getType();
6442 
6443       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
6444         isConstant = AT->getElementType().isConstant(S.Context);
6445       } else if (const PointerType *PT = T->getAs<PointerType>()) {
6446         isConstant = T.isConstant(S.Context) &&
6447                      PT->getPointeeType().isConstant(S.Context);
6448       } else if (T->isObjCObjectPointerType()) {
6449         // In ObjC, there is usually no "const ObjectPointer" type,
6450         // so don't check if the pointee type is constant.
6451         isConstant = T.isConstant(S.Context);
6452       }
6453 
6454       if (isConstant) {
6455         if (const Expr *Init = VD->getAnyInitializer()) {
6456           // Look through initializers like const char c[] = { "foo" }
6457           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
6458             if (InitList->isStringLiteralInit())
6459               Init = InitList->getInit(0)->IgnoreParenImpCasts();
6460           }
6461           return checkFormatStringExpr(S, Init, Args,
6462                                        HasVAListArg, format_idx,
6463                                        firstDataArg, Type, CallType,
6464                                        /*InFunctionCall*/ false, CheckedVarArgs,
6465                                        UncoveredArg, Offset);
6466         }
6467       }
6468 
6469       // For vprintf* functions (i.e., HasVAListArg==true), we add a
6470       // special check to see if the format string is a function parameter
6471       // of the function calling the printf function.  If the function
6472       // has an attribute indicating it is a printf-like function, then we
6473       // should suppress warnings concerning non-literals being used in a call
6474       // to a vprintf function.  For example:
6475       //
6476       // void
6477       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
6478       //      va_list ap;
6479       //      va_start(ap, fmt);
6480       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
6481       //      ...
6482       // }
6483       if (HasVAListArg) {
6484         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
6485           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
6486             int PVIndex = PV->getFunctionScopeIndex() + 1;
6487             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
6488               // adjust for implicit parameter
6489               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6490                 if (MD->isInstance())
6491                   ++PVIndex;
6492               // We also check if the formats are compatible.
6493               // We can't pass a 'scanf' string to a 'printf' function.
6494               if (PVIndex == PVFormat->getFormatIdx() &&
6495                   Type == S.GetFormatStringType(PVFormat))
6496                 return SLCT_UncheckedLiteral;
6497             }
6498           }
6499         }
6500       }
6501     }
6502 
6503     return SLCT_NotALiteral;
6504   }
6505 
6506   case Stmt::CallExprClass:
6507   case Stmt::CXXMemberCallExprClass: {
6508     const CallExpr *CE = cast<CallExpr>(E);
6509     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
6510       bool IsFirst = true;
6511       StringLiteralCheckType CommonResult;
6512       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
6513         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
6514         StringLiteralCheckType Result = checkFormatStringExpr(
6515             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6516             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6517             IgnoreStringsWithoutSpecifiers);
6518         if (IsFirst) {
6519           CommonResult = Result;
6520           IsFirst = false;
6521         }
6522       }
6523       if (!IsFirst)
6524         return CommonResult;
6525 
6526       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
6527         unsigned BuiltinID = FD->getBuiltinID();
6528         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
6529             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
6530           const Expr *Arg = CE->getArg(0);
6531           return checkFormatStringExpr(S, Arg, Args,
6532                                        HasVAListArg, format_idx,
6533                                        firstDataArg, Type, CallType,
6534                                        InFunctionCall, CheckedVarArgs,
6535                                        UncoveredArg, Offset,
6536                                        IgnoreStringsWithoutSpecifiers);
6537         }
6538       }
6539     }
6540 
6541     return SLCT_NotALiteral;
6542   }
6543   case Stmt::ObjCMessageExprClass: {
6544     const auto *ME = cast<ObjCMessageExpr>(E);
6545     if (const auto *MD = ME->getMethodDecl()) {
6546       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
6547         // As a special case heuristic, if we're using the method -[NSBundle
6548         // localizedStringForKey:value:table:], ignore any key strings that lack
6549         // format specifiers. The idea is that if the key doesn't have any
6550         // format specifiers then its probably just a key to map to the
6551         // localized strings. If it does have format specifiers though, then its
6552         // likely that the text of the key is the format string in the
6553         // programmer's language, and should be checked.
6554         const ObjCInterfaceDecl *IFace;
6555         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
6556             IFace->getIdentifier()->isStr("NSBundle") &&
6557             MD->getSelector().isKeywordSelector(
6558                 {"localizedStringForKey", "value", "table"})) {
6559           IgnoreStringsWithoutSpecifiers = true;
6560         }
6561 
6562         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
6563         return checkFormatStringExpr(
6564             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6565             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6566             IgnoreStringsWithoutSpecifiers);
6567       }
6568     }
6569 
6570     return SLCT_NotALiteral;
6571   }
6572   case Stmt::ObjCStringLiteralClass:
6573   case Stmt::StringLiteralClass: {
6574     const StringLiteral *StrE = nullptr;
6575 
6576     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
6577       StrE = ObjCFExpr->getString();
6578     else
6579       StrE = cast<StringLiteral>(E);
6580 
6581     if (StrE) {
6582       if (Offset.isNegative() || Offset > StrE->getLength()) {
6583         // TODO: It would be better to have an explicit warning for out of
6584         // bounds literals.
6585         return SLCT_NotALiteral;
6586       }
6587       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
6588       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
6589                         firstDataArg, Type, InFunctionCall, CallType,
6590                         CheckedVarArgs, UncoveredArg,
6591                         IgnoreStringsWithoutSpecifiers);
6592       return SLCT_CheckedLiteral;
6593     }
6594 
6595     return SLCT_NotALiteral;
6596   }
6597   case Stmt::BinaryOperatorClass: {
6598     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
6599 
6600     // A string literal + an int offset is still a string literal.
6601     if (BinOp->isAdditiveOp()) {
6602       Expr::EvalResult LResult, RResult;
6603 
6604       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
6605           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
6606       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
6607           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
6608 
6609       if (LIsInt != RIsInt) {
6610         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
6611 
6612         if (LIsInt) {
6613           if (BinOpKind == BO_Add) {
6614             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
6615             E = BinOp->getRHS();
6616             goto tryAgain;
6617           }
6618         } else {
6619           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
6620           E = BinOp->getLHS();
6621           goto tryAgain;
6622         }
6623       }
6624     }
6625 
6626     return SLCT_NotALiteral;
6627   }
6628   case Stmt::UnaryOperatorClass: {
6629     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
6630     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
6631     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
6632       Expr::EvalResult IndexResult;
6633       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
6634                                        Expr::SE_NoSideEffects,
6635                                        S.isConstantEvaluated())) {
6636         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
6637                    /*RHS is int*/ true);
6638         E = ASE->getBase();
6639         goto tryAgain;
6640       }
6641     }
6642 
6643     return SLCT_NotALiteral;
6644   }
6645 
6646   default:
6647     return SLCT_NotALiteral;
6648   }
6649 }
6650 
6651 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
6652   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
6653       .Case("scanf", FST_Scanf)
6654       .Cases("printf", "printf0", FST_Printf)
6655       .Cases("NSString", "CFString", FST_NSString)
6656       .Case("strftime", FST_Strftime)
6657       .Case("strfmon", FST_Strfmon)
6658       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
6659       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
6660       .Case("os_trace", FST_OSLog)
6661       .Case("os_log", FST_OSLog)
6662       .Default(FST_Unknown);
6663 }
6664 
6665 /// CheckFormatArguments - Check calls to printf and scanf (and similar
6666 /// functions) for correct use of format strings.
6667 /// Returns true if a format string has been fully checked.
6668 bool Sema::CheckFormatArguments(const FormatAttr *Format,
6669                                 ArrayRef<const Expr *> Args,
6670                                 bool IsCXXMember,
6671                                 VariadicCallType CallType,
6672                                 SourceLocation Loc, SourceRange Range,
6673                                 llvm::SmallBitVector &CheckedVarArgs) {
6674   FormatStringInfo FSI;
6675   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
6676     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
6677                                 FSI.FirstDataArg, GetFormatStringType(Format),
6678                                 CallType, Loc, Range, CheckedVarArgs);
6679   return false;
6680 }
6681 
6682 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
6683                                 bool HasVAListArg, unsigned format_idx,
6684                                 unsigned firstDataArg, FormatStringType Type,
6685                                 VariadicCallType CallType,
6686                                 SourceLocation Loc, SourceRange Range,
6687                                 llvm::SmallBitVector &CheckedVarArgs) {
6688   // CHECK: printf/scanf-like function is called with no format string.
6689   if (format_idx >= Args.size()) {
6690     Diag(Loc, diag::warn_missing_format_string) << Range;
6691     return false;
6692   }
6693 
6694   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
6695 
6696   // CHECK: format string is not a string literal.
6697   //
6698   // Dynamically generated format strings are difficult to
6699   // automatically vet at compile time.  Requiring that format strings
6700   // are string literals: (1) permits the checking of format strings by
6701   // the compiler and thereby (2) can practically remove the source of
6702   // many format string exploits.
6703 
6704   // Format string can be either ObjC string (e.g. @"%d") or
6705   // C string (e.g. "%d")
6706   // ObjC string uses the same format specifiers as C string, so we can use
6707   // the same format string checking logic for both ObjC and C strings.
6708   UncoveredArgHandler UncoveredArg;
6709   StringLiteralCheckType CT =
6710       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
6711                             format_idx, firstDataArg, Type, CallType,
6712                             /*IsFunctionCall*/ true, CheckedVarArgs,
6713                             UncoveredArg,
6714                             /*no string offset*/ llvm::APSInt(64, false) = 0);
6715 
6716   // Generate a diagnostic where an uncovered argument is detected.
6717   if (UncoveredArg.hasUncoveredArg()) {
6718     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
6719     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
6720     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
6721   }
6722 
6723   if (CT != SLCT_NotALiteral)
6724     // Literal format string found, check done!
6725     return CT == SLCT_CheckedLiteral;
6726 
6727   // Strftime is particular as it always uses a single 'time' argument,
6728   // so it is safe to pass a non-literal string.
6729   if (Type == FST_Strftime)
6730     return false;
6731 
6732   // Do not emit diag when the string param is a macro expansion and the
6733   // format is either NSString or CFString. This is a hack to prevent
6734   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
6735   // which are usually used in place of NS and CF string literals.
6736   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
6737   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
6738     return false;
6739 
6740   // If there are no arguments specified, warn with -Wformat-security, otherwise
6741   // warn only with -Wformat-nonliteral.
6742   if (Args.size() == firstDataArg) {
6743     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
6744       << OrigFormatExpr->getSourceRange();
6745     switch (Type) {
6746     default:
6747       break;
6748     case FST_Kprintf:
6749     case FST_FreeBSDKPrintf:
6750     case FST_Printf:
6751       Diag(FormatLoc, diag::note_format_security_fixit)
6752         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
6753       break;
6754     case FST_NSString:
6755       Diag(FormatLoc, diag::note_format_security_fixit)
6756         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
6757       break;
6758     }
6759   } else {
6760     Diag(FormatLoc, diag::warn_format_nonliteral)
6761       << OrigFormatExpr->getSourceRange();
6762   }
6763   return false;
6764 }
6765 
6766 namespace {
6767 
6768 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
6769 protected:
6770   Sema &S;
6771   const FormatStringLiteral *FExpr;
6772   const Expr *OrigFormatExpr;
6773   const Sema::FormatStringType FSType;
6774   const unsigned FirstDataArg;
6775   const unsigned NumDataArgs;
6776   const char *Beg; // Start of format string.
6777   const bool HasVAListArg;
6778   ArrayRef<const Expr *> Args;
6779   unsigned FormatIdx;
6780   llvm::SmallBitVector CoveredArgs;
6781   bool usesPositionalArgs = false;
6782   bool atFirstArg = true;
6783   bool inFunctionCall;
6784   Sema::VariadicCallType CallType;
6785   llvm::SmallBitVector &CheckedVarArgs;
6786   UncoveredArgHandler &UncoveredArg;
6787 
6788 public:
6789   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
6790                      const Expr *origFormatExpr,
6791                      const Sema::FormatStringType type, unsigned firstDataArg,
6792                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
6793                      ArrayRef<const Expr *> Args, unsigned formatIdx,
6794                      bool inFunctionCall, Sema::VariadicCallType callType,
6795                      llvm::SmallBitVector &CheckedVarArgs,
6796                      UncoveredArgHandler &UncoveredArg)
6797       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
6798         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
6799         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
6800         inFunctionCall(inFunctionCall), CallType(callType),
6801         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
6802     CoveredArgs.resize(numDataArgs);
6803     CoveredArgs.reset();
6804   }
6805 
6806   void DoneProcessing();
6807 
6808   void HandleIncompleteSpecifier(const char *startSpecifier,
6809                                  unsigned specifierLen) override;
6810 
6811   void HandleInvalidLengthModifier(
6812                            const analyze_format_string::FormatSpecifier &FS,
6813                            const analyze_format_string::ConversionSpecifier &CS,
6814                            const char *startSpecifier, unsigned specifierLen,
6815                            unsigned DiagID);
6816 
6817   void HandleNonStandardLengthModifier(
6818                     const analyze_format_string::FormatSpecifier &FS,
6819                     const char *startSpecifier, unsigned specifierLen);
6820 
6821   void HandleNonStandardConversionSpecifier(
6822                     const analyze_format_string::ConversionSpecifier &CS,
6823                     const char *startSpecifier, unsigned specifierLen);
6824 
6825   void HandlePosition(const char *startPos, unsigned posLen) override;
6826 
6827   void HandleInvalidPosition(const char *startSpecifier,
6828                              unsigned specifierLen,
6829                              analyze_format_string::PositionContext p) override;
6830 
6831   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
6832 
6833   void HandleNullChar(const char *nullCharacter) override;
6834 
6835   template <typename Range>
6836   static void
6837   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
6838                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
6839                        bool IsStringLocation, Range StringRange,
6840                        ArrayRef<FixItHint> Fixit = None);
6841 
6842 protected:
6843   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
6844                                         const char *startSpec,
6845                                         unsigned specifierLen,
6846                                         const char *csStart, unsigned csLen);
6847 
6848   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
6849                                          const char *startSpec,
6850                                          unsigned specifierLen);
6851 
6852   SourceRange getFormatStringRange();
6853   CharSourceRange getSpecifierRange(const char *startSpecifier,
6854                                     unsigned specifierLen);
6855   SourceLocation getLocationOfByte(const char *x);
6856 
6857   const Expr *getDataArg(unsigned i) const;
6858 
6859   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
6860                     const analyze_format_string::ConversionSpecifier &CS,
6861                     const char *startSpecifier, unsigned specifierLen,
6862                     unsigned argIndex);
6863 
6864   template <typename Range>
6865   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
6866                             bool IsStringLocation, Range StringRange,
6867                             ArrayRef<FixItHint> Fixit = None);
6868 };
6869 
6870 } // namespace
6871 
6872 SourceRange CheckFormatHandler::getFormatStringRange() {
6873   return OrigFormatExpr->getSourceRange();
6874 }
6875 
6876 CharSourceRange CheckFormatHandler::
6877 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
6878   SourceLocation Start = getLocationOfByte(startSpecifier);
6879   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
6880 
6881   // Advance the end SourceLocation by one due to half-open ranges.
6882   End = End.getLocWithOffset(1);
6883 
6884   return CharSourceRange::getCharRange(Start, End);
6885 }
6886 
6887 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
6888   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
6889                                   S.getLangOpts(), S.Context.getTargetInfo());
6890 }
6891 
6892 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
6893                                                    unsigned specifierLen){
6894   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
6895                        getLocationOfByte(startSpecifier),
6896                        /*IsStringLocation*/true,
6897                        getSpecifierRange(startSpecifier, specifierLen));
6898 }
6899 
6900 void CheckFormatHandler::HandleInvalidLengthModifier(
6901     const analyze_format_string::FormatSpecifier &FS,
6902     const analyze_format_string::ConversionSpecifier &CS,
6903     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
6904   using namespace analyze_format_string;
6905 
6906   const LengthModifier &LM = FS.getLengthModifier();
6907   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
6908 
6909   // See if we know how to fix this length modifier.
6910   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
6911   if (FixedLM) {
6912     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
6913                          getLocationOfByte(LM.getStart()),
6914                          /*IsStringLocation*/true,
6915                          getSpecifierRange(startSpecifier, specifierLen));
6916 
6917     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
6918       << FixedLM->toString()
6919       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
6920 
6921   } else {
6922     FixItHint Hint;
6923     if (DiagID == diag::warn_format_nonsensical_length)
6924       Hint = FixItHint::CreateRemoval(LMRange);
6925 
6926     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
6927                          getLocationOfByte(LM.getStart()),
6928                          /*IsStringLocation*/true,
6929                          getSpecifierRange(startSpecifier, specifierLen),
6930                          Hint);
6931   }
6932 }
6933 
6934 void CheckFormatHandler::HandleNonStandardLengthModifier(
6935     const analyze_format_string::FormatSpecifier &FS,
6936     const char *startSpecifier, unsigned specifierLen) {
6937   using namespace analyze_format_string;
6938 
6939   const LengthModifier &LM = FS.getLengthModifier();
6940   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
6941 
6942   // See if we know how to fix this length modifier.
6943   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
6944   if (FixedLM) {
6945     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6946                            << LM.toString() << 0,
6947                          getLocationOfByte(LM.getStart()),
6948                          /*IsStringLocation*/true,
6949                          getSpecifierRange(startSpecifier, specifierLen));
6950 
6951     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
6952       << FixedLM->toString()
6953       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
6954 
6955   } else {
6956     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6957                            << LM.toString() << 0,
6958                          getLocationOfByte(LM.getStart()),
6959                          /*IsStringLocation*/true,
6960                          getSpecifierRange(startSpecifier, specifierLen));
6961   }
6962 }
6963 
6964 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
6965     const analyze_format_string::ConversionSpecifier &CS,
6966     const char *startSpecifier, unsigned specifierLen) {
6967   using namespace analyze_format_string;
6968 
6969   // See if we know how to fix this conversion specifier.
6970   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
6971   if (FixedCS) {
6972     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6973                           << CS.toString() << /*conversion specifier*/1,
6974                          getLocationOfByte(CS.getStart()),
6975                          /*IsStringLocation*/true,
6976                          getSpecifierRange(startSpecifier, specifierLen));
6977 
6978     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
6979     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
6980       << FixedCS->toString()
6981       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
6982   } else {
6983     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6984                           << CS.toString() << /*conversion specifier*/1,
6985                          getLocationOfByte(CS.getStart()),
6986                          /*IsStringLocation*/true,
6987                          getSpecifierRange(startSpecifier, specifierLen));
6988   }
6989 }
6990 
6991 void CheckFormatHandler::HandlePosition(const char *startPos,
6992                                         unsigned posLen) {
6993   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
6994                                getLocationOfByte(startPos),
6995                                /*IsStringLocation*/true,
6996                                getSpecifierRange(startPos, posLen));
6997 }
6998 
6999 void
7000 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
7001                                      analyze_format_string::PositionContext p) {
7002   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
7003                          << (unsigned) p,
7004                        getLocationOfByte(startPos), /*IsStringLocation*/true,
7005                        getSpecifierRange(startPos, posLen));
7006 }
7007 
7008 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
7009                                             unsigned posLen) {
7010   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
7011                                getLocationOfByte(startPos),
7012                                /*IsStringLocation*/true,
7013                                getSpecifierRange(startPos, posLen));
7014 }
7015 
7016 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
7017   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
7018     // The presence of a null character is likely an error.
7019     EmitFormatDiagnostic(
7020       S.PDiag(diag::warn_printf_format_string_contains_null_char),
7021       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
7022       getFormatStringRange());
7023   }
7024 }
7025 
7026 // Note that this may return NULL if there was an error parsing or building
7027 // one of the argument expressions.
7028 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
7029   return Args[FirstDataArg + i];
7030 }
7031 
7032 void CheckFormatHandler::DoneProcessing() {
7033   // Does the number of data arguments exceed the number of
7034   // format conversions in the format string?
7035   if (!HasVAListArg) {
7036       // Find any arguments that weren't covered.
7037     CoveredArgs.flip();
7038     signed notCoveredArg = CoveredArgs.find_first();
7039     if (notCoveredArg >= 0) {
7040       assert((unsigned)notCoveredArg < NumDataArgs);
7041       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
7042     } else {
7043       UncoveredArg.setAllCovered();
7044     }
7045   }
7046 }
7047 
7048 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7049                                    const Expr *ArgExpr) {
7050   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
7051          "Invalid state");
7052 
7053   if (!ArgExpr)
7054     return;
7055 
7056   SourceLocation Loc = ArgExpr->getBeginLoc();
7057 
7058   if (S.getSourceManager().isInSystemMacro(Loc))
7059     return;
7060 
7061   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
7062   for (auto E : DiagnosticExprs)
7063     PDiag << E->getSourceRange();
7064 
7065   CheckFormatHandler::EmitFormatDiagnostic(
7066                                   S, IsFunctionCall, DiagnosticExprs[0],
7067                                   PDiag, Loc, /*IsStringLocation*/false,
7068                                   DiagnosticExprs[0]->getSourceRange());
7069 }
7070 
7071 bool
7072 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7073                                                      SourceLocation Loc,
7074                                                      const char *startSpec,
7075                                                      unsigned specifierLen,
7076                                                      const char *csStart,
7077                                                      unsigned csLen) {
7078   bool keepGoing = true;
7079   if (argIndex < NumDataArgs) {
7080     // Consider the argument coverered, even though the specifier doesn't
7081     // make sense.
7082     CoveredArgs.set(argIndex);
7083   }
7084   else {
7085     // If argIndex exceeds the number of data arguments we
7086     // don't issue a warning because that is just a cascade of warnings (and
7087     // they may have intended '%%' anyway). We don't want to continue processing
7088     // the format string after this point, however, as we will like just get
7089     // gibberish when trying to match arguments.
7090     keepGoing = false;
7091   }
7092 
7093   StringRef Specifier(csStart, csLen);
7094 
7095   // If the specifier in non-printable, it could be the first byte of a UTF-8
7096   // sequence. In that case, print the UTF-8 code point. If not, print the byte
7097   // hex value.
7098   std::string CodePointStr;
7099   if (!llvm::sys::locale::isPrint(*csStart)) {
7100     llvm::UTF32 CodePoint;
7101     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7102     const llvm::UTF8 *E =
7103         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7104     llvm::ConversionResult Result =
7105         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
7106 
7107     if (Result != llvm::conversionOK) {
7108       unsigned char FirstChar = *csStart;
7109       CodePoint = (llvm::UTF32)FirstChar;
7110     }
7111 
7112     llvm::raw_string_ostream OS(CodePointStr);
7113     if (CodePoint < 256)
7114       OS << "\\x" << llvm::format("%02x", CodePoint);
7115     else if (CodePoint <= 0xFFFF)
7116       OS << "\\u" << llvm::format("%04x", CodePoint);
7117     else
7118       OS << "\\U" << llvm::format("%08x", CodePoint);
7119     OS.flush();
7120     Specifier = CodePointStr;
7121   }
7122 
7123   EmitFormatDiagnostic(
7124       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
7125       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
7126 
7127   return keepGoing;
7128 }
7129 
7130 void
7131 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7132                                                       const char *startSpec,
7133                                                       unsigned specifierLen) {
7134   EmitFormatDiagnostic(
7135     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
7136     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
7137 }
7138 
7139 bool
7140 CheckFormatHandler::CheckNumArgs(
7141   const analyze_format_string::FormatSpecifier &FS,
7142   const analyze_format_string::ConversionSpecifier &CS,
7143   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7144 
7145   if (argIndex >= NumDataArgs) {
7146     PartialDiagnostic PDiag = FS.usesPositionalArg()
7147       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
7148            << (argIndex+1) << NumDataArgs)
7149       : S.PDiag(diag::warn_printf_insufficient_data_args);
7150     EmitFormatDiagnostic(
7151       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
7152       getSpecifierRange(startSpecifier, specifierLen));
7153 
7154     // Since more arguments than conversion tokens are given, by extension
7155     // all arguments are covered, so mark this as so.
7156     UncoveredArg.setAllCovered();
7157     return false;
7158   }
7159   return true;
7160 }
7161 
7162 template<typename Range>
7163 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
7164                                               SourceLocation Loc,
7165                                               bool IsStringLocation,
7166                                               Range StringRange,
7167                                               ArrayRef<FixItHint> FixIt) {
7168   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
7169                        Loc, IsStringLocation, StringRange, FixIt);
7170 }
7171 
7172 /// If the format string is not within the function call, emit a note
7173 /// so that the function call and string are in diagnostic messages.
7174 ///
7175 /// \param InFunctionCall if true, the format string is within the function
7176 /// call and only one diagnostic message will be produced.  Otherwise, an
7177 /// extra note will be emitted pointing to location of the format string.
7178 ///
7179 /// \param ArgumentExpr the expression that is passed as the format string
7180 /// argument in the function call.  Used for getting locations when two
7181 /// diagnostics are emitted.
7182 ///
7183 /// \param PDiag the callee should already have provided any strings for the
7184 /// diagnostic message.  This function only adds locations and fixits
7185 /// to diagnostics.
7186 ///
7187 /// \param Loc primary location for diagnostic.  If two diagnostics are
7188 /// required, one will be at Loc and a new SourceLocation will be created for
7189 /// the other one.
7190 ///
7191 /// \param IsStringLocation if true, Loc points to the format string should be
7192 /// used for the note.  Otherwise, Loc points to the argument list and will
7193 /// be used with PDiag.
7194 ///
7195 /// \param StringRange some or all of the string to highlight.  This is
7196 /// templated so it can accept either a CharSourceRange or a SourceRange.
7197 ///
7198 /// \param FixIt optional fix it hint for the format string.
7199 template <typename Range>
7200 void CheckFormatHandler::EmitFormatDiagnostic(
7201     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
7202     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
7203     Range StringRange, ArrayRef<FixItHint> FixIt) {
7204   if (InFunctionCall) {
7205     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
7206     D << StringRange;
7207     D << FixIt;
7208   } else {
7209     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
7210       << ArgumentExpr->getSourceRange();
7211 
7212     const Sema::SemaDiagnosticBuilder &Note =
7213       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
7214              diag::note_format_string_defined);
7215 
7216     Note << StringRange;
7217     Note << FixIt;
7218   }
7219 }
7220 
7221 //===--- CHECK: Printf format string checking ------------------------------===//
7222 
7223 namespace {
7224 
7225 class CheckPrintfHandler : public CheckFormatHandler {
7226 public:
7227   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7228                      const Expr *origFormatExpr,
7229                      const Sema::FormatStringType type, unsigned firstDataArg,
7230                      unsigned numDataArgs, bool isObjC, const char *beg,
7231                      bool hasVAListArg, ArrayRef<const Expr *> Args,
7232                      unsigned formatIdx, bool inFunctionCall,
7233                      Sema::VariadicCallType CallType,
7234                      llvm::SmallBitVector &CheckedVarArgs,
7235                      UncoveredArgHandler &UncoveredArg)
7236       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7237                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
7238                            inFunctionCall, CallType, CheckedVarArgs,
7239                            UncoveredArg) {}
7240 
7241   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
7242 
7243   /// Returns true if '%@' specifiers are allowed in the format string.
7244   bool allowsObjCArg() const {
7245     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
7246            FSType == Sema::FST_OSTrace;
7247   }
7248 
7249   bool HandleInvalidPrintfConversionSpecifier(
7250                                       const analyze_printf::PrintfSpecifier &FS,
7251                                       const char *startSpecifier,
7252                                       unsigned specifierLen) override;
7253 
7254   void handleInvalidMaskType(StringRef MaskType) override;
7255 
7256   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7257                              const char *startSpecifier,
7258                              unsigned specifierLen) override;
7259   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7260                        const char *StartSpecifier,
7261                        unsigned SpecifierLen,
7262                        const Expr *E);
7263 
7264   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
7265                     const char *startSpecifier, unsigned specifierLen);
7266   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
7267                            const analyze_printf::OptionalAmount &Amt,
7268                            unsigned type,
7269                            const char *startSpecifier, unsigned specifierLen);
7270   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7271                   const analyze_printf::OptionalFlag &flag,
7272                   const char *startSpecifier, unsigned specifierLen);
7273   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
7274                          const analyze_printf::OptionalFlag &ignoredFlag,
7275                          const analyze_printf::OptionalFlag &flag,
7276                          const char *startSpecifier, unsigned specifierLen);
7277   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
7278                            const Expr *E);
7279 
7280   void HandleEmptyObjCModifierFlag(const char *startFlag,
7281                                    unsigned flagLen) override;
7282 
7283   void HandleInvalidObjCModifierFlag(const char *startFlag,
7284                                             unsigned flagLen) override;
7285 
7286   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
7287                                            const char *flagsEnd,
7288                                            const char *conversionPosition)
7289                                              override;
7290 };
7291 
7292 } // namespace
7293 
7294 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
7295                                       const analyze_printf::PrintfSpecifier &FS,
7296                                       const char *startSpecifier,
7297                                       unsigned specifierLen) {
7298   const analyze_printf::PrintfConversionSpecifier &CS =
7299     FS.getConversionSpecifier();
7300 
7301   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7302                                           getLocationOfByte(CS.getStart()),
7303                                           startSpecifier, specifierLen,
7304                                           CS.getStart(), CS.getLength());
7305 }
7306 
7307 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
7308   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
7309 }
7310 
7311 bool CheckPrintfHandler::HandleAmount(
7312                                const analyze_format_string::OptionalAmount &Amt,
7313                                unsigned k, const char *startSpecifier,
7314                                unsigned specifierLen) {
7315   if (Amt.hasDataArgument()) {
7316     if (!HasVAListArg) {
7317       unsigned argIndex = Amt.getArgIndex();
7318       if (argIndex >= NumDataArgs) {
7319         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
7320                                << k,
7321                              getLocationOfByte(Amt.getStart()),
7322                              /*IsStringLocation*/true,
7323                              getSpecifierRange(startSpecifier, specifierLen));
7324         // Don't do any more checking.  We will just emit
7325         // spurious errors.
7326         return false;
7327       }
7328 
7329       // Type check the data argument.  It should be an 'int'.
7330       // Although not in conformance with C99, we also allow the argument to be
7331       // an 'unsigned int' as that is a reasonably safe case.  GCC also
7332       // doesn't emit a warning for that case.
7333       CoveredArgs.set(argIndex);
7334       const Expr *Arg = getDataArg(argIndex);
7335       if (!Arg)
7336         return false;
7337 
7338       QualType T = Arg->getType();
7339 
7340       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
7341       assert(AT.isValid());
7342 
7343       if (!AT.matchesType(S.Context, T)) {
7344         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
7345                                << k << AT.getRepresentativeTypeName(S.Context)
7346                                << T << Arg->getSourceRange(),
7347                              getLocationOfByte(Amt.getStart()),
7348                              /*IsStringLocation*/true,
7349                              getSpecifierRange(startSpecifier, specifierLen));
7350         // Don't do any more checking.  We will just emit
7351         // spurious errors.
7352         return false;
7353       }
7354     }
7355   }
7356   return true;
7357 }
7358 
7359 void CheckPrintfHandler::HandleInvalidAmount(
7360                                       const analyze_printf::PrintfSpecifier &FS,
7361                                       const analyze_printf::OptionalAmount &Amt,
7362                                       unsigned type,
7363                                       const char *startSpecifier,
7364                                       unsigned specifierLen) {
7365   const analyze_printf::PrintfConversionSpecifier &CS =
7366     FS.getConversionSpecifier();
7367 
7368   FixItHint fixit =
7369     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
7370       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
7371                                  Amt.getConstantLength()))
7372       : FixItHint();
7373 
7374   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
7375                          << type << CS.toString(),
7376                        getLocationOfByte(Amt.getStart()),
7377                        /*IsStringLocation*/true,
7378                        getSpecifierRange(startSpecifier, specifierLen),
7379                        fixit);
7380 }
7381 
7382 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7383                                     const analyze_printf::OptionalFlag &flag,
7384                                     const char *startSpecifier,
7385                                     unsigned specifierLen) {
7386   // Warn about pointless flag with a fixit removal.
7387   const analyze_printf::PrintfConversionSpecifier &CS =
7388     FS.getConversionSpecifier();
7389   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
7390                          << flag.toString() << CS.toString(),
7391                        getLocationOfByte(flag.getPosition()),
7392                        /*IsStringLocation*/true,
7393                        getSpecifierRange(startSpecifier, specifierLen),
7394                        FixItHint::CreateRemoval(
7395                          getSpecifierRange(flag.getPosition(), 1)));
7396 }
7397 
7398 void CheckPrintfHandler::HandleIgnoredFlag(
7399                                 const analyze_printf::PrintfSpecifier &FS,
7400                                 const analyze_printf::OptionalFlag &ignoredFlag,
7401                                 const analyze_printf::OptionalFlag &flag,
7402                                 const char *startSpecifier,
7403                                 unsigned specifierLen) {
7404   // Warn about ignored flag with a fixit removal.
7405   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
7406                          << ignoredFlag.toString() << flag.toString(),
7407                        getLocationOfByte(ignoredFlag.getPosition()),
7408                        /*IsStringLocation*/true,
7409                        getSpecifierRange(startSpecifier, specifierLen),
7410                        FixItHint::CreateRemoval(
7411                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
7412 }
7413 
7414 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
7415                                                      unsigned flagLen) {
7416   // Warn about an empty flag.
7417   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
7418                        getLocationOfByte(startFlag),
7419                        /*IsStringLocation*/true,
7420                        getSpecifierRange(startFlag, flagLen));
7421 }
7422 
7423 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
7424                                                        unsigned flagLen) {
7425   // Warn about an invalid flag.
7426   auto Range = getSpecifierRange(startFlag, flagLen);
7427   StringRef flag(startFlag, flagLen);
7428   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
7429                       getLocationOfByte(startFlag),
7430                       /*IsStringLocation*/true,
7431                       Range, FixItHint::CreateRemoval(Range));
7432 }
7433 
7434 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
7435     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
7436     // Warn about using '[...]' without a '@' conversion.
7437     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
7438     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
7439     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
7440                          getLocationOfByte(conversionPosition),
7441                          /*IsStringLocation*/true,
7442                          Range, FixItHint::CreateRemoval(Range));
7443 }
7444 
7445 // Determines if the specified is a C++ class or struct containing
7446 // a member with the specified name and kind (e.g. a CXXMethodDecl named
7447 // "c_str()").
7448 template<typename MemberKind>
7449 static llvm::SmallPtrSet<MemberKind*, 1>
7450 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
7451   const RecordType *RT = Ty->getAs<RecordType>();
7452   llvm::SmallPtrSet<MemberKind*, 1> Results;
7453 
7454   if (!RT)
7455     return Results;
7456   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
7457   if (!RD || !RD->getDefinition())
7458     return Results;
7459 
7460   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
7461                  Sema::LookupMemberName);
7462   R.suppressDiagnostics();
7463 
7464   // We just need to include all members of the right kind turned up by the
7465   // filter, at this point.
7466   if (S.LookupQualifiedName(R, RT->getDecl()))
7467     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7468       NamedDecl *decl = (*I)->getUnderlyingDecl();
7469       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
7470         Results.insert(FK);
7471     }
7472   return Results;
7473 }
7474 
7475 /// Check if we could call '.c_str()' on an object.
7476 ///
7477 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
7478 /// allow the call, or if it would be ambiguous).
7479 bool Sema::hasCStrMethod(const Expr *E) {
7480   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7481 
7482   MethodSet Results =
7483       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
7484   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7485        MI != ME; ++MI)
7486     if ((*MI)->getMinRequiredArguments() == 0)
7487       return true;
7488   return false;
7489 }
7490 
7491 // Check if a (w)string was passed when a (w)char* was needed, and offer a
7492 // better diagnostic if so. AT is assumed to be valid.
7493 // Returns true when a c_str() conversion method is found.
7494 bool CheckPrintfHandler::checkForCStrMembers(
7495     const analyze_printf::ArgType &AT, const Expr *E) {
7496   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7497 
7498   MethodSet Results =
7499       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
7500 
7501   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7502        MI != ME; ++MI) {
7503     const CXXMethodDecl *Method = *MI;
7504     if (Method->getMinRequiredArguments() == 0 &&
7505         AT.matchesType(S.Context, Method->getReturnType())) {
7506       // FIXME: Suggest parens if the expression needs them.
7507       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
7508       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
7509           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
7510       return true;
7511     }
7512   }
7513 
7514   return false;
7515 }
7516 
7517 bool
7518 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
7519                                             &FS,
7520                                           const char *startSpecifier,
7521                                           unsigned specifierLen) {
7522   using namespace analyze_format_string;
7523   using namespace analyze_printf;
7524 
7525   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
7526 
7527   if (FS.consumesDataArgument()) {
7528     if (atFirstArg) {
7529         atFirstArg = false;
7530         usesPositionalArgs = FS.usesPositionalArg();
7531     }
7532     else if (usesPositionalArgs != FS.usesPositionalArg()) {
7533       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
7534                                         startSpecifier, specifierLen);
7535       return false;
7536     }
7537   }
7538 
7539   // First check if the field width, precision, and conversion specifier
7540   // have matching data arguments.
7541   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
7542                     startSpecifier, specifierLen)) {
7543     return false;
7544   }
7545 
7546   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
7547                     startSpecifier, specifierLen)) {
7548     return false;
7549   }
7550 
7551   if (!CS.consumesDataArgument()) {
7552     // FIXME: Technically specifying a precision or field width here
7553     // makes no sense.  Worth issuing a warning at some point.
7554     return true;
7555   }
7556 
7557   // Consume the argument.
7558   unsigned argIndex = FS.getArgIndex();
7559   if (argIndex < NumDataArgs) {
7560     // The check to see if the argIndex is valid will come later.
7561     // We set the bit here because we may exit early from this
7562     // function if we encounter some other error.
7563     CoveredArgs.set(argIndex);
7564   }
7565 
7566   // FreeBSD kernel extensions.
7567   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
7568       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
7569     // We need at least two arguments.
7570     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
7571       return false;
7572 
7573     // Claim the second argument.
7574     CoveredArgs.set(argIndex + 1);
7575 
7576     // Type check the first argument (int for %b, pointer for %D)
7577     const Expr *Ex = getDataArg(argIndex);
7578     const analyze_printf::ArgType &AT =
7579       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
7580         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
7581     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
7582       EmitFormatDiagnostic(
7583           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7584               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
7585               << false << Ex->getSourceRange(),
7586           Ex->getBeginLoc(), /*IsStringLocation*/ false,
7587           getSpecifierRange(startSpecifier, specifierLen));
7588 
7589     // Type check the second argument (char * for both %b and %D)
7590     Ex = getDataArg(argIndex + 1);
7591     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
7592     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
7593       EmitFormatDiagnostic(
7594           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7595               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
7596               << false << Ex->getSourceRange(),
7597           Ex->getBeginLoc(), /*IsStringLocation*/ false,
7598           getSpecifierRange(startSpecifier, specifierLen));
7599 
7600      return true;
7601   }
7602 
7603   // Check for using an Objective-C specific conversion specifier
7604   // in a non-ObjC literal.
7605   if (!allowsObjCArg() && CS.isObjCArg()) {
7606     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7607                                                   specifierLen);
7608   }
7609 
7610   // %P can only be used with os_log.
7611   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
7612     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7613                                                   specifierLen);
7614   }
7615 
7616   // %n is not allowed with os_log.
7617   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
7618     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
7619                          getLocationOfByte(CS.getStart()),
7620                          /*IsStringLocation*/ false,
7621                          getSpecifierRange(startSpecifier, specifierLen));
7622 
7623     return true;
7624   }
7625 
7626   // Only scalars are allowed for os_trace.
7627   if (FSType == Sema::FST_OSTrace &&
7628       (CS.getKind() == ConversionSpecifier::PArg ||
7629        CS.getKind() == ConversionSpecifier::sArg ||
7630        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
7631     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7632                                                   specifierLen);
7633   }
7634 
7635   // Check for use of public/private annotation outside of os_log().
7636   if (FSType != Sema::FST_OSLog) {
7637     if (FS.isPublic().isSet()) {
7638       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7639                                << "public",
7640                            getLocationOfByte(FS.isPublic().getPosition()),
7641                            /*IsStringLocation*/ false,
7642                            getSpecifierRange(startSpecifier, specifierLen));
7643     }
7644     if (FS.isPrivate().isSet()) {
7645       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7646                                << "private",
7647                            getLocationOfByte(FS.isPrivate().getPosition()),
7648                            /*IsStringLocation*/ false,
7649                            getSpecifierRange(startSpecifier, specifierLen));
7650     }
7651   }
7652 
7653   // Check for invalid use of field width
7654   if (!FS.hasValidFieldWidth()) {
7655     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
7656         startSpecifier, specifierLen);
7657   }
7658 
7659   // Check for invalid use of precision
7660   if (!FS.hasValidPrecision()) {
7661     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
7662         startSpecifier, specifierLen);
7663   }
7664 
7665   // Precision is mandatory for %P specifier.
7666   if (CS.getKind() == ConversionSpecifier::PArg &&
7667       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
7668     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
7669                          getLocationOfByte(startSpecifier),
7670                          /*IsStringLocation*/ false,
7671                          getSpecifierRange(startSpecifier, specifierLen));
7672   }
7673 
7674   // Check each flag does not conflict with any other component.
7675   if (!FS.hasValidThousandsGroupingPrefix())
7676     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
7677   if (!FS.hasValidLeadingZeros())
7678     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
7679   if (!FS.hasValidPlusPrefix())
7680     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
7681   if (!FS.hasValidSpacePrefix())
7682     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
7683   if (!FS.hasValidAlternativeForm())
7684     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
7685   if (!FS.hasValidLeftJustified())
7686     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
7687 
7688   // Check that flags are not ignored by another flag
7689   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
7690     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
7691         startSpecifier, specifierLen);
7692   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
7693     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
7694             startSpecifier, specifierLen);
7695 
7696   // Check the length modifier is valid with the given conversion specifier.
7697   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
7698                                  S.getLangOpts()))
7699     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7700                                 diag::warn_format_nonsensical_length);
7701   else if (!FS.hasStandardLengthModifier())
7702     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
7703   else if (!FS.hasStandardLengthConversionCombination())
7704     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7705                                 diag::warn_format_non_standard_conversion_spec);
7706 
7707   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
7708     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
7709 
7710   // The remaining checks depend on the data arguments.
7711   if (HasVAListArg)
7712     return true;
7713 
7714   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
7715     return false;
7716 
7717   const Expr *Arg = getDataArg(argIndex);
7718   if (!Arg)
7719     return true;
7720 
7721   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
7722 }
7723 
7724 static bool requiresParensToAddCast(const Expr *E) {
7725   // FIXME: We should have a general way to reason about operator
7726   // precedence and whether parens are actually needed here.
7727   // Take care of a few common cases where they aren't.
7728   const Expr *Inside = E->IgnoreImpCasts();
7729   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
7730     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
7731 
7732   switch (Inside->getStmtClass()) {
7733   case Stmt::ArraySubscriptExprClass:
7734   case Stmt::CallExprClass:
7735   case Stmt::CharacterLiteralClass:
7736   case Stmt::CXXBoolLiteralExprClass:
7737   case Stmt::DeclRefExprClass:
7738   case Stmt::FloatingLiteralClass:
7739   case Stmt::IntegerLiteralClass:
7740   case Stmt::MemberExprClass:
7741   case Stmt::ObjCArrayLiteralClass:
7742   case Stmt::ObjCBoolLiteralExprClass:
7743   case Stmt::ObjCBoxedExprClass:
7744   case Stmt::ObjCDictionaryLiteralClass:
7745   case Stmt::ObjCEncodeExprClass:
7746   case Stmt::ObjCIvarRefExprClass:
7747   case Stmt::ObjCMessageExprClass:
7748   case Stmt::ObjCPropertyRefExprClass:
7749   case Stmt::ObjCStringLiteralClass:
7750   case Stmt::ObjCSubscriptRefExprClass:
7751   case Stmt::ParenExprClass:
7752   case Stmt::StringLiteralClass:
7753   case Stmt::UnaryOperatorClass:
7754     return false;
7755   default:
7756     return true;
7757   }
7758 }
7759 
7760 static std::pair<QualType, StringRef>
7761 shouldNotPrintDirectly(const ASTContext &Context,
7762                        QualType IntendedTy,
7763                        const Expr *E) {
7764   // Use a 'while' to peel off layers of typedefs.
7765   QualType TyTy = IntendedTy;
7766   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
7767     StringRef Name = UserTy->getDecl()->getName();
7768     QualType CastTy = llvm::StringSwitch<QualType>(Name)
7769       .Case("CFIndex", Context.getNSIntegerType())
7770       .Case("NSInteger", Context.getNSIntegerType())
7771       .Case("NSUInteger", Context.getNSUIntegerType())
7772       .Case("SInt32", Context.IntTy)
7773       .Case("UInt32", Context.UnsignedIntTy)
7774       .Default(QualType());
7775 
7776     if (!CastTy.isNull())
7777       return std::make_pair(CastTy, Name);
7778 
7779     TyTy = UserTy->desugar();
7780   }
7781 
7782   // Strip parens if necessary.
7783   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
7784     return shouldNotPrintDirectly(Context,
7785                                   PE->getSubExpr()->getType(),
7786                                   PE->getSubExpr());
7787 
7788   // If this is a conditional expression, then its result type is constructed
7789   // via usual arithmetic conversions and thus there might be no necessary
7790   // typedef sugar there.  Recurse to operands to check for NSInteger &
7791   // Co. usage condition.
7792   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
7793     QualType TrueTy, FalseTy;
7794     StringRef TrueName, FalseName;
7795 
7796     std::tie(TrueTy, TrueName) =
7797       shouldNotPrintDirectly(Context,
7798                              CO->getTrueExpr()->getType(),
7799                              CO->getTrueExpr());
7800     std::tie(FalseTy, FalseName) =
7801       shouldNotPrintDirectly(Context,
7802                              CO->getFalseExpr()->getType(),
7803                              CO->getFalseExpr());
7804 
7805     if (TrueTy == FalseTy)
7806       return std::make_pair(TrueTy, TrueName);
7807     else if (TrueTy.isNull())
7808       return std::make_pair(FalseTy, FalseName);
7809     else if (FalseTy.isNull())
7810       return std::make_pair(TrueTy, TrueName);
7811   }
7812 
7813   return std::make_pair(QualType(), StringRef());
7814 }
7815 
7816 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
7817 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
7818 /// type do not count.
7819 static bool
7820 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
7821   QualType From = ICE->getSubExpr()->getType();
7822   QualType To = ICE->getType();
7823   // It's an integer promotion if the destination type is the promoted
7824   // source type.
7825   if (ICE->getCastKind() == CK_IntegralCast &&
7826       From->isPromotableIntegerType() &&
7827       S.Context.getPromotedIntegerType(From) == To)
7828     return true;
7829   // Look through vector types, since we do default argument promotion for
7830   // those in OpenCL.
7831   if (const auto *VecTy = From->getAs<ExtVectorType>())
7832     From = VecTy->getElementType();
7833   if (const auto *VecTy = To->getAs<ExtVectorType>())
7834     To = VecTy->getElementType();
7835   // It's a floating promotion if the source type is a lower rank.
7836   return ICE->getCastKind() == CK_FloatingCast &&
7837          S.Context.getFloatingTypeOrder(From, To) < 0;
7838 }
7839 
7840 bool
7841 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7842                                     const char *StartSpecifier,
7843                                     unsigned SpecifierLen,
7844                                     const Expr *E) {
7845   using namespace analyze_format_string;
7846   using namespace analyze_printf;
7847 
7848   // Now type check the data expression that matches the
7849   // format specifier.
7850   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
7851   if (!AT.isValid())
7852     return true;
7853 
7854   QualType ExprTy = E->getType();
7855   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
7856     ExprTy = TET->getUnderlyingExpr()->getType();
7857   }
7858 
7859   // Diagnose attempts to print a boolean value as a character. Unlike other
7860   // -Wformat diagnostics, this is fine from a type perspective, but it still
7861   // doesn't make sense.
7862   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
7863       E->isKnownToHaveBooleanValue()) {
7864     const CharSourceRange &CSR =
7865         getSpecifierRange(StartSpecifier, SpecifierLen);
7866     SmallString<4> FSString;
7867     llvm::raw_svector_ostream os(FSString);
7868     FS.toString(os);
7869     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
7870                              << FSString,
7871                          E->getExprLoc(), false, CSR);
7872     return true;
7873   }
7874 
7875   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
7876   if (Match == analyze_printf::ArgType::Match)
7877     return true;
7878 
7879   // Look through argument promotions for our error message's reported type.
7880   // This includes the integral and floating promotions, but excludes array
7881   // and function pointer decay (seeing that an argument intended to be a
7882   // string has type 'char [6]' is probably more confusing than 'char *') and
7883   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
7884   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
7885     if (isArithmeticArgumentPromotion(S, ICE)) {
7886       E = ICE->getSubExpr();
7887       ExprTy = E->getType();
7888 
7889       // Check if we didn't match because of an implicit cast from a 'char'
7890       // or 'short' to an 'int'.  This is done because printf is a varargs
7891       // function.
7892       if (ICE->getType() == S.Context.IntTy ||
7893           ICE->getType() == S.Context.UnsignedIntTy) {
7894         // All further checking is done on the subexpression
7895         const analyze_printf::ArgType::MatchKind ImplicitMatch =
7896             AT.matchesType(S.Context, ExprTy);
7897         if (ImplicitMatch == analyze_printf::ArgType::Match)
7898           return true;
7899         if (ImplicitMatch == ArgType::NoMatchPedantic ||
7900             ImplicitMatch == ArgType::NoMatchTypeConfusion)
7901           Match = ImplicitMatch;
7902       }
7903     }
7904   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
7905     // Special case for 'a', which has type 'int' in C.
7906     // Note, however, that we do /not/ want to treat multibyte constants like
7907     // 'MooV' as characters! This form is deprecated but still exists.
7908     if (ExprTy == S.Context.IntTy)
7909       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
7910         ExprTy = S.Context.CharTy;
7911   }
7912 
7913   // Look through enums to their underlying type.
7914   bool IsEnum = false;
7915   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
7916     ExprTy = EnumTy->getDecl()->getIntegerType();
7917     IsEnum = true;
7918   }
7919 
7920   // %C in an Objective-C context prints a unichar, not a wchar_t.
7921   // If the argument is an integer of some kind, believe the %C and suggest
7922   // a cast instead of changing the conversion specifier.
7923   QualType IntendedTy = ExprTy;
7924   if (isObjCContext() &&
7925       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
7926     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
7927         !ExprTy->isCharType()) {
7928       // 'unichar' is defined as a typedef of unsigned short, but we should
7929       // prefer using the typedef if it is visible.
7930       IntendedTy = S.Context.UnsignedShortTy;
7931 
7932       // While we are here, check if the value is an IntegerLiteral that happens
7933       // to be within the valid range.
7934       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
7935         const llvm::APInt &V = IL->getValue();
7936         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
7937           return true;
7938       }
7939 
7940       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
7941                           Sema::LookupOrdinaryName);
7942       if (S.LookupName(Result, S.getCurScope())) {
7943         NamedDecl *ND = Result.getFoundDecl();
7944         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
7945           if (TD->getUnderlyingType() == IntendedTy)
7946             IntendedTy = S.Context.getTypedefType(TD);
7947       }
7948     }
7949   }
7950 
7951   // Special-case some of Darwin's platform-independence types by suggesting
7952   // casts to primitive types that are known to be large enough.
7953   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
7954   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
7955     QualType CastTy;
7956     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
7957     if (!CastTy.isNull()) {
7958       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
7959       // (long in ASTContext). Only complain to pedants.
7960       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
7961           (AT.isSizeT() || AT.isPtrdiffT()) &&
7962           AT.matchesType(S.Context, CastTy))
7963         Match = ArgType::NoMatchPedantic;
7964       IntendedTy = CastTy;
7965       ShouldNotPrintDirectly = true;
7966     }
7967   }
7968 
7969   // We may be able to offer a FixItHint if it is a supported type.
7970   PrintfSpecifier fixedFS = FS;
7971   bool Success =
7972       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
7973 
7974   if (Success) {
7975     // Get the fix string from the fixed format specifier
7976     SmallString<16> buf;
7977     llvm::raw_svector_ostream os(buf);
7978     fixedFS.toString(os);
7979 
7980     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
7981 
7982     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
7983       unsigned Diag;
7984       switch (Match) {
7985       case ArgType::Match: llvm_unreachable("expected non-matching");
7986       case ArgType::NoMatchPedantic:
7987         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
7988         break;
7989       case ArgType::NoMatchTypeConfusion:
7990         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
7991         break;
7992       case ArgType::NoMatch:
7993         Diag = diag::warn_format_conversion_argument_type_mismatch;
7994         break;
7995       }
7996 
7997       // In this case, the specifier is wrong and should be changed to match
7998       // the argument.
7999       EmitFormatDiagnostic(S.PDiag(Diag)
8000                                << AT.getRepresentativeTypeName(S.Context)
8001                                << IntendedTy << IsEnum << E->getSourceRange(),
8002                            E->getBeginLoc(),
8003                            /*IsStringLocation*/ false, SpecRange,
8004                            FixItHint::CreateReplacement(SpecRange, os.str()));
8005     } else {
8006       // The canonical type for formatting this value is different from the
8007       // actual type of the expression. (This occurs, for example, with Darwin's
8008       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
8009       // should be printed as 'long' for 64-bit compatibility.)
8010       // Rather than emitting a normal format/argument mismatch, we want to
8011       // add a cast to the recommended type (and correct the format string
8012       // if necessary).
8013       SmallString<16> CastBuf;
8014       llvm::raw_svector_ostream CastFix(CastBuf);
8015       CastFix << "(";
8016       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
8017       CastFix << ")";
8018 
8019       SmallVector<FixItHint,4> Hints;
8020       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
8021         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
8022 
8023       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
8024         // If there's already a cast present, just replace it.
8025         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
8026         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
8027 
8028       } else if (!requiresParensToAddCast(E)) {
8029         // If the expression has high enough precedence,
8030         // just write the C-style cast.
8031         Hints.push_back(
8032             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8033       } else {
8034         // Otherwise, add parens around the expression as well as the cast.
8035         CastFix << "(";
8036         Hints.push_back(
8037             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8038 
8039         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
8040         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
8041       }
8042 
8043       if (ShouldNotPrintDirectly) {
8044         // The expression has a type that should not be printed directly.
8045         // We extract the name from the typedef because we don't want to show
8046         // the underlying type in the diagnostic.
8047         StringRef Name;
8048         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
8049           Name = TypedefTy->getDecl()->getName();
8050         else
8051           Name = CastTyName;
8052         unsigned Diag = Match == ArgType::NoMatchPedantic
8053                             ? diag::warn_format_argument_needs_cast_pedantic
8054                             : diag::warn_format_argument_needs_cast;
8055         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
8056                                            << E->getSourceRange(),
8057                              E->getBeginLoc(), /*IsStringLocation=*/false,
8058                              SpecRange, Hints);
8059       } else {
8060         // In this case, the expression could be printed using a different
8061         // specifier, but we've decided that the specifier is probably correct
8062         // and we should cast instead. Just use the normal warning message.
8063         EmitFormatDiagnostic(
8064             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8065                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
8066                 << E->getSourceRange(),
8067             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
8068       }
8069     }
8070   } else {
8071     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
8072                                                    SpecifierLen);
8073     // Since the warning for passing non-POD types to variadic functions
8074     // was deferred until now, we emit a warning for non-POD
8075     // arguments here.
8076     switch (S.isValidVarArgType(ExprTy)) {
8077     case Sema::VAK_Valid:
8078     case Sema::VAK_ValidInCXX11: {
8079       unsigned Diag;
8080       switch (Match) {
8081       case ArgType::Match: llvm_unreachable("expected non-matching");
8082       case ArgType::NoMatchPedantic:
8083         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8084         break;
8085       case ArgType::NoMatchTypeConfusion:
8086         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8087         break;
8088       case ArgType::NoMatch:
8089         Diag = diag::warn_format_conversion_argument_type_mismatch;
8090         break;
8091       }
8092 
8093       EmitFormatDiagnostic(
8094           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
8095                         << IsEnum << CSR << E->getSourceRange(),
8096           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8097       break;
8098     }
8099     case Sema::VAK_Undefined:
8100     case Sema::VAK_MSVCUndefined:
8101       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
8102                                << S.getLangOpts().CPlusPlus11 << ExprTy
8103                                << CallType
8104                                << AT.getRepresentativeTypeName(S.Context) << CSR
8105                                << E->getSourceRange(),
8106                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8107       checkForCStrMembers(AT, E);
8108       break;
8109 
8110     case Sema::VAK_Invalid:
8111       if (ExprTy->isObjCObjectType())
8112         EmitFormatDiagnostic(
8113             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
8114                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
8115                 << AT.getRepresentativeTypeName(S.Context) << CSR
8116                 << E->getSourceRange(),
8117             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8118       else
8119         // FIXME: If this is an initializer list, suggest removing the braces
8120         // or inserting a cast to the target type.
8121         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
8122             << isa<InitListExpr>(E) << ExprTy << CallType
8123             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
8124       break;
8125     }
8126 
8127     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
8128            "format string specifier index out of range");
8129     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
8130   }
8131 
8132   return true;
8133 }
8134 
8135 //===--- CHECK: Scanf format string checking ------------------------------===//
8136 
8137 namespace {
8138 
8139 class CheckScanfHandler : public CheckFormatHandler {
8140 public:
8141   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
8142                     const Expr *origFormatExpr, Sema::FormatStringType type,
8143                     unsigned firstDataArg, unsigned numDataArgs,
8144                     const char *beg, bool hasVAListArg,
8145                     ArrayRef<const Expr *> Args, unsigned formatIdx,
8146                     bool inFunctionCall, Sema::VariadicCallType CallType,
8147                     llvm::SmallBitVector &CheckedVarArgs,
8148                     UncoveredArgHandler &UncoveredArg)
8149       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8150                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8151                            inFunctionCall, CallType, CheckedVarArgs,
8152                            UncoveredArg) {}
8153 
8154   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
8155                             const char *startSpecifier,
8156                             unsigned specifierLen) override;
8157 
8158   bool HandleInvalidScanfConversionSpecifier(
8159           const analyze_scanf::ScanfSpecifier &FS,
8160           const char *startSpecifier,
8161           unsigned specifierLen) override;
8162 
8163   void HandleIncompleteScanList(const char *start, const char *end) override;
8164 };
8165 
8166 } // namespace
8167 
8168 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
8169                                                  const char *end) {
8170   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
8171                        getLocationOfByte(end), /*IsStringLocation*/true,
8172                        getSpecifierRange(start, end - start));
8173 }
8174 
8175 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
8176                                         const analyze_scanf::ScanfSpecifier &FS,
8177                                         const char *startSpecifier,
8178                                         unsigned specifierLen) {
8179   const analyze_scanf::ScanfConversionSpecifier &CS =
8180     FS.getConversionSpecifier();
8181 
8182   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8183                                           getLocationOfByte(CS.getStart()),
8184                                           startSpecifier, specifierLen,
8185                                           CS.getStart(), CS.getLength());
8186 }
8187 
8188 bool CheckScanfHandler::HandleScanfSpecifier(
8189                                        const analyze_scanf::ScanfSpecifier &FS,
8190                                        const char *startSpecifier,
8191                                        unsigned specifierLen) {
8192   using namespace analyze_scanf;
8193   using namespace analyze_format_string;
8194 
8195   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
8196 
8197   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
8198   // be used to decide if we are using positional arguments consistently.
8199   if (FS.consumesDataArgument()) {
8200     if (atFirstArg) {
8201       atFirstArg = false;
8202       usesPositionalArgs = FS.usesPositionalArg();
8203     }
8204     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8205       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8206                                         startSpecifier, specifierLen);
8207       return false;
8208     }
8209   }
8210 
8211   // Check if the field with is non-zero.
8212   const OptionalAmount &Amt = FS.getFieldWidth();
8213   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
8214     if (Amt.getConstantAmount() == 0) {
8215       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
8216                                                    Amt.getConstantLength());
8217       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
8218                            getLocationOfByte(Amt.getStart()),
8219                            /*IsStringLocation*/true, R,
8220                            FixItHint::CreateRemoval(R));
8221     }
8222   }
8223 
8224   if (!FS.consumesDataArgument()) {
8225     // FIXME: Technically specifying a precision or field width here
8226     // makes no sense.  Worth issuing a warning at some point.
8227     return true;
8228   }
8229 
8230   // Consume the argument.
8231   unsigned argIndex = FS.getArgIndex();
8232   if (argIndex < NumDataArgs) {
8233       // The check to see if the argIndex is valid will come later.
8234       // We set the bit here because we may exit early from this
8235       // function if we encounter some other error.
8236     CoveredArgs.set(argIndex);
8237   }
8238 
8239   // Check the length modifier is valid with the given conversion specifier.
8240   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8241                                  S.getLangOpts()))
8242     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8243                                 diag::warn_format_nonsensical_length);
8244   else if (!FS.hasStandardLengthModifier())
8245     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8246   else if (!FS.hasStandardLengthConversionCombination())
8247     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8248                                 diag::warn_format_non_standard_conversion_spec);
8249 
8250   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8251     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8252 
8253   // The remaining checks depend on the data arguments.
8254   if (HasVAListArg)
8255     return true;
8256 
8257   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8258     return false;
8259 
8260   // Check that the argument type matches the format specifier.
8261   const Expr *Ex = getDataArg(argIndex);
8262   if (!Ex)
8263     return true;
8264 
8265   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
8266 
8267   if (!AT.isValid()) {
8268     return true;
8269   }
8270 
8271   analyze_format_string::ArgType::MatchKind Match =
8272       AT.matchesType(S.Context, Ex->getType());
8273   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
8274   if (Match == analyze_format_string::ArgType::Match)
8275     return true;
8276 
8277   ScanfSpecifier fixedFS = FS;
8278   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
8279                                  S.getLangOpts(), S.Context);
8280 
8281   unsigned Diag =
8282       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8283                : diag::warn_format_conversion_argument_type_mismatch;
8284 
8285   if (Success) {
8286     // Get the fix string from the fixed format specifier.
8287     SmallString<128> buf;
8288     llvm::raw_svector_ostream os(buf);
8289     fixedFS.toString(os);
8290 
8291     EmitFormatDiagnostic(
8292         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
8293                       << Ex->getType() << false << Ex->getSourceRange(),
8294         Ex->getBeginLoc(),
8295         /*IsStringLocation*/ false,
8296         getSpecifierRange(startSpecifier, specifierLen),
8297         FixItHint::CreateReplacement(
8298             getSpecifierRange(startSpecifier, specifierLen), os.str()));
8299   } else {
8300     EmitFormatDiagnostic(S.PDiag(Diag)
8301                              << AT.getRepresentativeTypeName(S.Context)
8302                              << Ex->getType() << false << Ex->getSourceRange(),
8303                          Ex->getBeginLoc(),
8304                          /*IsStringLocation*/ false,
8305                          getSpecifierRange(startSpecifier, specifierLen));
8306   }
8307 
8308   return true;
8309 }
8310 
8311 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
8312                               const Expr *OrigFormatExpr,
8313                               ArrayRef<const Expr *> Args,
8314                               bool HasVAListArg, unsigned format_idx,
8315                               unsigned firstDataArg,
8316                               Sema::FormatStringType Type,
8317                               bool inFunctionCall,
8318                               Sema::VariadicCallType CallType,
8319                               llvm::SmallBitVector &CheckedVarArgs,
8320                               UncoveredArgHandler &UncoveredArg,
8321                               bool IgnoreStringsWithoutSpecifiers) {
8322   // CHECK: is the format string a wide literal?
8323   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
8324     CheckFormatHandler::EmitFormatDiagnostic(
8325         S, inFunctionCall, Args[format_idx],
8326         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
8327         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8328     return;
8329   }
8330 
8331   // Str - The format string.  NOTE: this is NOT null-terminated!
8332   StringRef StrRef = FExpr->getString();
8333   const char *Str = StrRef.data();
8334   // Account for cases where the string literal is truncated in a declaration.
8335   const ConstantArrayType *T =
8336     S.Context.getAsConstantArrayType(FExpr->getType());
8337   assert(T && "String literal not of constant array type!");
8338   size_t TypeSize = T->getSize().getZExtValue();
8339   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8340   const unsigned numDataArgs = Args.size() - firstDataArg;
8341 
8342   if (IgnoreStringsWithoutSpecifiers &&
8343       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
8344           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
8345     return;
8346 
8347   // Emit a warning if the string literal is truncated and does not contain an
8348   // embedded null character.
8349   if (TypeSize <= StrRef.size() &&
8350       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
8351     CheckFormatHandler::EmitFormatDiagnostic(
8352         S, inFunctionCall, Args[format_idx],
8353         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
8354         FExpr->getBeginLoc(),
8355         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
8356     return;
8357   }
8358 
8359   // CHECK: empty format string?
8360   if (StrLen == 0 && numDataArgs > 0) {
8361     CheckFormatHandler::EmitFormatDiagnostic(
8362         S, inFunctionCall, Args[format_idx],
8363         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
8364         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8365     return;
8366   }
8367 
8368   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
8369       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
8370       Type == Sema::FST_OSTrace) {
8371     CheckPrintfHandler H(
8372         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
8373         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
8374         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
8375         CheckedVarArgs, UncoveredArg);
8376 
8377     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
8378                                                   S.getLangOpts(),
8379                                                   S.Context.getTargetInfo(),
8380                                             Type == Sema::FST_FreeBSDKPrintf))
8381       H.DoneProcessing();
8382   } else if (Type == Sema::FST_Scanf) {
8383     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
8384                         numDataArgs, Str, HasVAListArg, Args, format_idx,
8385                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
8386 
8387     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
8388                                                  S.getLangOpts(),
8389                                                  S.Context.getTargetInfo()))
8390       H.DoneProcessing();
8391   } // TODO: handle other formats
8392 }
8393 
8394 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
8395   // Str - The format string.  NOTE: this is NOT null-terminated!
8396   StringRef StrRef = FExpr->getString();
8397   const char *Str = StrRef.data();
8398   // Account for cases where the string literal is truncated in a declaration.
8399   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
8400   assert(T && "String literal not of constant array type!");
8401   size_t TypeSize = T->getSize().getZExtValue();
8402   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8403   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
8404                                                          getLangOpts(),
8405                                                          Context.getTargetInfo());
8406 }
8407 
8408 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
8409 
8410 // Returns the related absolute value function that is larger, of 0 if one
8411 // does not exist.
8412 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
8413   switch (AbsFunction) {
8414   default:
8415     return 0;
8416 
8417   case Builtin::BI__builtin_abs:
8418     return Builtin::BI__builtin_labs;
8419   case Builtin::BI__builtin_labs:
8420     return Builtin::BI__builtin_llabs;
8421   case Builtin::BI__builtin_llabs:
8422     return 0;
8423 
8424   case Builtin::BI__builtin_fabsf:
8425     return Builtin::BI__builtin_fabs;
8426   case Builtin::BI__builtin_fabs:
8427     return Builtin::BI__builtin_fabsl;
8428   case Builtin::BI__builtin_fabsl:
8429     return 0;
8430 
8431   case Builtin::BI__builtin_cabsf:
8432     return Builtin::BI__builtin_cabs;
8433   case Builtin::BI__builtin_cabs:
8434     return Builtin::BI__builtin_cabsl;
8435   case Builtin::BI__builtin_cabsl:
8436     return 0;
8437 
8438   case Builtin::BIabs:
8439     return Builtin::BIlabs;
8440   case Builtin::BIlabs:
8441     return Builtin::BIllabs;
8442   case Builtin::BIllabs:
8443     return 0;
8444 
8445   case Builtin::BIfabsf:
8446     return Builtin::BIfabs;
8447   case Builtin::BIfabs:
8448     return Builtin::BIfabsl;
8449   case Builtin::BIfabsl:
8450     return 0;
8451 
8452   case Builtin::BIcabsf:
8453    return Builtin::BIcabs;
8454   case Builtin::BIcabs:
8455     return Builtin::BIcabsl;
8456   case Builtin::BIcabsl:
8457     return 0;
8458   }
8459 }
8460 
8461 // Returns the argument type of the absolute value function.
8462 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
8463                                              unsigned AbsType) {
8464   if (AbsType == 0)
8465     return QualType();
8466 
8467   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
8468   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
8469   if (Error != ASTContext::GE_None)
8470     return QualType();
8471 
8472   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
8473   if (!FT)
8474     return QualType();
8475 
8476   if (FT->getNumParams() != 1)
8477     return QualType();
8478 
8479   return FT->getParamType(0);
8480 }
8481 
8482 // Returns the best absolute value function, or zero, based on type and
8483 // current absolute value function.
8484 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
8485                                    unsigned AbsFunctionKind) {
8486   unsigned BestKind = 0;
8487   uint64_t ArgSize = Context.getTypeSize(ArgType);
8488   for (unsigned Kind = AbsFunctionKind; Kind != 0;
8489        Kind = getLargerAbsoluteValueFunction(Kind)) {
8490     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
8491     if (Context.getTypeSize(ParamType) >= ArgSize) {
8492       if (BestKind == 0)
8493         BestKind = Kind;
8494       else if (Context.hasSameType(ParamType, ArgType)) {
8495         BestKind = Kind;
8496         break;
8497       }
8498     }
8499   }
8500   return BestKind;
8501 }
8502 
8503 enum AbsoluteValueKind {
8504   AVK_Integer,
8505   AVK_Floating,
8506   AVK_Complex
8507 };
8508 
8509 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
8510   if (T->isIntegralOrEnumerationType())
8511     return AVK_Integer;
8512   if (T->isRealFloatingType())
8513     return AVK_Floating;
8514   if (T->isAnyComplexType())
8515     return AVK_Complex;
8516 
8517   llvm_unreachable("Type not integer, floating, or complex");
8518 }
8519 
8520 // Changes the absolute value function to a different type.  Preserves whether
8521 // the function is a builtin.
8522 static unsigned changeAbsFunction(unsigned AbsKind,
8523                                   AbsoluteValueKind ValueKind) {
8524   switch (ValueKind) {
8525   case AVK_Integer:
8526     switch (AbsKind) {
8527     default:
8528       return 0;
8529     case Builtin::BI__builtin_fabsf:
8530     case Builtin::BI__builtin_fabs:
8531     case Builtin::BI__builtin_fabsl:
8532     case Builtin::BI__builtin_cabsf:
8533     case Builtin::BI__builtin_cabs:
8534     case Builtin::BI__builtin_cabsl:
8535       return Builtin::BI__builtin_abs;
8536     case Builtin::BIfabsf:
8537     case Builtin::BIfabs:
8538     case Builtin::BIfabsl:
8539     case Builtin::BIcabsf:
8540     case Builtin::BIcabs:
8541     case Builtin::BIcabsl:
8542       return Builtin::BIabs;
8543     }
8544   case AVK_Floating:
8545     switch (AbsKind) {
8546     default:
8547       return 0;
8548     case Builtin::BI__builtin_abs:
8549     case Builtin::BI__builtin_labs:
8550     case Builtin::BI__builtin_llabs:
8551     case Builtin::BI__builtin_cabsf:
8552     case Builtin::BI__builtin_cabs:
8553     case Builtin::BI__builtin_cabsl:
8554       return Builtin::BI__builtin_fabsf;
8555     case Builtin::BIabs:
8556     case Builtin::BIlabs:
8557     case Builtin::BIllabs:
8558     case Builtin::BIcabsf:
8559     case Builtin::BIcabs:
8560     case Builtin::BIcabsl:
8561       return Builtin::BIfabsf;
8562     }
8563   case AVK_Complex:
8564     switch (AbsKind) {
8565     default:
8566       return 0;
8567     case Builtin::BI__builtin_abs:
8568     case Builtin::BI__builtin_labs:
8569     case Builtin::BI__builtin_llabs:
8570     case Builtin::BI__builtin_fabsf:
8571     case Builtin::BI__builtin_fabs:
8572     case Builtin::BI__builtin_fabsl:
8573       return Builtin::BI__builtin_cabsf;
8574     case Builtin::BIabs:
8575     case Builtin::BIlabs:
8576     case Builtin::BIllabs:
8577     case Builtin::BIfabsf:
8578     case Builtin::BIfabs:
8579     case Builtin::BIfabsl:
8580       return Builtin::BIcabsf;
8581     }
8582   }
8583   llvm_unreachable("Unable to convert function");
8584 }
8585 
8586 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
8587   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
8588   if (!FnInfo)
8589     return 0;
8590 
8591   switch (FDecl->getBuiltinID()) {
8592   default:
8593     return 0;
8594   case Builtin::BI__builtin_abs:
8595   case Builtin::BI__builtin_fabs:
8596   case Builtin::BI__builtin_fabsf:
8597   case Builtin::BI__builtin_fabsl:
8598   case Builtin::BI__builtin_labs:
8599   case Builtin::BI__builtin_llabs:
8600   case Builtin::BI__builtin_cabs:
8601   case Builtin::BI__builtin_cabsf:
8602   case Builtin::BI__builtin_cabsl:
8603   case Builtin::BIabs:
8604   case Builtin::BIlabs:
8605   case Builtin::BIllabs:
8606   case Builtin::BIfabs:
8607   case Builtin::BIfabsf:
8608   case Builtin::BIfabsl:
8609   case Builtin::BIcabs:
8610   case Builtin::BIcabsf:
8611   case Builtin::BIcabsl:
8612     return FDecl->getBuiltinID();
8613   }
8614   llvm_unreachable("Unknown Builtin type");
8615 }
8616 
8617 // If the replacement is valid, emit a note with replacement function.
8618 // Additionally, suggest including the proper header if not already included.
8619 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
8620                             unsigned AbsKind, QualType ArgType) {
8621   bool EmitHeaderHint = true;
8622   const char *HeaderName = nullptr;
8623   const char *FunctionName = nullptr;
8624   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
8625     FunctionName = "std::abs";
8626     if (ArgType->isIntegralOrEnumerationType()) {
8627       HeaderName = "cstdlib";
8628     } else if (ArgType->isRealFloatingType()) {
8629       HeaderName = "cmath";
8630     } else {
8631       llvm_unreachable("Invalid Type");
8632     }
8633 
8634     // Lookup all std::abs
8635     if (NamespaceDecl *Std = S.getStdNamespace()) {
8636       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
8637       R.suppressDiagnostics();
8638       S.LookupQualifiedName(R, Std);
8639 
8640       for (const auto *I : R) {
8641         const FunctionDecl *FDecl = nullptr;
8642         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
8643           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
8644         } else {
8645           FDecl = dyn_cast<FunctionDecl>(I);
8646         }
8647         if (!FDecl)
8648           continue;
8649 
8650         // Found std::abs(), check that they are the right ones.
8651         if (FDecl->getNumParams() != 1)
8652           continue;
8653 
8654         // Check that the parameter type can handle the argument.
8655         QualType ParamType = FDecl->getParamDecl(0)->getType();
8656         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
8657             S.Context.getTypeSize(ArgType) <=
8658                 S.Context.getTypeSize(ParamType)) {
8659           // Found a function, don't need the header hint.
8660           EmitHeaderHint = false;
8661           break;
8662         }
8663       }
8664     }
8665   } else {
8666     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
8667     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
8668 
8669     if (HeaderName) {
8670       DeclarationName DN(&S.Context.Idents.get(FunctionName));
8671       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
8672       R.suppressDiagnostics();
8673       S.LookupName(R, S.getCurScope());
8674 
8675       if (R.isSingleResult()) {
8676         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
8677         if (FD && FD->getBuiltinID() == AbsKind) {
8678           EmitHeaderHint = false;
8679         } else {
8680           return;
8681         }
8682       } else if (!R.empty()) {
8683         return;
8684       }
8685     }
8686   }
8687 
8688   S.Diag(Loc, diag::note_replace_abs_function)
8689       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
8690 
8691   if (!HeaderName)
8692     return;
8693 
8694   if (!EmitHeaderHint)
8695     return;
8696 
8697   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
8698                                                     << FunctionName;
8699 }
8700 
8701 template <std::size_t StrLen>
8702 static bool IsStdFunction(const FunctionDecl *FDecl,
8703                           const char (&Str)[StrLen]) {
8704   if (!FDecl)
8705     return false;
8706   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
8707     return false;
8708   if (!FDecl->isInStdNamespace())
8709     return false;
8710 
8711   return true;
8712 }
8713 
8714 // Warn when using the wrong abs() function.
8715 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
8716                                       const FunctionDecl *FDecl) {
8717   if (Call->getNumArgs() != 1)
8718     return;
8719 
8720   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
8721   bool IsStdAbs = IsStdFunction(FDecl, "abs");
8722   if (AbsKind == 0 && !IsStdAbs)
8723     return;
8724 
8725   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
8726   QualType ParamType = Call->getArg(0)->getType();
8727 
8728   // Unsigned types cannot be negative.  Suggest removing the absolute value
8729   // function call.
8730   if (ArgType->isUnsignedIntegerType()) {
8731     const char *FunctionName =
8732         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
8733     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
8734     Diag(Call->getExprLoc(), diag::note_remove_abs)
8735         << FunctionName
8736         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
8737     return;
8738   }
8739 
8740   // Taking the absolute value of a pointer is very suspicious, they probably
8741   // wanted to index into an array, dereference a pointer, call a function, etc.
8742   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
8743     unsigned DiagType = 0;
8744     if (ArgType->isFunctionType())
8745       DiagType = 1;
8746     else if (ArgType->isArrayType())
8747       DiagType = 2;
8748 
8749     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
8750     return;
8751   }
8752 
8753   // std::abs has overloads which prevent most of the absolute value problems
8754   // from occurring.
8755   if (IsStdAbs)
8756     return;
8757 
8758   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
8759   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
8760 
8761   // The argument and parameter are the same kind.  Check if they are the right
8762   // size.
8763   if (ArgValueKind == ParamValueKind) {
8764     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
8765       return;
8766 
8767     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
8768     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
8769         << FDecl << ArgType << ParamType;
8770 
8771     if (NewAbsKind == 0)
8772       return;
8773 
8774     emitReplacement(*this, Call->getExprLoc(),
8775                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
8776     return;
8777   }
8778 
8779   // ArgValueKind != ParamValueKind
8780   // The wrong type of absolute value function was used.  Attempt to find the
8781   // proper one.
8782   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
8783   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
8784   if (NewAbsKind == 0)
8785     return;
8786 
8787   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
8788       << FDecl << ParamValueKind << ArgValueKind;
8789 
8790   emitReplacement(*this, Call->getExprLoc(),
8791                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
8792 }
8793 
8794 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
8795 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
8796                                 const FunctionDecl *FDecl) {
8797   if (!Call || !FDecl) return;
8798 
8799   // Ignore template specializations and macros.
8800   if (inTemplateInstantiation()) return;
8801   if (Call->getExprLoc().isMacroID()) return;
8802 
8803   // Only care about the one template argument, two function parameter std::max
8804   if (Call->getNumArgs() != 2) return;
8805   if (!IsStdFunction(FDecl, "max")) return;
8806   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
8807   if (!ArgList) return;
8808   if (ArgList->size() != 1) return;
8809 
8810   // Check that template type argument is unsigned integer.
8811   const auto& TA = ArgList->get(0);
8812   if (TA.getKind() != TemplateArgument::Type) return;
8813   QualType ArgType = TA.getAsType();
8814   if (!ArgType->isUnsignedIntegerType()) return;
8815 
8816   // See if either argument is a literal zero.
8817   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
8818     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
8819     if (!MTE) return false;
8820     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
8821     if (!Num) return false;
8822     if (Num->getValue() != 0) return false;
8823     return true;
8824   };
8825 
8826   const Expr *FirstArg = Call->getArg(0);
8827   const Expr *SecondArg = Call->getArg(1);
8828   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
8829   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
8830 
8831   // Only warn when exactly one argument is zero.
8832   if (IsFirstArgZero == IsSecondArgZero) return;
8833 
8834   SourceRange FirstRange = FirstArg->getSourceRange();
8835   SourceRange SecondRange = SecondArg->getSourceRange();
8836 
8837   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
8838 
8839   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
8840       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
8841 
8842   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
8843   SourceRange RemovalRange;
8844   if (IsFirstArgZero) {
8845     RemovalRange = SourceRange(FirstRange.getBegin(),
8846                                SecondRange.getBegin().getLocWithOffset(-1));
8847   } else {
8848     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
8849                                SecondRange.getEnd());
8850   }
8851 
8852   Diag(Call->getExprLoc(), diag::note_remove_max_call)
8853         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
8854         << FixItHint::CreateRemoval(RemovalRange);
8855 }
8856 
8857 //===--- CHECK: Standard memory functions ---------------------------------===//
8858 
8859 /// Takes the expression passed to the size_t parameter of functions
8860 /// such as memcmp, strncat, etc and warns if it's a comparison.
8861 ///
8862 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
8863 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
8864                                            IdentifierInfo *FnName,
8865                                            SourceLocation FnLoc,
8866                                            SourceLocation RParenLoc) {
8867   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
8868   if (!Size)
8869     return false;
8870 
8871   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
8872   if (!Size->isComparisonOp() && !Size->isLogicalOp())
8873     return false;
8874 
8875   SourceRange SizeRange = Size->getSourceRange();
8876   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
8877       << SizeRange << FnName;
8878   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
8879       << FnName
8880       << FixItHint::CreateInsertion(
8881              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
8882       << FixItHint::CreateRemoval(RParenLoc);
8883   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
8884       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
8885       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
8886                                     ")");
8887 
8888   return true;
8889 }
8890 
8891 /// Determine whether the given type is or contains a dynamic class type
8892 /// (e.g., whether it has a vtable).
8893 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
8894                                                      bool &IsContained) {
8895   // Look through array types while ignoring qualifiers.
8896   const Type *Ty = T->getBaseElementTypeUnsafe();
8897   IsContained = false;
8898 
8899   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
8900   RD = RD ? RD->getDefinition() : nullptr;
8901   if (!RD || RD->isInvalidDecl())
8902     return nullptr;
8903 
8904   if (RD->isDynamicClass())
8905     return RD;
8906 
8907   // Check all the fields.  If any bases were dynamic, the class is dynamic.
8908   // It's impossible for a class to transitively contain itself by value, so
8909   // infinite recursion is impossible.
8910   for (auto *FD : RD->fields()) {
8911     bool SubContained;
8912     if (const CXXRecordDecl *ContainedRD =
8913             getContainedDynamicClass(FD->getType(), SubContained)) {
8914       IsContained = true;
8915       return ContainedRD;
8916     }
8917   }
8918 
8919   return nullptr;
8920 }
8921 
8922 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
8923   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
8924     if (Unary->getKind() == UETT_SizeOf)
8925       return Unary;
8926   return nullptr;
8927 }
8928 
8929 /// If E is a sizeof expression, returns its argument expression,
8930 /// otherwise returns NULL.
8931 static const Expr *getSizeOfExprArg(const Expr *E) {
8932   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
8933     if (!SizeOf->isArgumentType())
8934       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
8935   return nullptr;
8936 }
8937 
8938 /// If E is a sizeof expression, returns its argument type.
8939 static QualType getSizeOfArgType(const Expr *E) {
8940   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
8941     return SizeOf->getTypeOfArgument();
8942   return QualType();
8943 }
8944 
8945 namespace {
8946 
8947 struct SearchNonTrivialToInitializeField
8948     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
8949   using Super =
8950       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
8951 
8952   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
8953 
8954   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
8955                      SourceLocation SL) {
8956     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
8957       asDerived().visitArray(PDIK, AT, SL);
8958       return;
8959     }
8960 
8961     Super::visitWithKind(PDIK, FT, SL);
8962   }
8963 
8964   void visitARCStrong(QualType FT, SourceLocation SL) {
8965     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
8966   }
8967   void visitARCWeak(QualType FT, SourceLocation SL) {
8968     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
8969   }
8970   void visitStruct(QualType FT, SourceLocation SL) {
8971     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
8972       visit(FD->getType(), FD->getLocation());
8973   }
8974   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
8975                   const ArrayType *AT, SourceLocation SL) {
8976     visit(getContext().getBaseElementType(AT), SL);
8977   }
8978   void visitTrivial(QualType FT, SourceLocation SL) {}
8979 
8980   static void diag(QualType RT, const Expr *E, Sema &S) {
8981     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
8982   }
8983 
8984   ASTContext &getContext() { return S.getASTContext(); }
8985 
8986   const Expr *E;
8987   Sema &S;
8988 };
8989 
8990 struct SearchNonTrivialToCopyField
8991     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
8992   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
8993 
8994   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
8995 
8996   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
8997                      SourceLocation SL) {
8998     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
8999       asDerived().visitArray(PCK, AT, SL);
9000       return;
9001     }
9002 
9003     Super::visitWithKind(PCK, FT, SL);
9004   }
9005 
9006   void visitARCStrong(QualType FT, SourceLocation SL) {
9007     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9008   }
9009   void visitARCWeak(QualType FT, SourceLocation SL) {
9010     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9011   }
9012   void visitStruct(QualType FT, SourceLocation SL) {
9013     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9014       visit(FD->getType(), FD->getLocation());
9015   }
9016   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
9017                   SourceLocation SL) {
9018     visit(getContext().getBaseElementType(AT), SL);
9019   }
9020   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
9021                 SourceLocation SL) {}
9022   void visitTrivial(QualType FT, SourceLocation SL) {}
9023   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
9024 
9025   static void diag(QualType RT, const Expr *E, Sema &S) {
9026     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
9027   }
9028 
9029   ASTContext &getContext() { return S.getASTContext(); }
9030 
9031   const Expr *E;
9032   Sema &S;
9033 };
9034 
9035 }
9036 
9037 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
9038 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
9039   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
9040 
9041   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
9042     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
9043       return false;
9044 
9045     return doesExprLikelyComputeSize(BO->getLHS()) ||
9046            doesExprLikelyComputeSize(BO->getRHS());
9047   }
9048 
9049   return getAsSizeOfExpr(SizeofExpr) != nullptr;
9050 }
9051 
9052 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
9053 ///
9054 /// \code
9055 ///   #define MACRO 0
9056 ///   foo(MACRO);
9057 ///   foo(0);
9058 /// \endcode
9059 ///
9060 /// This should return true for the first call to foo, but not for the second
9061 /// (regardless of whether foo is a macro or function).
9062 static bool isArgumentExpandedFromMacro(SourceManager &SM,
9063                                         SourceLocation CallLoc,
9064                                         SourceLocation ArgLoc) {
9065   if (!CallLoc.isMacroID())
9066     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
9067 
9068   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
9069          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
9070 }
9071 
9072 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
9073 /// last two arguments transposed.
9074 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
9075   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
9076     return;
9077 
9078   const Expr *SizeArg =
9079     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
9080 
9081   auto isLiteralZero = [](const Expr *E) {
9082     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
9083   };
9084 
9085   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
9086   SourceLocation CallLoc = Call->getRParenLoc();
9087   SourceManager &SM = S.getSourceManager();
9088   if (isLiteralZero(SizeArg) &&
9089       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
9090 
9091     SourceLocation DiagLoc = SizeArg->getExprLoc();
9092 
9093     // Some platforms #define bzero to __builtin_memset. See if this is the
9094     // case, and if so, emit a better diagnostic.
9095     if (BId == Builtin::BIbzero ||
9096         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
9097                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
9098       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
9099       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
9100     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
9101       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
9102       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
9103     }
9104     return;
9105   }
9106 
9107   // If the second argument to a memset is a sizeof expression and the third
9108   // isn't, this is also likely an error. This should catch
9109   // 'memset(buf, sizeof(buf), 0xff)'.
9110   if (BId == Builtin::BImemset &&
9111       doesExprLikelyComputeSize(Call->getArg(1)) &&
9112       !doesExprLikelyComputeSize(Call->getArg(2))) {
9113     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
9114     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
9115     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
9116     return;
9117   }
9118 }
9119 
9120 /// Check for dangerous or invalid arguments to memset().
9121 ///
9122 /// This issues warnings on known problematic, dangerous or unspecified
9123 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
9124 /// function calls.
9125 ///
9126 /// \param Call The call expression to diagnose.
9127 void Sema::CheckMemaccessArguments(const CallExpr *Call,
9128                                    unsigned BId,
9129                                    IdentifierInfo *FnName) {
9130   assert(BId != 0);
9131 
9132   // It is possible to have a non-standard definition of memset.  Validate
9133   // we have enough arguments, and if not, abort further checking.
9134   unsigned ExpectedNumArgs =
9135       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
9136   if (Call->getNumArgs() < ExpectedNumArgs)
9137     return;
9138 
9139   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
9140                       BId == Builtin::BIstrndup ? 1 : 2);
9141   unsigned LenArg =
9142       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
9143   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
9144 
9145   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
9146                                      Call->getBeginLoc(), Call->getRParenLoc()))
9147     return;
9148 
9149   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
9150   CheckMemaccessSize(*this, BId, Call);
9151 
9152   // We have special checking when the length is a sizeof expression.
9153   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
9154   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
9155   llvm::FoldingSetNodeID SizeOfArgID;
9156 
9157   // Although widely used, 'bzero' is not a standard function. Be more strict
9158   // with the argument types before allowing diagnostics and only allow the
9159   // form bzero(ptr, sizeof(...)).
9160   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9161   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
9162     return;
9163 
9164   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
9165     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
9166     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
9167 
9168     QualType DestTy = Dest->getType();
9169     QualType PointeeTy;
9170     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
9171       PointeeTy = DestPtrTy->getPointeeType();
9172 
9173       // Never warn about void type pointers. This can be used to suppress
9174       // false positives.
9175       if (PointeeTy->isVoidType())
9176         continue;
9177 
9178       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
9179       // actually comparing the expressions for equality. Because computing the
9180       // expression IDs can be expensive, we only do this if the diagnostic is
9181       // enabled.
9182       if (SizeOfArg &&
9183           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
9184                            SizeOfArg->getExprLoc())) {
9185         // We only compute IDs for expressions if the warning is enabled, and
9186         // cache the sizeof arg's ID.
9187         if (SizeOfArgID == llvm::FoldingSetNodeID())
9188           SizeOfArg->Profile(SizeOfArgID, Context, true);
9189         llvm::FoldingSetNodeID DestID;
9190         Dest->Profile(DestID, Context, true);
9191         if (DestID == SizeOfArgID) {
9192           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
9193           //       over sizeof(src) as well.
9194           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
9195           StringRef ReadableName = FnName->getName();
9196 
9197           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
9198             if (UnaryOp->getOpcode() == UO_AddrOf)
9199               ActionIdx = 1; // If its an address-of operator, just remove it.
9200           if (!PointeeTy->isIncompleteType() &&
9201               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
9202             ActionIdx = 2; // If the pointee's size is sizeof(char),
9203                            // suggest an explicit length.
9204 
9205           // If the function is defined as a builtin macro, do not show macro
9206           // expansion.
9207           SourceLocation SL = SizeOfArg->getExprLoc();
9208           SourceRange DSR = Dest->getSourceRange();
9209           SourceRange SSR = SizeOfArg->getSourceRange();
9210           SourceManager &SM = getSourceManager();
9211 
9212           if (SM.isMacroArgExpansion(SL)) {
9213             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
9214             SL = SM.getSpellingLoc(SL);
9215             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
9216                              SM.getSpellingLoc(DSR.getEnd()));
9217             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
9218                              SM.getSpellingLoc(SSR.getEnd()));
9219           }
9220 
9221           DiagRuntimeBehavior(SL, SizeOfArg,
9222                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
9223                                 << ReadableName
9224                                 << PointeeTy
9225                                 << DestTy
9226                                 << DSR
9227                                 << SSR);
9228           DiagRuntimeBehavior(SL, SizeOfArg,
9229                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
9230                                 << ActionIdx
9231                                 << SSR);
9232 
9233           break;
9234         }
9235       }
9236 
9237       // Also check for cases where the sizeof argument is the exact same
9238       // type as the memory argument, and where it points to a user-defined
9239       // record type.
9240       if (SizeOfArgTy != QualType()) {
9241         if (PointeeTy->isRecordType() &&
9242             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
9243           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
9244                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
9245                                 << FnName << SizeOfArgTy << ArgIdx
9246                                 << PointeeTy << Dest->getSourceRange()
9247                                 << LenExpr->getSourceRange());
9248           break;
9249         }
9250       }
9251     } else if (DestTy->isArrayType()) {
9252       PointeeTy = DestTy;
9253     }
9254 
9255     if (PointeeTy == QualType())
9256       continue;
9257 
9258     // Always complain about dynamic classes.
9259     bool IsContained;
9260     if (const CXXRecordDecl *ContainedRD =
9261             getContainedDynamicClass(PointeeTy, IsContained)) {
9262 
9263       unsigned OperationType = 0;
9264       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
9265       // "overwritten" if we're warning about the destination for any call
9266       // but memcmp; otherwise a verb appropriate to the call.
9267       if (ArgIdx != 0 || IsCmp) {
9268         if (BId == Builtin::BImemcpy)
9269           OperationType = 1;
9270         else if(BId == Builtin::BImemmove)
9271           OperationType = 2;
9272         else if (IsCmp)
9273           OperationType = 3;
9274       }
9275 
9276       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9277                           PDiag(diag::warn_dyn_class_memaccess)
9278                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
9279                               << IsContained << ContainedRD << OperationType
9280                               << Call->getCallee()->getSourceRange());
9281     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
9282              BId != Builtin::BImemset)
9283       DiagRuntimeBehavior(
9284         Dest->getExprLoc(), Dest,
9285         PDiag(diag::warn_arc_object_memaccess)
9286           << ArgIdx << FnName << PointeeTy
9287           << Call->getCallee()->getSourceRange());
9288     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
9289       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
9290           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
9291         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9292                             PDiag(diag::warn_cstruct_memaccess)
9293                                 << ArgIdx << FnName << PointeeTy << 0);
9294         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
9295       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
9296                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
9297         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9298                             PDiag(diag::warn_cstruct_memaccess)
9299                                 << ArgIdx << FnName << PointeeTy << 1);
9300         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
9301       } else {
9302         continue;
9303       }
9304     } else
9305       continue;
9306 
9307     DiagRuntimeBehavior(
9308       Dest->getExprLoc(), Dest,
9309       PDiag(diag::note_bad_memaccess_silence)
9310         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
9311     break;
9312   }
9313 }
9314 
9315 // A little helper routine: ignore addition and subtraction of integer literals.
9316 // This intentionally does not ignore all integer constant expressions because
9317 // we don't want to remove sizeof().
9318 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
9319   Ex = Ex->IgnoreParenCasts();
9320 
9321   while (true) {
9322     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
9323     if (!BO || !BO->isAdditiveOp())
9324       break;
9325 
9326     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
9327     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
9328 
9329     if (isa<IntegerLiteral>(RHS))
9330       Ex = LHS;
9331     else if (isa<IntegerLiteral>(LHS))
9332       Ex = RHS;
9333     else
9334       break;
9335   }
9336 
9337   return Ex;
9338 }
9339 
9340 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
9341                                                       ASTContext &Context) {
9342   // Only handle constant-sized or VLAs, but not flexible members.
9343   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
9344     // Only issue the FIXIT for arrays of size > 1.
9345     if (CAT->getSize().getSExtValue() <= 1)
9346       return false;
9347   } else if (!Ty->isVariableArrayType()) {
9348     return false;
9349   }
9350   return true;
9351 }
9352 
9353 // Warn if the user has made the 'size' argument to strlcpy or strlcat
9354 // be the size of the source, instead of the destination.
9355 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
9356                                     IdentifierInfo *FnName) {
9357 
9358   // Don't crash if the user has the wrong number of arguments
9359   unsigned NumArgs = Call->getNumArgs();
9360   if ((NumArgs != 3) && (NumArgs != 4))
9361     return;
9362 
9363   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
9364   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
9365   const Expr *CompareWithSrc = nullptr;
9366 
9367   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
9368                                      Call->getBeginLoc(), Call->getRParenLoc()))
9369     return;
9370 
9371   // Look for 'strlcpy(dst, x, sizeof(x))'
9372   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
9373     CompareWithSrc = Ex;
9374   else {
9375     // Look for 'strlcpy(dst, x, strlen(x))'
9376     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
9377       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
9378           SizeCall->getNumArgs() == 1)
9379         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
9380     }
9381   }
9382 
9383   if (!CompareWithSrc)
9384     return;
9385 
9386   // Determine if the argument to sizeof/strlen is equal to the source
9387   // argument.  In principle there's all kinds of things you could do
9388   // here, for instance creating an == expression and evaluating it with
9389   // EvaluateAsBooleanCondition, but this uses a more direct technique:
9390   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
9391   if (!SrcArgDRE)
9392     return;
9393 
9394   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
9395   if (!CompareWithSrcDRE ||
9396       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
9397     return;
9398 
9399   const Expr *OriginalSizeArg = Call->getArg(2);
9400   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
9401       << OriginalSizeArg->getSourceRange() << FnName;
9402 
9403   // Output a FIXIT hint if the destination is an array (rather than a
9404   // pointer to an array).  This could be enhanced to handle some
9405   // pointers if we know the actual size, like if DstArg is 'array+2'
9406   // we could say 'sizeof(array)-2'.
9407   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
9408   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
9409     return;
9410 
9411   SmallString<128> sizeString;
9412   llvm::raw_svector_ostream OS(sizeString);
9413   OS << "sizeof(";
9414   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9415   OS << ")";
9416 
9417   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
9418       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
9419                                       OS.str());
9420 }
9421 
9422 /// Check if two expressions refer to the same declaration.
9423 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
9424   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
9425     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
9426       return D1->getDecl() == D2->getDecl();
9427   return false;
9428 }
9429 
9430 static const Expr *getStrlenExprArg(const Expr *E) {
9431   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9432     const FunctionDecl *FD = CE->getDirectCallee();
9433     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
9434       return nullptr;
9435     return CE->getArg(0)->IgnoreParenCasts();
9436   }
9437   return nullptr;
9438 }
9439 
9440 // Warn on anti-patterns as the 'size' argument to strncat.
9441 // The correct size argument should look like following:
9442 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
9443 void Sema::CheckStrncatArguments(const CallExpr *CE,
9444                                  IdentifierInfo *FnName) {
9445   // Don't crash if the user has the wrong number of arguments.
9446   if (CE->getNumArgs() < 3)
9447     return;
9448   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
9449   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
9450   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
9451 
9452   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
9453                                      CE->getRParenLoc()))
9454     return;
9455 
9456   // Identify common expressions, which are wrongly used as the size argument
9457   // to strncat and may lead to buffer overflows.
9458   unsigned PatternType = 0;
9459   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
9460     // - sizeof(dst)
9461     if (referToTheSameDecl(SizeOfArg, DstArg))
9462       PatternType = 1;
9463     // - sizeof(src)
9464     else if (referToTheSameDecl(SizeOfArg, SrcArg))
9465       PatternType = 2;
9466   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
9467     if (BE->getOpcode() == BO_Sub) {
9468       const Expr *L = BE->getLHS()->IgnoreParenCasts();
9469       const Expr *R = BE->getRHS()->IgnoreParenCasts();
9470       // - sizeof(dst) - strlen(dst)
9471       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
9472           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
9473         PatternType = 1;
9474       // - sizeof(src) - (anything)
9475       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
9476         PatternType = 2;
9477     }
9478   }
9479 
9480   if (PatternType == 0)
9481     return;
9482 
9483   // Generate the diagnostic.
9484   SourceLocation SL = LenArg->getBeginLoc();
9485   SourceRange SR = LenArg->getSourceRange();
9486   SourceManager &SM = getSourceManager();
9487 
9488   // If the function is defined as a builtin macro, do not show macro expansion.
9489   if (SM.isMacroArgExpansion(SL)) {
9490     SL = SM.getSpellingLoc(SL);
9491     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
9492                      SM.getSpellingLoc(SR.getEnd()));
9493   }
9494 
9495   // Check if the destination is an array (rather than a pointer to an array).
9496   QualType DstTy = DstArg->getType();
9497   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
9498                                                                     Context);
9499   if (!isKnownSizeArray) {
9500     if (PatternType == 1)
9501       Diag(SL, diag::warn_strncat_wrong_size) << SR;
9502     else
9503       Diag(SL, diag::warn_strncat_src_size) << SR;
9504     return;
9505   }
9506 
9507   if (PatternType == 1)
9508     Diag(SL, diag::warn_strncat_large_size) << SR;
9509   else
9510     Diag(SL, diag::warn_strncat_src_size) << SR;
9511 
9512   SmallString<128> sizeString;
9513   llvm::raw_svector_ostream OS(sizeString);
9514   OS << "sizeof(";
9515   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9516   OS << ") - ";
9517   OS << "strlen(";
9518   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9519   OS << ") - 1";
9520 
9521   Diag(SL, diag::note_strncat_wrong_size)
9522     << FixItHint::CreateReplacement(SR, OS.str());
9523 }
9524 
9525 void
9526 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
9527                          SourceLocation ReturnLoc,
9528                          bool isObjCMethod,
9529                          const AttrVec *Attrs,
9530                          const FunctionDecl *FD) {
9531   // Check if the return value is null but should not be.
9532   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
9533        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
9534       CheckNonNullExpr(*this, RetValExp))
9535     Diag(ReturnLoc, diag::warn_null_ret)
9536       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
9537 
9538   // C++11 [basic.stc.dynamic.allocation]p4:
9539   //   If an allocation function declared with a non-throwing
9540   //   exception-specification fails to allocate storage, it shall return
9541   //   a null pointer. Any other allocation function that fails to allocate
9542   //   storage shall indicate failure only by throwing an exception [...]
9543   if (FD) {
9544     OverloadedOperatorKind Op = FD->getOverloadedOperator();
9545     if (Op == OO_New || Op == OO_Array_New) {
9546       const FunctionProtoType *Proto
9547         = FD->getType()->castAs<FunctionProtoType>();
9548       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
9549           CheckNonNullExpr(*this, RetValExp))
9550         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
9551           << FD << getLangOpts().CPlusPlus11;
9552     }
9553   }
9554 }
9555 
9556 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
9557 
9558 /// Check for comparisons of floating point operands using != and ==.
9559 /// Issue a warning if these are no self-comparisons, as they are not likely
9560 /// to do what the programmer intended.
9561 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
9562   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
9563   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
9564 
9565   // Special case: check for x == x (which is OK).
9566   // Do not emit warnings for such cases.
9567   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
9568     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
9569       if (DRL->getDecl() == DRR->getDecl())
9570         return;
9571 
9572   // Special case: check for comparisons against literals that can be exactly
9573   //  represented by APFloat.  In such cases, do not emit a warning.  This
9574   //  is a heuristic: often comparison against such literals are used to
9575   //  detect if a value in a variable has not changed.  This clearly can
9576   //  lead to false negatives.
9577   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
9578     if (FLL->isExact())
9579       return;
9580   } else
9581     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
9582       if (FLR->isExact())
9583         return;
9584 
9585   // Check for comparisons with builtin types.
9586   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
9587     if (CL->getBuiltinCallee())
9588       return;
9589 
9590   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
9591     if (CR->getBuiltinCallee())
9592       return;
9593 
9594   // Emit the diagnostic.
9595   Diag(Loc, diag::warn_floatingpoint_eq)
9596     << LHS->getSourceRange() << RHS->getSourceRange();
9597 }
9598 
9599 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
9600 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
9601 
9602 namespace {
9603 
9604 /// Structure recording the 'active' range of an integer-valued
9605 /// expression.
9606 struct IntRange {
9607   /// The number of bits active in the int.
9608   unsigned Width;
9609 
9610   /// True if the int is known not to have negative values.
9611   bool NonNegative;
9612 
9613   IntRange(unsigned Width, bool NonNegative)
9614       : Width(Width), NonNegative(NonNegative) {}
9615 
9616   /// Returns the range of the bool type.
9617   static IntRange forBoolType() {
9618     return IntRange(1, true);
9619   }
9620 
9621   /// Returns the range of an opaque value of the given integral type.
9622   static IntRange forValueOfType(ASTContext &C, QualType T) {
9623     return forValueOfCanonicalType(C,
9624                           T->getCanonicalTypeInternal().getTypePtr());
9625   }
9626 
9627   /// Returns the range of an opaque value of a canonical integral type.
9628   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
9629     assert(T->isCanonicalUnqualified());
9630 
9631     if (const VectorType *VT = dyn_cast<VectorType>(T))
9632       T = VT->getElementType().getTypePtr();
9633     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9634       T = CT->getElementType().getTypePtr();
9635     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9636       T = AT->getValueType().getTypePtr();
9637 
9638     if (!C.getLangOpts().CPlusPlus) {
9639       // For enum types in C code, use the underlying datatype.
9640       if (const EnumType *ET = dyn_cast<EnumType>(T))
9641         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
9642     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
9643       // For enum types in C++, use the known bit width of the enumerators.
9644       EnumDecl *Enum = ET->getDecl();
9645       // In C++11, enums can have a fixed underlying type. Use this type to
9646       // compute the range.
9647       if (Enum->isFixed()) {
9648         return IntRange(C.getIntWidth(QualType(T, 0)),
9649                         !ET->isSignedIntegerOrEnumerationType());
9650       }
9651 
9652       unsigned NumPositive = Enum->getNumPositiveBits();
9653       unsigned NumNegative = Enum->getNumNegativeBits();
9654 
9655       if (NumNegative == 0)
9656         return IntRange(NumPositive, true/*NonNegative*/);
9657       else
9658         return IntRange(std::max(NumPositive + 1, NumNegative),
9659                         false/*NonNegative*/);
9660     }
9661 
9662     const BuiltinType *BT = cast<BuiltinType>(T);
9663     assert(BT->isInteger());
9664 
9665     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9666   }
9667 
9668   /// Returns the "target" range of a canonical integral type, i.e.
9669   /// the range of values expressible in the type.
9670   ///
9671   /// This matches forValueOfCanonicalType except that enums have the
9672   /// full range of their type, not the range of their enumerators.
9673   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
9674     assert(T->isCanonicalUnqualified());
9675 
9676     if (const VectorType *VT = dyn_cast<VectorType>(T))
9677       T = VT->getElementType().getTypePtr();
9678     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9679       T = CT->getElementType().getTypePtr();
9680     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9681       T = AT->getValueType().getTypePtr();
9682     if (const EnumType *ET = dyn_cast<EnumType>(T))
9683       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
9684 
9685     const BuiltinType *BT = cast<BuiltinType>(T);
9686     assert(BT->isInteger());
9687 
9688     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9689   }
9690 
9691   /// Returns the supremum of two ranges: i.e. their conservative merge.
9692   static IntRange join(IntRange L, IntRange R) {
9693     return IntRange(std::max(L.Width, R.Width),
9694                     L.NonNegative && R.NonNegative);
9695   }
9696 
9697   /// Returns the infinum of two ranges: i.e. their aggressive merge.
9698   static IntRange meet(IntRange L, IntRange R) {
9699     return IntRange(std::min(L.Width, R.Width),
9700                     L.NonNegative || R.NonNegative);
9701   }
9702 };
9703 
9704 } // namespace
9705 
9706 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
9707                               unsigned MaxWidth) {
9708   if (value.isSigned() && value.isNegative())
9709     return IntRange(value.getMinSignedBits(), false);
9710 
9711   if (value.getBitWidth() > MaxWidth)
9712     value = value.trunc(MaxWidth);
9713 
9714   // isNonNegative() just checks the sign bit without considering
9715   // signedness.
9716   return IntRange(value.getActiveBits(), true);
9717 }
9718 
9719 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
9720                               unsigned MaxWidth) {
9721   if (result.isInt())
9722     return GetValueRange(C, result.getInt(), MaxWidth);
9723 
9724   if (result.isVector()) {
9725     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
9726     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
9727       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
9728       R = IntRange::join(R, El);
9729     }
9730     return R;
9731   }
9732 
9733   if (result.isComplexInt()) {
9734     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
9735     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
9736     return IntRange::join(R, I);
9737   }
9738 
9739   // This can happen with lossless casts to intptr_t of "based" lvalues.
9740   // Assume it might use arbitrary bits.
9741   // FIXME: The only reason we need to pass the type in here is to get
9742   // the sign right on this one case.  It would be nice if APValue
9743   // preserved this.
9744   assert(result.isLValue() || result.isAddrLabelDiff());
9745   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
9746 }
9747 
9748 static QualType GetExprType(const Expr *E) {
9749   QualType Ty = E->getType();
9750   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
9751     Ty = AtomicRHS->getValueType();
9752   return Ty;
9753 }
9754 
9755 /// Pseudo-evaluate the given integer expression, estimating the
9756 /// range of values it might take.
9757 ///
9758 /// \param MaxWidth - the width to which the value will be truncated
9759 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
9760                              bool InConstantContext) {
9761   E = E->IgnoreParens();
9762 
9763   // Try a full evaluation first.
9764   Expr::EvalResult result;
9765   if (E->EvaluateAsRValue(result, C, InConstantContext))
9766     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
9767 
9768   // I think we only want to look through implicit casts here; if the
9769   // user has an explicit widening cast, we should treat the value as
9770   // being of the new, wider type.
9771   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
9772     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
9773       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext);
9774 
9775     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
9776 
9777     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
9778                          CE->getCastKind() == CK_BooleanToSignedIntegral;
9779 
9780     // Assume that non-integer casts can span the full range of the type.
9781     if (!isIntegerCast)
9782       return OutputTypeRange;
9783 
9784     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
9785                                      std::min(MaxWidth, OutputTypeRange.Width),
9786                                      InConstantContext);
9787 
9788     // Bail out if the subexpr's range is as wide as the cast type.
9789     if (SubRange.Width >= OutputTypeRange.Width)
9790       return OutputTypeRange;
9791 
9792     // Otherwise, we take the smaller width, and we're non-negative if
9793     // either the output type or the subexpr is.
9794     return IntRange(SubRange.Width,
9795                     SubRange.NonNegative || OutputTypeRange.NonNegative);
9796   }
9797 
9798   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
9799     // If we can fold the condition, just take that operand.
9800     bool CondResult;
9801     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
9802       return GetExprRange(C,
9803                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
9804                           MaxWidth, InConstantContext);
9805 
9806     // Otherwise, conservatively merge.
9807     IntRange L =
9808         GetExprRange(C, CO->getTrueExpr(), MaxWidth, InConstantContext);
9809     IntRange R =
9810         GetExprRange(C, CO->getFalseExpr(), MaxWidth, InConstantContext);
9811     return IntRange::join(L, R);
9812   }
9813 
9814   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
9815     switch (BO->getOpcode()) {
9816     case BO_Cmp:
9817       llvm_unreachable("builtin <=> should have class type");
9818 
9819     // Boolean-valued operations are single-bit and positive.
9820     case BO_LAnd:
9821     case BO_LOr:
9822     case BO_LT:
9823     case BO_GT:
9824     case BO_LE:
9825     case BO_GE:
9826     case BO_EQ:
9827     case BO_NE:
9828       return IntRange::forBoolType();
9829 
9830     // The type of the assignments is the type of the LHS, so the RHS
9831     // is not necessarily the same type.
9832     case BO_MulAssign:
9833     case BO_DivAssign:
9834     case BO_RemAssign:
9835     case BO_AddAssign:
9836     case BO_SubAssign:
9837     case BO_XorAssign:
9838     case BO_OrAssign:
9839       // TODO: bitfields?
9840       return IntRange::forValueOfType(C, GetExprType(E));
9841 
9842     // Simple assignments just pass through the RHS, which will have
9843     // been coerced to the LHS type.
9844     case BO_Assign:
9845       // TODO: bitfields?
9846       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
9847 
9848     // Operations with opaque sources are black-listed.
9849     case BO_PtrMemD:
9850     case BO_PtrMemI:
9851       return IntRange::forValueOfType(C, GetExprType(E));
9852 
9853     // Bitwise-and uses the *infinum* of the two source ranges.
9854     case BO_And:
9855     case BO_AndAssign:
9856       return IntRange::meet(
9857           GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext),
9858           GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext));
9859 
9860     // Left shift gets black-listed based on a judgement call.
9861     case BO_Shl:
9862       // ...except that we want to treat '1 << (blah)' as logically
9863       // positive.  It's an important idiom.
9864       if (IntegerLiteral *I
9865             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
9866         if (I->getValue() == 1) {
9867           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
9868           return IntRange(R.Width, /*NonNegative*/ true);
9869         }
9870       }
9871       LLVM_FALLTHROUGH;
9872 
9873     case BO_ShlAssign:
9874       return IntRange::forValueOfType(C, GetExprType(E));
9875 
9876     // Right shift by a constant can narrow its left argument.
9877     case BO_Shr:
9878     case BO_ShrAssign: {
9879       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
9880 
9881       // If the shift amount is a positive constant, drop the width by
9882       // that much.
9883       llvm::APSInt shift;
9884       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
9885           shift.isNonNegative()) {
9886         unsigned zext = shift.getZExtValue();
9887         if (zext >= L.Width)
9888           L.Width = (L.NonNegative ? 0 : 1);
9889         else
9890           L.Width -= zext;
9891       }
9892 
9893       return L;
9894     }
9895 
9896     // Comma acts as its right operand.
9897     case BO_Comma:
9898       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
9899 
9900     // Black-list pointer subtractions.
9901     case BO_Sub:
9902       if (BO->getLHS()->getType()->isPointerType())
9903         return IntRange::forValueOfType(C, GetExprType(E));
9904       break;
9905 
9906     // The width of a division result is mostly determined by the size
9907     // of the LHS.
9908     case BO_Div: {
9909       // Don't 'pre-truncate' the operands.
9910       unsigned opWidth = C.getIntWidth(GetExprType(E));
9911       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
9912 
9913       // If the divisor is constant, use that.
9914       llvm::APSInt divisor;
9915       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
9916         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
9917         if (log2 >= L.Width)
9918           L.Width = (L.NonNegative ? 0 : 1);
9919         else
9920           L.Width = std::min(L.Width - log2, MaxWidth);
9921         return L;
9922       }
9923 
9924       // Otherwise, just use the LHS's width.
9925       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
9926       return IntRange(L.Width, L.NonNegative && R.NonNegative);
9927     }
9928 
9929     // The result of a remainder can't be larger than the result of
9930     // either side.
9931     case BO_Rem: {
9932       // Don't 'pre-truncate' the operands.
9933       unsigned opWidth = C.getIntWidth(GetExprType(E));
9934       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
9935       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
9936 
9937       IntRange meet = IntRange::meet(L, R);
9938       meet.Width = std::min(meet.Width, MaxWidth);
9939       return meet;
9940     }
9941 
9942     // The default behavior is okay for these.
9943     case BO_Mul:
9944     case BO_Add:
9945     case BO_Xor:
9946     case BO_Or:
9947       break;
9948     }
9949 
9950     // The default case is to treat the operation as if it were closed
9951     // on the narrowest type that encompasses both operands.
9952     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
9953     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
9954     return IntRange::join(L, R);
9955   }
9956 
9957   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
9958     switch (UO->getOpcode()) {
9959     // Boolean-valued operations are white-listed.
9960     case UO_LNot:
9961       return IntRange::forBoolType();
9962 
9963     // Operations with opaque sources are black-listed.
9964     case UO_Deref:
9965     case UO_AddrOf: // should be impossible
9966       return IntRange::forValueOfType(C, GetExprType(E));
9967 
9968     default:
9969       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext);
9970     }
9971   }
9972 
9973   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
9974     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext);
9975 
9976   if (const auto *BitField = E->getSourceBitField())
9977     return IntRange(BitField->getBitWidthValue(C),
9978                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
9979 
9980   return IntRange::forValueOfType(C, GetExprType(E));
9981 }
9982 
9983 static IntRange GetExprRange(ASTContext &C, const Expr *E,
9984                              bool InConstantContext) {
9985   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext);
9986 }
9987 
9988 /// Checks whether the given value, which currently has the given
9989 /// source semantics, has the same value when coerced through the
9990 /// target semantics.
9991 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
9992                                  const llvm::fltSemantics &Src,
9993                                  const llvm::fltSemantics &Tgt) {
9994   llvm::APFloat truncated = value;
9995 
9996   bool ignored;
9997   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
9998   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
9999 
10000   return truncated.bitwiseIsEqual(value);
10001 }
10002 
10003 /// Checks whether the given value, which currently has the given
10004 /// source semantics, has the same value when coerced through the
10005 /// target semantics.
10006 ///
10007 /// The value might be a vector of floats (or a complex number).
10008 static bool IsSameFloatAfterCast(const APValue &value,
10009                                  const llvm::fltSemantics &Src,
10010                                  const llvm::fltSemantics &Tgt) {
10011   if (value.isFloat())
10012     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
10013 
10014   if (value.isVector()) {
10015     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
10016       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
10017         return false;
10018     return true;
10019   }
10020 
10021   assert(value.isComplexFloat());
10022   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
10023           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
10024 }
10025 
10026 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
10027                                        bool IsListInit = false);
10028 
10029 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
10030   // Suppress cases where we are comparing against an enum constant.
10031   if (const DeclRefExpr *DR =
10032       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
10033     if (isa<EnumConstantDecl>(DR->getDecl()))
10034       return true;
10035 
10036   // Suppress cases where the value is expanded from a macro, unless that macro
10037   // is how a language represents a boolean literal. This is the case in both C
10038   // and Objective-C.
10039   SourceLocation BeginLoc = E->getBeginLoc();
10040   if (BeginLoc.isMacroID()) {
10041     StringRef MacroName = Lexer::getImmediateMacroName(
10042         BeginLoc, S.getSourceManager(), S.getLangOpts());
10043     return MacroName != "YES" && MacroName != "NO" &&
10044            MacroName != "true" && MacroName != "false";
10045   }
10046 
10047   return false;
10048 }
10049 
10050 static bool isKnownToHaveUnsignedValue(Expr *E) {
10051   return E->getType()->isIntegerType() &&
10052          (!E->getType()->isSignedIntegerType() ||
10053           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
10054 }
10055 
10056 namespace {
10057 /// The promoted range of values of a type. In general this has the
10058 /// following structure:
10059 ///
10060 ///     |-----------| . . . |-----------|
10061 ///     ^           ^       ^           ^
10062 ///    Min       HoleMin  HoleMax      Max
10063 ///
10064 /// ... where there is only a hole if a signed type is promoted to unsigned
10065 /// (in which case Min and Max are the smallest and largest representable
10066 /// values).
10067 struct PromotedRange {
10068   // Min, or HoleMax if there is a hole.
10069   llvm::APSInt PromotedMin;
10070   // Max, or HoleMin if there is a hole.
10071   llvm::APSInt PromotedMax;
10072 
10073   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
10074     if (R.Width == 0)
10075       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
10076     else if (R.Width >= BitWidth && !Unsigned) {
10077       // Promotion made the type *narrower*. This happens when promoting
10078       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
10079       // Treat all values of 'signed int' as being in range for now.
10080       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
10081       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
10082     } else {
10083       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
10084                         .extOrTrunc(BitWidth);
10085       PromotedMin.setIsUnsigned(Unsigned);
10086 
10087       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
10088                         .extOrTrunc(BitWidth);
10089       PromotedMax.setIsUnsigned(Unsigned);
10090     }
10091   }
10092 
10093   // Determine whether this range is contiguous (has no hole).
10094   bool isContiguous() const { return PromotedMin <= PromotedMax; }
10095 
10096   // Where a constant value is within the range.
10097   enum ComparisonResult {
10098     LT = 0x1,
10099     LE = 0x2,
10100     GT = 0x4,
10101     GE = 0x8,
10102     EQ = 0x10,
10103     NE = 0x20,
10104     InRangeFlag = 0x40,
10105 
10106     Less = LE | LT | NE,
10107     Min = LE | InRangeFlag,
10108     InRange = InRangeFlag,
10109     Max = GE | InRangeFlag,
10110     Greater = GE | GT | NE,
10111 
10112     OnlyValue = LE | GE | EQ | InRangeFlag,
10113     InHole = NE
10114   };
10115 
10116   ComparisonResult compare(const llvm::APSInt &Value) const {
10117     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
10118            Value.isUnsigned() == PromotedMin.isUnsigned());
10119     if (!isContiguous()) {
10120       assert(Value.isUnsigned() && "discontiguous range for signed compare");
10121       if (Value.isMinValue()) return Min;
10122       if (Value.isMaxValue()) return Max;
10123       if (Value >= PromotedMin) return InRange;
10124       if (Value <= PromotedMax) return InRange;
10125       return InHole;
10126     }
10127 
10128     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
10129     case -1: return Less;
10130     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
10131     case 1:
10132       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
10133       case -1: return InRange;
10134       case 0: return Max;
10135       case 1: return Greater;
10136       }
10137     }
10138 
10139     llvm_unreachable("impossible compare result");
10140   }
10141 
10142   static llvm::Optional<StringRef>
10143   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
10144     if (Op == BO_Cmp) {
10145       ComparisonResult LTFlag = LT, GTFlag = GT;
10146       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
10147 
10148       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
10149       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
10150       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
10151       return llvm::None;
10152     }
10153 
10154     ComparisonResult TrueFlag, FalseFlag;
10155     if (Op == BO_EQ) {
10156       TrueFlag = EQ;
10157       FalseFlag = NE;
10158     } else if (Op == BO_NE) {
10159       TrueFlag = NE;
10160       FalseFlag = EQ;
10161     } else {
10162       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
10163         TrueFlag = LT;
10164         FalseFlag = GE;
10165       } else {
10166         TrueFlag = GT;
10167         FalseFlag = LE;
10168       }
10169       if (Op == BO_GE || Op == BO_LE)
10170         std::swap(TrueFlag, FalseFlag);
10171     }
10172     if (R & TrueFlag)
10173       return StringRef("true");
10174     if (R & FalseFlag)
10175       return StringRef("false");
10176     return llvm::None;
10177   }
10178 };
10179 }
10180 
10181 static bool HasEnumType(Expr *E) {
10182   // Strip off implicit integral promotions.
10183   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
10184     if (ICE->getCastKind() != CK_IntegralCast &&
10185         ICE->getCastKind() != CK_NoOp)
10186       break;
10187     E = ICE->getSubExpr();
10188   }
10189 
10190   return E->getType()->isEnumeralType();
10191 }
10192 
10193 static int classifyConstantValue(Expr *Constant) {
10194   // The values of this enumeration are used in the diagnostics
10195   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
10196   enum ConstantValueKind {
10197     Miscellaneous = 0,
10198     LiteralTrue,
10199     LiteralFalse
10200   };
10201   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
10202     return BL->getValue() ? ConstantValueKind::LiteralTrue
10203                           : ConstantValueKind::LiteralFalse;
10204   return ConstantValueKind::Miscellaneous;
10205 }
10206 
10207 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
10208                                         Expr *Constant, Expr *Other,
10209                                         const llvm::APSInt &Value,
10210                                         bool RhsConstant) {
10211   if (S.inTemplateInstantiation())
10212     return false;
10213 
10214   Expr *OriginalOther = Other;
10215 
10216   Constant = Constant->IgnoreParenImpCasts();
10217   Other = Other->IgnoreParenImpCasts();
10218 
10219   // Suppress warnings on tautological comparisons between values of the same
10220   // enumeration type. There are only two ways we could warn on this:
10221   //  - If the constant is outside the range of representable values of
10222   //    the enumeration. In such a case, we should warn about the cast
10223   //    to enumeration type, not about the comparison.
10224   //  - If the constant is the maximum / minimum in-range value. For an
10225   //    enumeratin type, such comparisons can be meaningful and useful.
10226   if (Constant->getType()->isEnumeralType() &&
10227       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
10228     return false;
10229 
10230   // TODO: Investigate using GetExprRange() to get tighter bounds
10231   // on the bit ranges.
10232   QualType OtherT = Other->getType();
10233   if (const auto *AT = OtherT->getAs<AtomicType>())
10234     OtherT = AT->getValueType();
10235   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
10236 
10237   // Special case for ObjC BOOL on targets where its a typedef for a signed char
10238   // (Namely, macOS).
10239   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
10240                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
10241                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
10242 
10243   // Whether we're treating Other as being a bool because of the form of
10244   // expression despite it having another type (typically 'int' in C).
10245   bool OtherIsBooleanDespiteType =
10246       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
10247   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
10248     OtherRange = IntRange::forBoolType();
10249 
10250   // Determine the promoted range of the other type and see if a comparison of
10251   // the constant against that range is tautological.
10252   PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
10253                                    Value.isUnsigned());
10254   auto Cmp = OtherPromotedRange.compare(Value);
10255   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
10256   if (!Result)
10257     return false;
10258 
10259   // Suppress the diagnostic for an in-range comparison if the constant comes
10260   // from a macro or enumerator. We don't want to diagnose
10261   //
10262   //   some_long_value <= INT_MAX
10263   //
10264   // when sizeof(int) == sizeof(long).
10265   bool InRange = Cmp & PromotedRange::InRangeFlag;
10266   if (InRange && IsEnumConstOrFromMacro(S, Constant))
10267     return false;
10268 
10269   // If this is a comparison to an enum constant, include that
10270   // constant in the diagnostic.
10271   const EnumConstantDecl *ED = nullptr;
10272   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
10273     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
10274 
10275   // Should be enough for uint128 (39 decimal digits)
10276   SmallString<64> PrettySourceValue;
10277   llvm::raw_svector_ostream OS(PrettySourceValue);
10278   if (ED) {
10279     OS << '\'' << *ED << "' (" << Value << ")";
10280   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
10281                Constant->IgnoreParenImpCasts())) {
10282     OS << (BL->getValue() ? "YES" : "NO");
10283   } else {
10284     OS << Value;
10285   }
10286 
10287   if (IsObjCSignedCharBool) {
10288     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10289                           S.PDiag(diag::warn_tautological_compare_objc_bool)
10290                               << OS.str() << *Result);
10291     return true;
10292   }
10293 
10294   // FIXME: We use a somewhat different formatting for the in-range cases and
10295   // cases involving boolean values for historical reasons. We should pick a
10296   // consistent way of presenting these diagnostics.
10297   if (!InRange || Other->isKnownToHaveBooleanValue()) {
10298 
10299     S.DiagRuntimeBehavior(
10300         E->getOperatorLoc(), E,
10301         S.PDiag(!InRange ? diag::warn_out_of_range_compare
10302                          : diag::warn_tautological_bool_compare)
10303             << OS.str() << classifyConstantValue(Constant) << OtherT
10304             << OtherIsBooleanDespiteType << *Result
10305             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
10306   } else {
10307     unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
10308                         ? (HasEnumType(OriginalOther)
10309                                ? diag::warn_unsigned_enum_always_true_comparison
10310                                : diag::warn_unsigned_always_true_comparison)
10311                         : diag::warn_tautological_constant_compare;
10312 
10313     S.Diag(E->getOperatorLoc(), Diag)
10314         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
10315         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
10316   }
10317 
10318   return true;
10319 }
10320 
10321 /// Analyze the operands of the given comparison.  Implements the
10322 /// fallback case from AnalyzeComparison.
10323 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
10324   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10325   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10326 }
10327 
10328 /// Implements -Wsign-compare.
10329 ///
10330 /// \param E the binary operator to check for warnings
10331 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
10332   // The type the comparison is being performed in.
10333   QualType T = E->getLHS()->getType();
10334 
10335   // Only analyze comparison operators where both sides have been converted to
10336   // the same type.
10337   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
10338     return AnalyzeImpConvsInComparison(S, E);
10339 
10340   // Don't analyze value-dependent comparisons directly.
10341   if (E->isValueDependent())
10342     return AnalyzeImpConvsInComparison(S, E);
10343 
10344   Expr *LHS = E->getLHS();
10345   Expr *RHS = E->getRHS();
10346 
10347   if (T->isIntegralType(S.Context)) {
10348     llvm::APSInt RHSValue;
10349     llvm::APSInt LHSValue;
10350 
10351     bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
10352     bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
10353 
10354     // We don't care about expressions whose result is a constant.
10355     if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
10356       return AnalyzeImpConvsInComparison(S, E);
10357 
10358     // We only care about expressions where just one side is literal
10359     if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
10360       // Is the constant on the RHS or LHS?
10361       const bool RhsConstant = IsRHSIntegralLiteral;
10362       Expr *Const = RhsConstant ? RHS : LHS;
10363       Expr *Other = RhsConstant ? LHS : RHS;
10364       const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
10365 
10366       // Check whether an integer constant comparison results in a value
10367       // of 'true' or 'false'.
10368       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
10369         return AnalyzeImpConvsInComparison(S, E);
10370     }
10371   }
10372 
10373   if (!T->hasUnsignedIntegerRepresentation()) {
10374     // We don't do anything special if this isn't an unsigned integral
10375     // comparison:  we're only interested in integral comparisons, and
10376     // signed comparisons only happen in cases we don't care to warn about.
10377     return AnalyzeImpConvsInComparison(S, E);
10378   }
10379 
10380   LHS = LHS->IgnoreParenImpCasts();
10381   RHS = RHS->IgnoreParenImpCasts();
10382 
10383   if (!S.getLangOpts().CPlusPlus) {
10384     // Avoid warning about comparison of integers with different signs when
10385     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
10386     // the type of `E`.
10387     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
10388       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10389     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
10390       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10391   }
10392 
10393   // Check to see if one of the (unmodified) operands is of different
10394   // signedness.
10395   Expr *signedOperand, *unsignedOperand;
10396   if (LHS->getType()->hasSignedIntegerRepresentation()) {
10397     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
10398            "unsigned comparison between two signed integer expressions?");
10399     signedOperand = LHS;
10400     unsignedOperand = RHS;
10401   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
10402     signedOperand = RHS;
10403     unsignedOperand = LHS;
10404   } else {
10405     return AnalyzeImpConvsInComparison(S, E);
10406   }
10407 
10408   // Otherwise, calculate the effective range of the signed operand.
10409   IntRange signedRange =
10410       GetExprRange(S.Context, signedOperand, S.isConstantEvaluated());
10411 
10412   // Go ahead and analyze implicit conversions in the operands.  Note
10413   // that we skip the implicit conversions on both sides.
10414   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
10415   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
10416 
10417   // If the signed range is non-negative, -Wsign-compare won't fire.
10418   if (signedRange.NonNegative)
10419     return;
10420 
10421   // For (in)equality comparisons, if the unsigned operand is a
10422   // constant which cannot collide with a overflowed signed operand,
10423   // then reinterpreting the signed operand as unsigned will not
10424   // change the result of the comparison.
10425   if (E->isEqualityOp()) {
10426     unsigned comparisonWidth = S.Context.getIntWidth(T);
10427     IntRange unsignedRange =
10428         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated());
10429 
10430     // We should never be unable to prove that the unsigned operand is
10431     // non-negative.
10432     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
10433 
10434     if (unsignedRange.Width < comparisonWidth)
10435       return;
10436   }
10437 
10438   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10439                         S.PDiag(diag::warn_mixed_sign_comparison)
10440                             << LHS->getType() << RHS->getType()
10441                             << LHS->getSourceRange() << RHS->getSourceRange());
10442 }
10443 
10444 /// Analyzes an attempt to assign the given value to a bitfield.
10445 ///
10446 /// Returns true if there was something fishy about the attempt.
10447 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
10448                                       SourceLocation InitLoc) {
10449   assert(Bitfield->isBitField());
10450   if (Bitfield->isInvalidDecl())
10451     return false;
10452 
10453   // White-list bool bitfields.
10454   QualType BitfieldType = Bitfield->getType();
10455   if (BitfieldType->isBooleanType())
10456      return false;
10457 
10458   if (BitfieldType->isEnumeralType()) {
10459     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
10460     // If the underlying enum type was not explicitly specified as an unsigned
10461     // type and the enum contain only positive values, MSVC++ will cause an
10462     // inconsistency by storing this as a signed type.
10463     if (S.getLangOpts().CPlusPlus11 &&
10464         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
10465         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
10466         BitfieldEnumDecl->getNumNegativeBits() == 0) {
10467       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
10468         << BitfieldEnumDecl->getNameAsString();
10469     }
10470   }
10471 
10472   if (Bitfield->getType()->isBooleanType())
10473     return false;
10474 
10475   // Ignore value- or type-dependent expressions.
10476   if (Bitfield->getBitWidth()->isValueDependent() ||
10477       Bitfield->getBitWidth()->isTypeDependent() ||
10478       Init->isValueDependent() ||
10479       Init->isTypeDependent())
10480     return false;
10481 
10482   Expr *OriginalInit = Init->IgnoreParenImpCasts();
10483   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
10484 
10485   Expr::EvalResult Result;
10486   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
10487                                    Expr::SE_AllowSideEffects)) {
10488     // The RHS is not constant.  If the RHS has an enum type, make sure the
10489     // bitfield is wide enough to hold all the values of the enum without
10490     // truncation.
10491     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
10492       EnumDecl *ED = EnumTy->getDecl();
10493       bool SignedBitfield = BitfieldType->isSignedIntegerType();
10494 
10495       // Enum types are implicitly signed on Windows, so check if there are any
10496       // negative enumerators to see if the enum was intended to be signed or
10497       // not.
10498       bool SignedEnum = ED->getNumNegativeBits() > 0;
10499 
10500       // Check for surprising sign changes when assigning enum values to a
10501       // bitfield of different signedness.  If the bitfield is signed and we
10502       // have exactly the right number of bits to store this unsigned enum,
10503       // suggest changing the enum to an unsigned type. This typically happens
10504       // on Windows where unfixed enums always use an underlying type of 'int'.
10505       unsigned DiagID = 0;
10506       if (SignedEnum && !SignedBitfield) {
10507         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
10508       } else if (SignedBitfield && !SignedEnum &&
10509                  ED->getNumPositiveBits() == FieldWidth) {
10510         DiagID = diag::warn_signed_bitfield_enum_conversion;
10511       }
10512 
10513       if (DiagID) {
10514         S.Diag(InitLoc, DiagID) << Bitfield << ED;
10515         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
10516         SourceRange TypeRange =
10517             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
10518         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
10519             << SignedEnum << TypeRange;
10520       }
10521 
10522       // Compute the required bitwidth. If the enum has negative values, we need
10523       // one more bit than the normal number of positive bits to represent the
10524       // sign bit.
10525       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
10526                                                   ED->getNumNegativeBits())
10527                                        : ED->getNumPositiveBits();
10528 
10529       // Check the bitwidth.
10530       if (BitsNeeded > FieldWidth) {
10531         Expr *WidthExpr = Bitfield->getBitWidth();
10532         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
10533             << Bitfield << ED;
10534         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
10535             << BitsNeeded << ED << WidthExpr->getSourceRange();
10536       }
10537     }
10538 
10539     return false;
10540   }
10541 
10542   llvm::APSInt Value = Result.Val.getInt();
10543 
10544   unsigned OriginalWidth = Value.getBitWidth();
10545 
10546   if (!Value.isSigned() || Value.isNegative())
10547     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
10548       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
10549         OriginalWidth = Value.getMinSignedBits();
10550 
10551   if (OriginalWidth <= FieldWidth)
10552     return false;
10553 
10554   // Compute the value which the bitfield will contain.
10555   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
10556   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
10557 
10558   // Check whether the stored value is equal to the original value.
10559   TruncatedValue = TruncatedValue.extend(OriginalWidth);
10560   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
10561     return false;
10562 
10563   // Special-case bitfields of width 1: booleans are naturally 0/1, and
10564   // therefore don't strictly fit into a signed bitfield of width 1.
10565   if (FieldWidth == 1 && Value == 1)
10566     return false;
10567 
10568   std::string PrettyValue = Value.toString(10);
10569   std::string PrettyTrunc = TruncatedValue.toString(10);
10570 
10571   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
10572     << PrettyValue << PrettyTrunc << OriginalInit->getType()
10573     << Init->getSourceRange();
10574 
10575   return true;
10576 }
10577 
10578 /// Analyze the given simple or compound assignment for warning-worthy
10579 /// operations.
10580 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
10581   // Just recurse on the LHS.
10582   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10583 
10584   // We want to recurse on the RHS as normal unless we're assigning to
10585   // a bitfield.
10586   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
10587     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
10588                                   E->getOperatorLoc())) {
10589       // Recurse, ignoring any implicit conversions on the RHS.
10590       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
10591                                         E->getOperatorLoc());
10592     }
10593   }
10594 
10595   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10596 
10597   // Diagnose implicitly sequentially-consistent atomic assignment.
10598   if (E->getLHS()->getType()->isAtomicType())
10599     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
10600 }
10601 
10602 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
10603 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
10604                             SourceLocation CContext, unsigned diag,
10605                             bool pruneControlFlow = false) {
10606   if (pruneControlFlow) {
10607     S.DiagRuntimeBehavior(E->getExprLoc(), E,
10608                           S.PDiag(diag)
10609                               << SourceType << T << E->getSourceRange()
10610                               << SourceRange(CContext));
10611     return;
10612   }
10613   S.Diag(E->getExprLoc(), diag)
10614     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
10615 }
10616 
10617 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
10618 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
10619                             SourceLocation CContext,
10620                             unsigned diag, bool pruneControlFlow = false) {
10621   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
10622 }
10623 
10624 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
10625   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
10626       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
10627 }
10628 
10629 static void adornObjCBoolConversionDiagWithTernaryFixit(
10630     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
10631   Expr *Ignored = SourceExpr->IgnoreImplicit();
10632   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
10633     Ignored = OVE->getSourceExpr();
10634   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
10635                      isa<BinaryOperator>(Ignored) ||
10636                      isa<CXXOperatorCallExpr>(Ignored);
10637   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
10638   if (NeedsParens)
10639     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
10640             << FixItHint::CreateInsertion(EndLoc, ")");
10641   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
10642 }
10643 
10644 /// Diagnose an implicit cast from a floating point value to an integer value.
10645 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
10646                                     SourceLocation CContext) {
10647   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
10648   const bool PruneWarnings = S.inTemplateInstantiation();
10649 
10650   Expr *InnerE = E->IgnoreParenImpCasts();
10651   // We also want to warn on, e.g., "int i = -1.234"
10652   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
10653     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
10654       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
10655 
10656   const bool IsLiteral =
10657       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
10658 
10659   llvm::APFloat Value(0.0);
10660   bool IsConstant =
10661     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
10662   if (!IsConstant) {
10663     if (isObjCSignedCharBool(S, T)) {
10664       return adornObjCBoolConversionDiagWithTernaryFixit(
10665           S, E,
10666           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
10667               << E->getType());
10668     }
10669 
10670     return DiagnoseImpCast(S, E, T, CContext,
10671                            diag::warn_impcast_float_integer, PruneWarnings);
10672   }
10673 
10674   bool isExact = false;
10675 
10676   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
10677                             T->hasUnsignedIntegerRepresentation());
10678   llvm::APFloat::opStatus Result = Value.convertToInteger(
10679       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
10680 
10681   // FIXME: Force the precision of the source value down so we don't print
10682   // digits which are usually useless (we don't really care here if we
10683   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
10684   // would automatically print the shortest representation, but it's a bit
10685   // tricky to implement.
10686   SmallString<16> PrettySourceValue;
10687   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
10688   precision = (precision * 59 + 195) / 196;
10689   Value.toString(PrettySourceValue, precision);
10690 
10691   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
10692     return adornObjCBoolConversionDiagWithTernaryFixit(
10693         S, E,
10694         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
10695             << PrettySourceValue);
10696   }
10697 
10698   if (Result == llvm::APFloat::opOK && isExact) {
10699     if (IsLiteral) return;
10700     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
10701                            PruneWarnings);
10702   }
10703 
10704   // Conversion of a floating-point value to a non-bool integer where the
10705   // integral part cannot be represented by the integer type is undefined.
10706   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
10707     return DiagnoseImpCast(
10708         S, E, T, CContext,
10709         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
10710                   : diag::warn_impcast_float_to_integer_out_of_range,
10711         PruneWarnings);
10712 
10713   unsigned DiagID = 0;
10714   if (IsLiteral) {
10715     // Warn on floating point literal to integer.
10716     DiagID = diag::warn_impcast_literal_float_to_integer;
10717   } else if (IntegerValue == 0) {
10718     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
10719       return DiagnoseImpCast(S, E, T, CContext,
10720                              diag::warn_impcast_float_integer, PruneWarnings);
10721     }
10722     // Warn on non-zero to zero conversion.
10723     DiagID = diag::warn_impcast_float_to_integer_zero;
10724   } else {
10725     if (IntegerValue.isUnsigned()) {
10726       if (!IntegerValue.isMaxValue()) {
10727         return DiagnoseImpCast(S, E, T, CContext,
10728                                diag::warn_impcast_float_integer, PruneWarnings);
10729       }
10730     } else {  // IntegerValue.isSigned()
10731       if (!IntegerValue.isMaxSignedValue() &&
10732           !IntegerValue.isMinSignedValue()) {
10733         return DiagnoseImpCast(S, E, T, CContext,
10734                                diag::warn_impcast_float_integer, PruneWarnings);
10735       }
10736     }
10737     // Warn on evaluatable floating point expression to integer conversion.
10738     DiagID = diag::warn_impcast_float_to_integer;
10739   }
10740 
10741   SmallString<16> PrettyTargetValue;
10742   if (IsBool)
10743     PrettyTargetValue = Value.isZero() ? "false" : "true";
10744   else
10745     IntegerValue.toString(PrettyTargetValue);
10746 
10747   if (PruneWarnings) {
10748     S.DiagRuntimeBehavior(E->getExprLoc(), E,
10749                           S.PDiag(DiagID)
10750                               << E->getType() << T.getUnqualifiedType()
10751                               << PrettySourceValue << PrettyTargetValue
10752                               << E->getSourceRange() << SourceRange(CContext));
10753   } else {
10754     S.Diag(E->getExprLoc(), DiagID)
10755         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
10756         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
10757   }
10758 }
10759 
10760 /// Analyze the given compound assignment for the possible losing of
10761 /// floating-point precision.
10762 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
10763   assert(isa<CompoundAssignOperator>(E) &&
10764          "Must be compound assignment operation");
10765   // Recurse on the LHS and RHS in here
10766   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10767   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10768 
10769   if (E->getLHS()->getType()->isAtomicType())
10770     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
10771 
10772   // Now check the outermost expression
10773   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
10774   const auto *RBT = cast<CompoundAssignOperator>(E)
10775                         ->getComputationResultType()
10776                         ->getAs<BuiltinType>();
10777 
10778   // The below checks assume source is floating point.
10779   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
10780 
10781   // If source is floating point but target is an integer.
10782   if (ResultBT->isInteger())
10783     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
10784                            E->getExprLoc(), diag::warn_impcast_float_integer);
10785 
10786   if (!ResultBT->isFloatingPoint())
10787     return;
10788 
10789   // If both source and target are floating points, warn about losing precision.
10790   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
10791       QualType(ResultBT, 0), QualType(RBT, 0));
10792   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
10793     // warn about dropping FP rank.
10794     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
10795                     diag::warn_impcast_float_result_precision);
10796 }
10797 
10798 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
10799                                       IntRange Range) {
10800   if (!Range.Width) return "0";
10801 
10802   llvm::APSInt ValueInRange = Value;
10803   ValueInRange.setIsSigned(!Range.NonNegative);
10804   ValueInRange = ValueInRange.trunc(Range.Width);
10805   return ValueInRange.toString(10);
10806 }
10807 
10808 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
10809   if (!isa<ImplicitCastExpr>(Ex))
10810     return false;
10811 
10812   Expr *InnerE = Ex->IgnoreParenImpCasts();
10813   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
10814   const Type *Source =
10815     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
10816   if (Target->isDependentType())
10817     return false;
10818 
10819   const BuiltinType *FloatCandidateBT =
10820     dyn_cast<BuiltinType>(ToBool ? Source : Target);
10821   const Type *BoolCandidateType = ToBool ? Target : Source;
10822 
10823   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
10824           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
10825 }
10826 
10827 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
10828                                              SourceLocation CC) {
10829   unsigned NumArgs = TheCall->getNumArgs();
10830   for (unsigned i = 0; i < NumArgs; ++i) {
10831     Expr *CurrA = TheCall->getArg(i);
10832     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
10833       continue;
10834 
10835     bool IsSwapped = ((i > 0) &&
10836         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
10837     IsSwapped |= ((i < (NumArgs - 1)) &&
10838         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
10839     if (IsSwapped) {
10840       // Warn on this floating-point to bool conversion.
10841       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
10842                       CurrA->getType(), CC,
10843                       diag::warn_impcast_floating_point_to_bool);
10844     }
10845   }
10846 }
10847 
10848 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
10849                                    SourceLocation CC) {
10850   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
10851                         E->getExprLoc()))
10852     return;
10853 
10854   // Don't warn on functions which have return type nullptr_t.
10855   if (isa<CallExpr>(E))
10856     return;
10857 
10858   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
10859   const Expr::NullPointerConstantKind NullKind =
10860       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
10861   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
10862     return;
10863 
10864   // Return if target type is a safe conversion.
10865   if (T->isAnyPointerType() || T->isBlockPointerType() ||
10866       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
10867     return;
10868 
10869   SourceLocation Loc = E->getSourceRange().getBegin();
10870 
10871   // Venture through the macro stacks to get to the source of macro arguments.
10872   // The new location is a better location than the complete location that was
10873   // passed in.
10874   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
10875   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
10876 
10877   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
10878   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
10879     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
10880         Loc, S.SourceMgr, S.getLangOpts());
10881     if (MacroName == "NULL")
10882       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
10883   }
10884 
10885   // Only warn if the null and context location are in the same macro expansion.
10886   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
10887     return;
10888 
10889   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
10890       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
10891       << FixItHint::CreateReplacement(Loc,
10892                                       S.getFixItZeroLiteralForType(T, Loc));
10893 }
10894 
10895 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
10896                                   ObjCArrayLiteral *ArrayLiteral);
10897 
10898 static void
10899 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
10900                            ObjCDictionaryLiteral *DictionaryLiteral);
10901 
10902 /// Check a single element within a collection literal against the
10903 /// target element type.
10904 static void checkObjCCollectionLiteralElement(Sema &S,
10905                                               QualType TargetElementType,
10906                                               Expr *Element,
10907                                               unsigned ElementKind) {
10908   // Skip a bitcast to 'id' or qualified 'id'.
10909   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
10910     if (ICE->getCastKind() == CK_BitCast &&
10911         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
10912       Element = ICE->getSubExpr();
10913   }
10914 
10915   QualType ElementType = Element->getType();
10916   ExprResult ElementResult(Element);
10917   if (ElementType->getAs<ObjCObjectPointerType>() &&
10918       S.CheckSingleAssignmentConstraints(TargetElementType,
10919                                          ElementResult,
10920                                          false, false)
10921         != Sema::Compatible) {
10922     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
10923         << ElementType << ElementKind << TargetElementType
10924         << Element->getSourceRange();
10925   }
10926 
10927   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
10928     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
10929   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
10930     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
10931 }
10932 
10933 /// Check an Objective-C array literal being converted to the given
10934 /// target type.
10935 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
10936                                   ObjCArrayLiteral *ArrayLiteral) {
10937   if (!S.NSArrayDecl)
10938     return;
10939 
10940   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
10941   if (!TargetObjCPtr)
10942     return;
10943 
10944   if (TargetObjCPtr->isUnspecialized() ||
10945       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
10946         != S.NSArrayDecl->getCanonicalDecl())
10947     return;
10948 
10949   auto TypeArgs = TargetObjCPtr->getTypeArgs();
10950   if (TypeArgs.size() != 1)
10951     return;
10952 
10953   QualType TargetElementType = TypeArgs[0];
10954   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
10955     checkObjCCollectionLiteralElement(S, TargetElementType,
10956                                       ArrayLiteral->getElement(I),
10957                                       0);
10958   }
10959 }
10960 
10961 /// Check an Objective-C dictionary literal being converted to the given
10962 /// target type.
10963 static void
10964 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
10965                            ObjCDictionaryLiteral *DictionaryLiteral) {
10966   if (!S.NSDictionaryDecl)
10967     return;
10968 
10969   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
10970   if (!TargetObjCPtr)
10971     return;
10972 
10973   if (TargetObjCPtr->isUnspecialized() ||
10974       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
10975         != S.NSDictionaryDecl->getCanonicalDecl())
10976     return;
10977 
10978   auto TypeArgs = TargetObjCPtr->getTypeArgs();
10979   if (TypeArgs.size() != 2)
10980     return;
10981 
10982   QualType TargetKeyType = TypeArgs[0];
10983   QualType TargetObjectType = TypeArgs[1];
10984   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
10985     auto Element = DictionaryLiteral->getKeyValueElement(I);
10986     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
10987     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
10988   }
10989 }
10990 
10991 // Helper function to filter out cases for constant width constant conversion.
10992 // Don't warn on char array initialization or for non-decimal values.
10993 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
10994                                           SourceLocation CC) {
10995   // If initializing from a constant, and the constant starts with '0',
10996   // then it is a binary, octal, or hexadecimal.  Allow these constants
10997   // to fill all the bits, even if there is a sign change.
10998   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
10999     const char FirstLiteralCharacter =
11000         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
11001     if (FirstLiteralCharacter == '0')
11002       return false;
11003   }
11004 
11005   // If the CC location points to a '{', and the type is char, then assume
11006   // assume it is an array initialization.
11007   if (CC.isValid() && T->isCharType()) {
11008     const char FirstContextCharacter =
11009         S.getSourceManager().getCharacterData(CC)[0];
11010     if (FirstContextCharacter == '{')
11011       return false;
11012   }
11013 
11014   return true;
11015 }
11016 
11017 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
11018   const auto *IL = dyn_cast<IntegerLiteral>(E);
11019   if (!IL) {
11020     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
11021       if (UO->getOpcode() == UO_Minus)
11022         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
11023     }
11024   }
11025 
11026   return IL;
11027 }
11028 
11029 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
11030   E = E->IgnoreParenImpCasts();
11031   SourceLocation ExprLoc = E->getExprLoc();
11032 
11033   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11034     BinaryOperator::Opcode Opc = BO->getOpcode();
11035     Expr::EvalResult Result;
11036     // Do not diagnose unsigned shifts.
11037     if (Opc == BO_Shl) {
11038       const auto *LHS = getIntegerLiteral(BO->getLHS());
11039       const auto *RHS = getIntegerLiteral(BO->getRHS());
11040       if (LHS && LHS->getValue() == 0)
11041         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
11042       else if (!E->isValueDependent() && LHS && RHS &&
11043                RHS->getValue().isNonNegative() &&
11044                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
11045         S.Diag(ExprLoc, diag::warn_left_shift_always)
11046             << (Result.Val.getInt() != 0);
11047       else if (E->getType()->isSignedIntegerType())
11048         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
11049     }
11050   }
11051 
11052   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11053     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
11054     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
11055     if (!LHS || !RHS)
11056       return;
11057     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
11058         (RHS->getValue() == 0 || RHS->getValue() == 1))
11059       // Do not diagnose common idioms.
11060       return;
11061     if (LHS->getValue() != 0 && RHS->getValue() != 0)
11062       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
11063   }
11064 }
11065 
11066 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
11067                                     SourceLocation CC,
11068                                     bool *ICContext = nullptr,
11069                                     bool IsListInit = false) {
11070   if (E->isTypeDependent() || E->isValueDependent()) return;
11071 
11072   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
11073   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
11074   if (Source == Target) return;
11075   if (Target->isDependentType()) return;
11076 
11077   // If the conversion context location is invalid don't complain. We also
11078   // don't want to emit a warning if the issue occurs from the expansion of
11079   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
11080   // delay this check as long as possible. Once we detect we are in that
11081   // scenario, we just return.
11082   if (CC.isInvalid())
11083     return;
11084 
11085   if (Source->isAtomicType())
11086     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
11087 
11088   // Diagnose implicit casts to bool.
11089   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
11090     if (isa<StringLiteral>(E))
11091       // Warn on string literal to bool.  Checks for string literals in logical
11092       // and expressions, for instance, assert(0 && "error here"), are
11093       // prevented by a check in AnalyzeImplicitConversions().
11094       return DiagnoseImpCast(S, E, T, CC,
11095                              diag::warn_impcast_string_literal_to_bool);
11096     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
11097         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
11098       // This covers the literal expressions that evaluate to Objective-C
11099       // objects.
11100       return DiagnoseImpCast(S, E, T, CC,
11101                              diag::warn_impcast_objective_c_literal_to_bool);
11102     }
11103     if (Source->isPointerType() || Source->canDecayToPointerType()) {
11104       // Warn on pointer to bool conversion that is always true.
11105       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
11106                                      SourceRange(CC));
11107     }
11108   }
11109 
11110   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
11111   // is a typedef for signed char (macOS), then that constant value has to be 1
11112   // or 0.
11113   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
11114     Expr::EvalResult Result;
11115     if (E->EvaluateAsInt(Result, S.getASTContext(),
11116                          Expr::SE_AllowSideEffects)) {
11117       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
11118         adornObjCBoolConversionDiagWithTernaryFixit(
11119             S, E,
11120             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
11121                 << Result.Val.getInt().toString(10));
11122       }
11123       return;
11124     }
11125   }
11126 
11127   // Check implicit casts from Objective-C collection literals to specialized
11128   // collection types, e.g., NSArray<NSString *> *.
11129   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
11130     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
11131   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
11132     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
11133 
11134   // Strip vector types.
11135   if (isa<VectorType>(Source)) {
11136     if (!isa<VectorType>(Target)) {
11137       if (S.SourceMgr.isInSystemMacro(CC))
11138         return;
11139       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
11140     }
11141 
11142     // If the vector cast is cast between two vectors of the same size, it is
11143     // a bitcast, not a conversion.
11144     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
11145       return;
11146 
11147     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
11148     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
11149   }
11150   if (auto VecTy = dyn_cast<VectorType>(Target))
11151     Target = VecTy->getElementType().getTypePtr();
11152 
11153   // Strip complex types.
11154   if (isa<ComplexType>(Source)) {
11155     if (!isa<ComplexType>(Target)) {
11156       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
11157         return;
11158 
11159       return DiagnoseImpCast(S, E, T, CC,
11160                              S.getLangOpts().CPlusPlus
11161                                  ? diag::err_impcast_complex_scalar
11162                                  : diag::warn_impcast_complex_scalar);
11163     }
11164 
11165     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
11166     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
11167   }
11168 
11169   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
11170   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
11171 
11172   // If the source is floating point...
11173   if (SourceBT && SourceBT->isFloatingPoint()) {
11174     // ...and the target is floating point...
11175     if (TargetBT && TargetBT->isFloatingPoint()) {
11176       // ...then warn if we're dropping FP rank.
11177 
11178       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11179           QualType(SourceBT, 0), QualType(TargetBT, 0));
11180       if (Order > 0) {
11181         // Don't warn about float constants that are precisely
11182         // representable in the target type.
11183         Expr::EvalResult result;
11184         if (E->EvaluateAsRValue(result, S.Context)) {
11185           // Value might be a float, a float vector, or a float complex.
11186           if (IsSameFloatAfterCast(result.Val,
11187                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
11188                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
11189             return;
11190         }
11191 
11192         if (S.SourceMgr.isInSystemMacro(CC))
11193           return;
11194 
11195         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
11196       }
11197       // ... or possibly if we're increasing rank, too
11198       else if (Order < 0) {
11199         if (S.SourceMgr.isInSystemMacro(CC))
11200           return;
11201 
11202         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
11203       }
11204       return;
11205     }
11206 
11207     // If the target is integral, always warn.
11208     if (TargetBT && TargetBT->isInteger()) {
11209       if (S.SourceMgr.isInSystemMacro(CC))
11210         return;
11211 
11212       DiagnoseFloatingImpCast(S, E, T, CC);
11213     }
11214 
11215     // Detect the case where a call result is converted from floating-point to
11216     // to bool, and the final argument to the call is converted from bool, to
11217     // discover this typo:
11218     //
11219     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
11220     //
11221     // FIXME: This is an incredibly special case; is there some more general
11222     // way to detect this class of misplaced-parentheses bug?
11223     if (Target->isBooleanType() && isa<CallExpr>(E)) {
11224       // Check last argument of function call to see if it is an
11225       // implicit cast from a type matching the type the result
11226       // is being cast to.
11227       CallExpr *CEx = cast<CallExpr>(E);
11228       if (unsigned NumArgs = CEx->getNumArgs()) {
11229         Expr *LastA = CEx->getArg(NumArgs - 1);
11230         Expr *InnerE = LastA->IgnoreParenImpCasts();
11231         if (isa<ImplicitCastExpr>(LastA) &&
11232             InnerE->getType()->isBooleanType()) {
11233           // Warn on this floating-point to bool conversion
11234           DiagnoseImpCast(S, E, T, CC,
11235                           diag::warn_impcast_floating_point_to_bool);
11236         }
11237       }
11238     }
11239     return;
11240   }
11241 
11242   // Valid casts involving fixed point types should be accounted for here.
11243   if (Source->isFixedPointType()) {
11244     if (Target->isUnsaturatedFixedPointType()) {
11245       Expr::EvalResult Result;
11246       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
11247                                   S.isConstantEvaluated())) {
11248         APFixedPoint Value = Result.Val.getFixedPoint();
11249         APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
11250         APFixedPoint MinVal = S.Context.getFixedPointMin(T);
11251         if (Value > MaxVal || Value < MinVal) {
11252           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11253                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11254                                     << Value.toString() << T
11255                                     << E->getSourceRange()
11256                                     << clang::SourceRange(CC));
11257           return;
11258         }
11259       }
11260     } else if (Target->isIntegerType()) {
11261       Expr::EvalResult Result;
11262       if (!S.isConstantEvaluated() &&
11263           E->EvaluateAsFixedPoint(Result, S.Context,
11264                                   Expr::SE_AllowSideEffects)) {
11265         APFixedPoint FXResult = Result.Val.getFixedPoint();
11266 
11267         bool Overflowed;
11268         llvm::APSInt IntResult = FXResult.convertToInt(
11269             S.Context.getIntWidth(T),
11270             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
11271 
11272         if (Overflowed) {
11273           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11274                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11275                                     << FXResult.toString() << T
11276                                     << E->getSourceRange()
11277                                     << clang::SourceRange(CC));
11278           return;
11279         }
11280       }
11281     }
11282   } else if (Target->isUnsaturatedFixedPointType()) {
11283     if (Source->isIntegerType()) {
11284       Expr::EvalResult Result;
11285       if (!S.isConstantEvaluated() &&
11286           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
11287         llvm::APSInt Value = Result.Val.getInt();
11288 
11289         bool Overflowed;
11290         APFixedPoint IntResult = APFixedPoint::getFromIntValue(
11291             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
11292 
11293         if (Overflowed) {
11294           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11295                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11296                                     << Value.toString(/*Radix=*/10) << T
11297                                     << E->getSourceRange()
11298                                     << clang::SourceRange(CC));
11299           return;
11300         }
11301       }
11302     }
11303   }
11304 
11305   // If we are casting an integer type to a floating point type without
11306   // initialization-list syntax, we might lose accuracy if the floating
11307   // point type has a narrower significand than the integer type.
11308   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
11309       TargetBT->isFloatingType() && !IsListInit) {
11310     // Determine the number of precision bits in the source integer type.
11311     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated());
11312     unsigned int SourcePrecision = SourceRange.Width;
11313 
11314     // Determine the number of precision bits in the
11315     // target floating point type.
11316     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
11317         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
11318 
11319     if (SourcePrecision > 0 && TargetPrecision > 0 &&
11320         SourcePrecision > TargetPrecision) {
11321 
11322       llvm::APSInt SourceInt;
11323       if (E->isIntegerConstantExpr(SourceInt, S.Context)) {
11324         // If the source integer is a constant, convert it to the target
11325         // floating point type. Issue a warning if the value changes
11326         // during the whole conversion.
11327         llvm::APFloat TargetFloatValue(
11328             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
11329         llvm::APFloat::opStatus ConversionStatus =
11330             TargetFloatValue.convertFromAPInt(
11331                 SourceInt, SourceBT->isSignedInteger(),
11332                 llvm::APFloat::rmNearestTiesToEven);
11333 
11334         if (ConversionStatus != llvm::APFloat::opOK) {
11335           std::string PrettySourceValue = SourceInt.toString(10);
11336           SmallString<32> PrettyTargetValue;
11337           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
11338 
11339           S.DiagRuntimeBehavior(
11340               E->getExprLoc(), E,
11341               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
11342                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
11343                   << E->getSourceRange() << clang::SourceRange(CC));
11344         }
11345       } else {
11346         // Otherwise, the implicit conversion may lose precision.
11347         DiagnoseImpCast(S, E, T, CC,
11348                         diag::warn_impcast_integer_float_precision);
11349       }
11350     }
11351   }
11352 
11353   DiagnoseNullConversion(S, E, T, CC);
11354 
11355   S.DiscardMisalignedMemberAddress(Target, E);
11356 
11357   if (Target->isBooleanType())
11358     DiagnoseIntInBoolContext(S, E);
11359 
11360   if (!Source->isIntegerType() || !Target->isIntegerType())
11361     return;
11362 
11363   // TODO: remove this early return once the false positives for constant->bool
11364   // in templates, macros, etc, are reduced or removed.
11365   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
11366     return;
11367 
11368   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
11369       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
11370     return adornObjCBoolConversionDiagWithTernaryFixit(
11371         S, E,
11372         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
11373             << E->getType());
11374   }
11375 
11376   IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated());
11377   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
11378 
11379   if (SourceRange.Width > TargetRange.Width) {
11380     // If the source is a constant, use a default-on diagnostic.
11381     // TODO: this should happen for bitfield stores, too.
11382     Expr::EvalResult Result;
11383     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
11384                          S.isConstantEvaluated())) {
11385       llvm::APSInt Value(32);
11386       Value = Result.Val.getInt();
11387 
11388       if (S.SourceMgr.isInSystemMacro(CC))
11389         return;
11390 
11391       std::string PrettySourceValue = Value.toString(10);
11392       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11393 
11394       S.DiagRuntimeBehavior(
11395           E->getExprLoc(), E,
11396           S.PDiag(diag::warn_impcast_integer_precision_constant)
11397               << PrettySourceValue << PrettyTargetValue << E->getType() << T
11398               << E->getSourceRange() << clang::SourceRange(CC));
11399       return;
11400     }
11401 
11402     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
11403     if (S.SourceMgr.isInSystemMacro(CC))
11404       return;
11405 
11406     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
11407       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
11408                              /* pruneControlFlow */ true);
11409     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
11410   }
11411 
11412   if (TargetRange.Width > SourceRange.Width) {
11413     if (auto *UO = dyn_cast<UnaryOperator>(E))
11414       if (UO->getOpcode() == UO_Minus)
11415         if (Source->isUnsignedIntegerType()) {
11416           if (Target->isUnsignedIntegerType())
11417             return DiagnoseImpCast(S, E, T, CC,
11418                                    diag::warn_impcast_high_order_zero_bits);
11419           if (Target->isSignedIntegerType())
11420             return DiagnoseImpCast(S, E, T, CC,
11421                                    diag::warn_impcast_nonnegative_result);
11422         }
11423   }
11424 
11425   if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
11426       SourceRange.NonNegative && Source->isSignedIntegerType()) {
11427     // Warn when doing a signed to signed conversion, warn if the positive
11428     // source value is exactly the width of the target type, which will
11429     // cause a negative value to be stored.
11430 
11431     Expr::EvalResult Result;
11432     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
11433         !S.SourceMgr.isInSystemMacro(CC)) {
11434       llvm::APSInt Value = Result.Val.getInt();
11435       if (isSameWidthConstantConversion(S, E, T, CC)) {
11436         std::string PrettySourceValue = Value.toString(10);
11437         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11438 
11439         S.DiagRuntimeBehavior(
11440             E->getExprLoc(), E,
11441             S.PDiag(diag::warn_impcast_integer_precision_constant)
11442                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
11443                 << E->getSourceRange() << clang::SourceRange(CC));
11444         return;
11445       }
11446     }
11447 
11448     // Fall through for non-constants to give a sign conversion warning.
11449   }
11450 
11451   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
11452       (!TargetRange.NonNegative && SourceRange.NonNegative &&
11453        SourceRange.Width == TargetRange.Width)) {
11454     if (S.SourceMgr.isInSystemMacro(CC))
11455       return;
11456 
11457     unsigned DiagID = diag::warn_impcast_integer_sign;
11458 
11459     // Traditionally, gcc has warned about this under -Wsign-compare.
11460     // We also want to warn about it in -Wconversion.
11461     // So if -Wconversion is off, use a completely identical diagnostic
11462     // in the sign-compare group.
11463     // The conditional-checking code will
11464     if (ICContext) {
11465       DiagID = diag::warn_impcast_integer_sign_conditional;
11466       *ICContext = true;
11467     }
11468 
11469     return DiagnoseImpCast(S, E, T, CC, DiagID);
11470   }
11471 
11472   // Diagnose conversions between different enumeration types.
11473   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
11474   // type, to give us better diagnostics.
11475   QualType SourceType = E->getType();
11476   if (!S.getLangOpts().CPlusPlus) {
11477     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11478       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
11479         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
11480         SourceType = S.Context.getTypeDeclType(Enum);
11481         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
11482       }
11483   }
11484 
11485   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
11486     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
11487       if (SourceEnum->getDecl()->hasNameForLinkage() &&
11488           TargetEnum->getDecl()->hasNameForLinkage() &&
11489           SourceEnum != TargetEnum) {
11490         if (S.SourceMgr.isInSystemMacro(CC))
11491           return;
11492 
11493         return DiagnoseImpCast(S, E, SourceType, T, CC,
11494                                diag::warn_impcast_different_enum_types);
11495       }
11496 }
11497 
11498 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11499                                      SourceLocation CC, QualType T);
11500 
11501 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
11502                                     SourceLocation CC, bool &ICContext) {
11503   E = E->IgnoreParenImpCasts();
11504 
11505   if (isa<ConditionalOperator>(E))
11506     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
11507 
11508   AnalyzeImplicitConversions(S, E, CC);
11509   if (E->getType() != T)
11510     return CheckImplicitConversion(S, E, T, CC, &ICContext);
11511 }
11512 
11513 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11514                                      SourceLocation CC, QualType T) {
11515   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
11516 
11517   bool Suspicious = false;
11518   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
11519   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
11520 
11521   if (T->isBooleanType())
11522     DiagnoseIntInBoolContext(S, E);
11523 
11524   // If -Wconversion would have warned about either of the candidates
11525   // for a signedness conversion to the context type...
11526   if (!Suspicious) return;
11527 
11528   // ...but it's currently ignored...
11529   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
11530     return;
11531 
11532   // ...then check whether it would have warned about either of the
11533   // candidates for a signedness conversion to the condition type.
11534   if (E->getType() == T) return;
11535 
11536   Suspicious = false;
11537   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
11538                           E->getType(), CC, &Suspicious);
11539   if (!Suspicious)
11540     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
11541                             E->getType(), CC, &Suspicious);
11542 }
11543 
11544 /// Check conversion of given expression to boolean.
11545 /// Input argument E is a logical expression.
11546 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
11547   if (S.getLangOpts().Bool)
11548     return;
11549   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
11550     return;
11551   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
11552 }
11553 
11554 /// AnalyzeImplicitConversions - Find and report any interesting
11555 /// implicit conversions in the given expression.  There are a couple
11556 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
11557 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
11558                                        bool IsListInit/*= false*/) {
11559   QualType T = OrigE->getType();
11560   Expr *E = OrigE->IgnoreParenImpCasts();
11561 
11562   // Propagate whether we are in a C++ list initialization expression.
11563   // If so, we do not issue warnings for implicit int-float conversion
11564   // precision loss, because C++11 narrowing already handles it.
11565   IsListInit =
11566       IsListInit || (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
11567 
11568   if (E->isTypeDependent() || E->isValueDependent())
11569     return;
11570 
11571   if (const auto *UO = dyn_cast<UnaryOperator>(E))
11572     if (UO->getOpcode() == UO_Not &&
11573         UO->getSubExpr()->isKnownToHaveBooleanValue())
11574       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
11575           << OrigE->getSourceRange() << T->isBooleanType()
11576           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
11577 
11578   // For conditional operators, we analyze the arguments as if they
11579   // were being fed directly into the output.
11580   if (isa<ConditionalOperator>(E)) {
11581     ConditionalOperator *CO = cast<ConditionalOperator>(E);
11582     CheckConditionalOperator(S, CO, CC, T);
11583     return;
11584   }
11585 
11586   // Check implicit argument conversions for function calls.
11587   if (CallExpr *Call = dyn_cast<CallExpr>(E))
11588     CheckImplicitArgumentConversions(S, Call, CC);
11589 
11590   // Go ahead and check any implicit conversions we might have skipped.
11591   // The non-canonical typecheck is just an optimization;
11592   // CheckImplicitConversion will filter out dead implicit conversions.
11593   if (E->getType() != T)
11594     CheckImplicitConversion(S, E, T, CC, nullptr, IsListInit);
11595 
11596   // Now continue drilling into this expression.
11597 
11598   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
11599     // The bound subexpressions in a PseudoObjectExpr are not reachable
11600     // as transitive children.
11601     // FIXME: Use a more uniform representation for this.
11602     for (auto *SE : POE->semantics())
11603       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
11604         AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC, IsListInit);
11605   }
11606 
11607   // Skip past explicit casts.
11608   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
11609     E = CE->getSubExpr()->IgnoreParenImpCasts();
11610     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
11611       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
11612     return AnalyzeImplicitConversions(S, E, CC, IsListInit);
11613   }
11614 
11615   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11616     // Do a somewhat different check with comparison operators.
11617     if (BO->isComparisonOp())
11618       return AnalyzeComparison(S, BO);
11619 
11620     // And with simple assignments.
11621     if (BO->getOpcode() == BO_Assign)
11622       return AnalyzeAssignment(S, BO);
11623     // And with compound assignments.
11624     if (BO->isAssignmentOp())
11625       return AnalyzeCompoundAssignment(S, BO);
11626   }
11627 
11628   // These break the otherwise-useful invariant below.  Fortunately,
11629   // we don't really need to recurse into them, because any internal
11630   // expressions should have been analyzed already when they were
11631   // built into statements.
11632   if (isa<StmtExpr>(E)) return;
11633 
11634   // Don't descend into unevaluated contexts.
11635   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
11636 
11637   // Now just recurse over the expression's children.
11638   CC = E->getExprLoc();
11639   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
11640   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
11641   for (Stmt *SubStmt : E->children()) {
11642     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
11643     if (!ChildExpr)
11644       continue;
11645 
11646     if (IsLogicalAndOperator &&
11647         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
11648       // Ignore checking string literals that are in logical and operators.
11649       // This is a common pattern for asserts.
11650       continue;
11651     AnalyzeImplicitConversions(S, ChildExpr, CC, IsListInit);
11652   }
11653 
11654   if (BO && BO->isLogicalOp()) {
11655     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
11656     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
11657       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
11658 
11659     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
11660     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
11661       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
11662   }
11663 
11664   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
11665     if (U->getOpcode() == UO_LNot) {
11666       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
11667     } else if (U->getOpcode() != UO_AddrOf) {
11668       if (U->getSubExpr()->getType()->isAtomicType())
11669         S.Diag(U->getSubExpr()->getBeginLoc(),
11670                diag::warn_atomic_implicit_seq_cst);
11671     }
11672   }
11673 }
11674 
11675 /// Diagnose integer type and any valid implicit conversion to it.
11676 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
11677   // Taking into account implicit conversions,
11678   // allow any integer.
11679   if (!E->getType()->isIntegerType()) {
11680     S.Diag(E->getBeginLoc(),
11681            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
11682     return true;
11683   }
11684   // Potentially emit standard warnings for implicit conversions if enabled
11685   // using -Wconversion.
11686   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
11687   return false;
11688 }
11689 
11690 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
11691 // Returns true when emitting a warning about taking the address of a reference.
11692 static bool CheckForReference(Sema &SemaRef, const Expr *E,
11693                               const PartialDiagnostic &PD) {
11694   E = E->IgnoreParenImpCasts();
11695 
11696   const FunctionDecl *FD = nullptr;
11697 
11698   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11699     if (!DRE->getDecl()->getType()->isReferenceType())
11700       return false;
11701   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
11702     if (!M->getMemberDecl()->getType()->isReferenceType())
11703       return false;
11704   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
11705     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
11706       return false;
11707     FD = Call->getDirectCallee();
11708   } else {
11709     return false;
11710   }
11711 
11712   SemaRef.Diag(E->getExprLoc(), PD);
11713 
11714   // If possible, point to location of function.
11715   if (FD) {
11716     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
11717   }
11718 
11719   return true;
11720 }
11721 
11722 // Returns true if the SourceLocation is expanded from any macro body.
11723 // Returns false if the SourceLocation is invalid, is from not in a macro
11724 // expansion, or is from expanded from a top-level macro argument.
11725 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
11726   if (Loc.isInvalid())
11727     return false;
11728 
11729   while (Loc.isMacroID()) {
11730     if (SM.isMacroBodyExpansion(Loc))
11731       return true;
11732     Loc = SM.getImmediateMacroCallerLoc(Loc);
11733   }
11734 
11735   return false;
11736 }
11737 
11738 /// Diagnose pointers that are always non-null.
11739 /// \param E the expression containing the pointer
11740 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
11741 /// compared to a null pointer
11742 /// \param IsEqual True when the comparison is equal to a null pointer
11743 /// \param Range Extra SourceRange to highlight in the diagnostic
11744 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
11745                                         Expr::NullPointerConstantKind NullKind,
11746                                         bool IsEqual, SourceRange Range) {
11747   if (!E)
11748     return;
11749 
11750   // Don't warn inside macros.
11751   if (E->getExprLoc().isMacroID()) {
11752     const SourceManager &SM = getSourceManager();
11753     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
11754         IsInAnyMacroBody(SM, Range.getBegin()))
11755       return;
11756   }
11757   E = E->IgnoreImpCasts();
11758 
11759   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
11760 
11761   if (isa<CXXThisExpr>(E)) {
11762     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
11763                                 : diag::warn_this_bool_conversion;
11764     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
11765     return;
11766   }
11767 
11768   bool IsAddressOf = false;
11769 
11770   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
11771     if (UO->getOpcode() != UO_AddrOf)
11772       return;
11773     IsAddressOf = true;
11774     E = UO->getSubExpr();
11775   }
11776 
11777   if (IsAddressOf) {
11778     unsigned DiagID = IsCompare
11779                           ? diag::warn_address_of_reference_null_compare
11780                           : diag::warn_address_of_reference_bool_conversion;
11781     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
11782                                          << IsEqual;
11783     if (CheckForReference(*this, E, PD)) {
11784       return;
11785     }
11786   }
11787 
11788   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
11789     bool IsParam = isa<NonNullAttr>(NonnullAttr);
11790     std::string Str;
11791     llvm::raw_string_ostream S(Str);
11792     E->printPretty(S, nullptr, getPrintingPolicy());
11793     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
11794                                 : diag::warn_cast_nonnull_to_bool;
11795     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
11796       << E->getSourceRange() << Range << IsEqual;
11797     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
11798   };
11799 
11800   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
11801   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
11802     if (auto *Callee = Call->getDirectCallee()) {
11803       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
11804         ComplainAboutNonnullParamOrCall(A);
11805         return;
11806       }
11807     }
11808   }
11809 
11810   // Expect to find a single Decl.  Skip anything more complicated.
11811   ValueDecl *D = nullptr;
11812   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
11813     D = R->getDecl();
11814   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
11815     D = M->getMemberDecl();
11816   }
11817 
11818   // Weak Decls can be null.
11819   if (!D || D->isWeak())
11820     return;
11821 
11822   // Check for parameter decl with nonnull attribute
11823   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
11824     if (getCurFunction() &&
11825         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
11826       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
11827         ComplainAboutNonnullParamOrCall(A);
11828         return;
11829       }
11830 
11831       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
11832         // Skip function template not specialized yet.
11833         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
11834           return;
11835         auto ParamIter = llvm::find(FD->parameters(), PV);
11836         assert(ParamIter != FD->param_end());
11837         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
11838 
11839         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
11840           if (!NonNull->args_size()) {
11841               ComplainAboutNonnullParamOrCall(NonNull);
11842               return;
11843           }
11844 
11845           for (const ParamIdx &ArgNo : NonNull->args()) {
11846             if (ArgNo.getASTIndex() == ParamNo) {
11847               ComplainAboutNonnullParamOrCall(NonNull);
11848               return;
11849             }
11850           }
11851         }
11852       }
11853     }
11854   }
11855 
11856   QualType T = D->getType();
11857   const bool IsArray = T->isArrayType();
11858   const bool IsFunction = T->isFunctionType();
11859 
11860   // Address of function is used to silence the function warning.
11861   if (IsAddressOf && IsFunction) {
11862     return;
11863   }
11864 
11865   // Found nothing.
11866   if (!IsAddressOf && !IsFunction && !IsArray)
11867     return;
11868 
11869   // Pretty print the expression for the diagnostic.
11870   std::string Str;
11871   llvm::raw_string_ostream S(Str);
11872   E->printPretty(S, nullptr, getPrintingPolicy());
11873 
11874   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
11875                               : diag::warn_impcast_pointer_to_bool;
11876   enum {
11877     AddressOf,
11878     FunctionPointer,
11879     ArrayPointer
11880   } DiagType;
11881   if (IsAddressOf)
11882     DiagType = AddressOf;
11883   else if (IsFunction)
11884     DiagType = FunctionPointer;
11885   else if (IsArray)
11886     DiagType = ArrayPointer;
11887   else
11888     llvm_unreachable("Could not determine diagnostic.");
11889   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
11890                                 << Range << IsEqual;
11891 
11892   if (!IsFunction)
11893     return;
11894 
11895   // Suggest '&' to silence the function warning.
11896   Diag(E->getExprLoc(), diag::note_function_warning_silence)
11897       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
11898 
11899   // Check to see if '()' fixit should be emitted.
11900   QualType ReturnType;
11901   UnresolvedSet<4> NonTemplateOverloads;
11902   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
11903   if (ReturnType.isNull())
11904     return;
11905 
11906   if (IsCompare) {
11907     // There are two cases here.  If there is null constant, the only suggest
11908     // for a pointer return type.  If the null is 0, then suggest if the return
11909     // type is a pointer or an integer type.
11910     if (!ReturnType->isPointerType()) {
11911       if (NullKind == Expr::NPCK_ZeroExpression ||
11912           NullKind == Expr::NPCK_ZeroLiteral) {
11913         if (!ReturnType->isIntegerType())
11914           return;
11915       } else {
11916         return;
11917       }
11918     }
11919   } else { // !IsCompare
11920     // For function to bool, only suggest if the function pointer has bool
11921     // return type.
11922     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
11923       return;
11924   }
11925   Diag(E->getExprLoc(), diag::note_function_to_function_call)
11926       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
11927 }
11928 
11929 /// Diagnoses "dangerous" implicit conversions within the given
11930 /// expression (which is a full expression).  Implements -Wconversion
11931 /// and -Wsign-compare.
11932 ///
11933 /// \param CC the "context" location of the implicit conversion, i.e.
11934 ///   the most location of the syntactic entity requiring the implicit
11935 ///   conversion
11936 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
11937   // Don't diagnose in unevaluated contexts.
11938   if (isUnevaluatedContext())
11939     return;
11940 
11941   // Don't diagnose for value- or type-dependent expressions.
11942   if (E->isTypeDependent() || E->isValueDependent())
11943     return;
11944 
11945   // Check for array bounds violations in cases where the check isn't triggered
11946   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
11947   // ArraySubscriptExpr is on the RHS of a variable initialization.
11948   CheckArrayAccess(E);
11949 
11950   // This is not the right CC for (e.g.) a variable initialization.
11951   AnalyzeImplicitConversions(*this, E, CC);
11952 }
11953 
11954 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
11955 /// Input argument E is a logical expression.
11956 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
11957   ::CheckBoolLikeConversion(*this, E, CC);
11958 }
11959 
11960 /// Diagnose when expression is an integer constant expression and its evaluation
11961 /// results in integer overflow
11962 void Sema::CheckForIntOverflow (Expr *E) {
11963   // Use a work list to deal with nested struct initializers.
11964   SmallVector<Expr *, 2> Exprs(1, E);
11965 
11966   do {
11967     Expr *OriginalE = Exprs.pop_back_val();
11968     Expr *E = OriginalE->IgnoreParenCasts();
11969 
11970     if (isa<BinaryOperator>(E)) {
11971       E->EvaluateForOverflow(Context);
11972       continue;
11973     }
11974 
11975     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
11976       Exprs.append(InitList->inits().begin(), InitList->inits().end());
11977     else if (isa<ObjCBoxedExpr>(OriginalE))
11978       E->EvaluateForOverflow(Context);
11979     else if (auto Call = dyn_cast<CallExpr>(E))
11980       Exprs.append(Call->arg_begin(), Call->arg_end());
11981     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
11982       Exprs.append(Message->arg_begin(), Message->arg_end());
11983   } while (!Exprs.empty());
11984 }
11985 
11986 namespace {
11987 
11988 /// Visitor for expressions which looks for unsequenced operations on the
11989 /// same object.
11990 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
11991   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
11992 
11993   /// A tree of sequenced regions within an expression. Two regions are
11994   /// unsequenced if one is an ancestor or a descendent of the other. When we
11995   /// finish processing an expression with sequencing, such as a comma
11996   /// expression, we fold its tree nodes into its parent, since they are
11997   /// unsequenced with respect to nodes we will visit later.
11998   class SequenceTree {
11999     struct Value {
12000       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
12001       unsigned Parent : 31;
12002       unsigned Merged : 1;
12003     };
12004     SmallVector<Value, 8> Values;
12005 
12006   public:
12007     /// A region within an expression which may be sequenced with respect
12008     /// to some other region.
12009     class Seq {
12010       friend class SequenceTree;
12011 
12012       unsigned Index;
12013 
12014       explicit Seq(unsigned N) : Index(N) {}
12015 
12016     public:
12017       Seq() : Index(0) {}
12018     };
12019 
12020     SequenceTree() { Values.push_back(Value(0)); }
12021     Seq root() const { return Seq(0); }
12022 
12023     /// Create a new sequence of operations, which is an unsequenced
12024     /// subset of \p Parent. This sequence of operations is sequenced with
12025     /// respect to other children of \p Parent.
12026     Seq allocate(Seq Parent) {
12027       Values.push_back(Value(Parent.Index));
12028       return Seq(Values.size() - 1);
12029     }
12030 
12031     /// Merge a sequence of operations into its parent.
12032     void merge(Seq S) {
12033       Values[S.Index].Merged = true;
12034     }
12035 
12036     /// Determine whether two operations are unsequenced. This operation
12037     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
12038     /// should have been merged into its parent as appropriate.
12039     bool isUnsequenced(Seq Cur, Seq Old) {
12040       unsigned C = representative(Cur.Index);
12041       unsigned Target = representative(Old.Index);
12042       while (C >= Target) {
12043         if (C == Target)
12044           return true;
12045         C = Values[C].Parent;
12046       }
12047       return false;
12048     }
12049 
12050   private:
12051     /// Pick a representative for a sequence.
12052     unsigned representative(unsigned K) {
12053       if (Values[K].Merged)
12054         // Perform path compression as we go.
12055         return Values[K].Parent = representative(Values[K].Parent);
12056       return K;
12057     }
12058   };
12059 
12060   /// An object for which we can track unsequenced uses.
12061   using Object = const NamedDecl *;
12062 
12063   /// Different flavors of object usage which we track. We only track the
12064   /// least-sequenced usage of each kind.
12065   enum UsageKind {
12066     /// A read of an object. Multiple unsequenced reads are OK.
12067     UK_Use,
12068 
12069     /// A modification of an object which is sequenced before the value
12070     /// computation of the expression, such as ++n in C++.
12071     UK_ModAsValue,
12072 
12073     /// A modification of an object which is not sequenced before the value
12074     /// computation of the expression, such as n++.
12075     UK_ModAsSideEffect,
12076 
12077     UK_Count = UK_ModAsSideEffect + 1
12078   };
12079 
12080   /// Bundle together a sequencing region and the expression corresponding
12081   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
12082   struct Usage {
12083     const Expr *UsageExpr;
12084     SequenceTree::Seq Seq;
12085 
12086     Usage() : UsageExpr(nullptr), Seq() {}
12087   };
12088 
12089   struct UsageInfo {
12090     Usage Uses[UK_Count];
12091 
12092     /// Have we issued a diagnostic for this object already?
12093     bool Diagnosed;
12094 
12095     UsageInfo() : Uses(), Diagnosed(false) {}
12096   };
12097   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
12098 
12099   Sema &SemaRef;
12100 
12101   /// Sequenced regions within the expression.
12102   SequenceTree Tree;
12103 
12104   /// Declaration modifications and references which we have seen.
12105   UsageInfoMap UsageMap;
12106 
12107   /// The region we are currently within.
12108   SequenceTree::Seq Region;
12109 
12110   /// Filled in with declarations which were modified as a side-effect
12111   /// (that is, post-increment operations).
12112   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
12113 
12114   /// Expressions to check later. We defer checking these to reduce
12115   /// stack usage.
12116   SmallVectorImpl<const Expr *> &WorkList;
12117 
12118   /// RAII object wrapping the visitation of a sequenced subexpression of an
12119   /// expression. At the end of this process, the side-effects of the evaluation
12120   /// become sequenced with respect to the value computation of the result, so
12121   /// we downgrade any UK_ModAsSideEffect within the evaluation to
12122   /// UK_ModAsValue.
12123   struct SequencedSubexpression {
12124     SequencedSubexpression(SequenceChecker &Self)
12125       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
12126       Self.ModAsSideEffect = &ModAsSideEffect;
12127     }
12128 
12129     ~SequencedSubexpression() {
12130       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
12131         // Add a new usage with usage kind UK_ModAsValue, and then restore
12132         // the previous usage with UK_ModAsSideEffect (thus clearing it if
12133         // the previous one was empty).
12134         UsageInfo &UI = Self.UsageMap[M.first];
12135         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
12136         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
12137         SideEffectUsage = M.second;
12138       }
12139       Self.ModAsSideEffect = OldModAsSideEffect;
12140     }
12141 
12142     SequenceChecker &Self;
12143     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
12144     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
12145   };
12146 
12147   /// RAII object wrapping the visitation of a subexpression which we might
12148   /// choose to evaluate as a constant. If any subexpression is evaluated and
12149   /// found to be non-constant, this allows us to suppress the evaluation of
12150   /// the outer expression.
12151   class EvaluationTracker {
12152   public:
12153     EvaluationTracker(SequenceChecker &Self)
12154         : Self(Self), Prev(Self.EvalTracker) {
12155       Self.EvalTracker = this;
12156     }
12157 
12158     ~EvaluationTracker() {
12159       Self.EvalTracker = Prev;
12160       if (Prev)
12161         Prev->EvalOK &= EvalOK;
12162     }
12163 
12164     bool evaluate(const Expr *E, bool &Result) {
12165       if (!EvalOK || E->isValueDependent())
12166         return false;
12167       EvalOK = E->EvaluateAsBooleanCondition(
12168           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
12169       return EvalOK;
12170     }
12171 
12172   private:
12173     SequenceChecker &Self;
12174     EvaluationTracker *Prev;
12175     bool EvalOK = true;
12176   } *EvalTracker = nullptr;
12177 
12178   /// Find the object which is produced by the specified expression,
12179   /// if any.
12180   Object getObject(const Expr *E, bool Mod) const {
12181     E = E->IgnoreParenCasts();
12182     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12183       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
12184         return getObject(UO->getSubExpr(), Mod);
12185     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12186       if (BO->getOpcode() == BO_Comma)
12187         return getObject(BO->getRHS(), Mod);
12188       if (Mod && BO->isAssignmentOp())
12189         return getObject(BO->getLHS(), Mod);
12190     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12191       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
12192       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
12193         return ME->getMemberDecl();
12194     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12195       // FIXME: If this is a reference, map through to its value.
12196       return DRE->getDecl();
12197     return nullptr;
12198   }
12199 
12200   /// Note that an object \p O was modified or used by an expression
12201   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
12202   /// the object \p O as obtained via the \p UsageMap.
12203   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
12204     // Get the old usage for the given object and usage kind.
12205     Usage &U = UI.Uses[UK];
12206     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
12207       // If we have a modification as side effect and are in a sequenced
12208       // subexpression, save the old Usage so that we can restore it later
12209       // in SequencedSubexpression::~SequencedSubexpression.
12210       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
12211         ModAsSideEffect->push_back(std::make_pair(O, U));
12212       // Then record the new usage with the current sequencing region.
12213       U.UsageExpr = UsageExpr;
12214       U.Seq = Region;
12215     }
12216   }
12217 
12218   /// Check whether a modification or use of an object \p O in an expression
12219   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
12220   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
12221   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
12222   /// usage and false we are checking for a mod-use unsequenced usage.
12223   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
12224                   UsageKind OtherKind, bool IsModMod) {
12225     if (UI.Diagnosed)
12226       return;
12227 
12228     const Usage &U = UI.Uses[OtherKind];
12229     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
12230       return;
12231 
12232     const Expr *Mod = U.UsageExpr;
12233     const Expr *ModOrUse = UsageExpr;
12234     if (OtherKind == UK_Use)
12235       std::swap(Mod, ModOrUse);
12236 
12237     SemaRef.DiagRuntimeBehavior(
12238         Mod->getExprLoc(), {Mod, ModOrUse},
12239         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
12240                                : diag::warn_unsequenced_mod_use)
12241             << O << SourceRange(ModOrUse->getExprLoc()));
12242     UI.Diagnosed = true;
12243   }
12244 
12245   // A note on note{Pre, Post}{Use, Mod}:
12246   //
12247   // (It helps to follow the algorithm with an expression such as
12248   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
12249   //  operations before C++17 and both are well-defined in C++17).
12250   //
12251   // When visiting a node which uses/modify an object we first call notePreUse
12252   // or notePreMod before visiting its sub-expression(s). At this point the
12253   // children of the current node have not yet been visited and so the eventual
12254   // uses/modifications resulting from the children of the current node have not
12255   // been recorded yet.
12256   //
12257   // We then visit the children of the current node. After that notePostUse or
12258   // notePostMod is called. These will 1) detect an unsequenced modification
12259   // as side effect (as in "k++ + k") and 2) add a new usage with the
12260   // appropriate usage kind.
12261   //
12262   // We also have to be careful that some operation sequences modification as
12263   // side effect as well (for example: || or ,). To account for this we wrap
12264   // the visitation of such a sub-expression (for example: the LHS of || or ,)
12265   // with SequencedSubexpression. SequencedSubexpression is an RAII object
12266   // which record usages which are modifications as side effect, and then
12267   // downgrade them (or more accurately restore the previous usage which was a
12268   // modification as side effect) when exiting the scope of the sequenced
12269   // subexpression.
12270 
12271   void notePreUse(Object O, const Expr *UseExpr) {
12272     UsageInfo &UI = UsageMap[O];
12273     // Uses conflict with other modifications.
12274     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
12275   }
12276 
12277   void notePostUse(Object O, const Expr *UseExpr) {
12278     UsageInfo &UI = UsageMap[O];
12279     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
12280                /*IsModMod=*/false);
12281     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
12282   }
12283 
12284   void notePreMod(Object O, const Expr *ModExpr) {
12285     UsageInfo &UI = UsageMap[O];
12286     // Modifications conflict with other modifications and with uses.
12287     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
12288     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
12289   }
12290 
12291   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
12292     UsageInfo &UI = UsageMap[O];
12293     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
12294                /*IsModMod=*/true);
12295     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
12296   }
12297 
12298 public:
12299   SequenceChecker(Sema &S, const Expr *E,
12300                   SmallVectorImpl<const Expr *> &WorkList)
12301       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
12302     Visit(E);
12303     // Silence a -Wunused-private-field since WorkList is now unused.
12304     // TODO: Evaluate if it can be used, and if not remove it.
12305     (void)this->WorkList;
12306   }
12307 
12308   void VisitStmt(const Stmt *S) {
12309     // Skip all statements which aren't expressions for now.
12310   }
12311 
12312   void VisitExpr(const Expr *E) {
12313     // By default, just recurse to evaluated subexpressions.
12314     Base::VisitStmt(E);
12315   }
12316 
12317   void VisitCastExpr(const CastExpr *E) {
12318     Object O = Object();
12319     if (E->getCastKind() == CK_LValueToRValue)
12320       O = getObject(E->getSubExpr(), false);
12321 
12322     if (O)
12323       notePreUse(O, E);
12324     VisitExpr(E);
12325     if (O)
12326       notePostUse(O, E);
12327   }
12328 
12329   void VisitSequencedExpressions(const Expr *SequencedBefore,
12330                                  const Expr *SequencedAfter) {
12331     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
12332     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
12333     SequenceTree::Seq OldRegion = Region;
12334 
12335     {
12336       SequencedSubexpression SeqBefore(*this);
12337       Region = BeforeRegion;
12338       Visit(SequencedBefore);
12339     }
12340 
12341     Region = AfterRegion;
12342     Visit(SequencedAfter);
12343 
12344     Region = OldRegion;
12345 
12346     Tree.merge(BeforeRegion);
12347     Tree.merge(AfterRegion);
12348   }
12349 
12350   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
12351     // C++17 [expr.sub]p1:
12352     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
12353     //   expression E1 is sequenced before the expression E2.
12354     if (SemaRef.getLangOpts().CPlusPlus17)
12355       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
12356     else {
12357       Visit(ASE->getLHS());
12358       Visit(ASE->getRHS());
12359     }
12360   }
12361 
12362   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
12363   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
12364   void VisitBinPtrMem(const BinaryOperator *BO) {
12365     // C++17 [expr.mptr.oper]p4:
12366     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
12367     //  the expression E1 is sequenced before the expression E2.
12368     if (SemaRef.getLangOpts().CPlusPlus17)
12369       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12370     else {
12371       Visit(BO->getLHS());
12372       Visit(BO->getRHS());
12373     }
12374   }
12375 
12376   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
12377   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
12378   void VisitBinShlShr(const BinaryOperator *BO) {
12379     // C++17 [expr.shift]p4:
12380     //  The expression E1 is sequenced before the expression E2.
12381     if (SemaRef.getLangOpts().CPlusPlus17)
12382       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12383     else {
12384       Visit(BO->getLHS());
12385       Visit(BO->getRHS());
12386     }
12387   }
12388 
12389   void VisitBinComma(const BinaryOperator *BO) {
12390     // C++11 [expr.comma]p1:
12391     //   Every value computation and side effect associated with the left
12392     //   expression is sequenced before every value computation and side
12393     //   effect associated with the right expression.
12394     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12395   }
12396 
12397   void VisitBinAssign(const BinaryOperator *BO) {
12398     SequenceTree::Seq RHSRegion;
12399     SequenceTree::Seq LHSRegion;
12400     if (SemaRef.getLangOpts().CPlusPlus17) {
12401       RHSRegion = Tree.allocate(Region);
12402       LHSRegion = Tree.allocate(Region);
12403     } else {
12404       RHSRegion = Region;
12405       LHSRegion = Region;
12406     }
12407     SequenceTree::Seq OldRegion = Region;
12408 
12409     // C++11 [expr.ass]p1:
12410     //  [...] the assignment is sequenced after the value computation
12411     //  of the right and left operands, [...]
12412     //
12413     // so check it before inspecting the operands and update the
12414     // map afterwards.
12415     Object O = getObject(BO->getLHS(), /*Mod=*/true);
12416     if (O)
12417       notePreMod(O, BO);
12418 
12419     if (SemaRef.getLangOpts().CPlusPlus17) {
12420       // C++17 [expr.ass]p1:
12421       //  [...] The right operand is sequenced before the left operand. [...]
12422       {
12423         SequencedSubexpression SeqBefore(*this);
12424         Region = RHSRegion;
12425         Visit(BO->getRHS());
12426       }
12427 
12428       Region = LHSRegion;
12429       Visit(BO->getLHS());
12430 
12431       if (O && isa<CompoundAssignOperator>(BO))
12432         notePostUse(O, BO);
12433 
12434     } else {
12435       // C++11 does not specify any sequencing between the LHS and RHS.
12436       Region = LHSRegion;
12437       Visit(BO->getLHS());
12438 
12439       if (O && isa<CompoundAssignOperator>(BO))
12440         notePostUse(O, BO);
12441 
12442       Region = RHSRegion;
12443       Visit(BO->getRHS());
12444     }
12445 
12446     // C++11 [expr.ass]p1:
12447     //  the assignment is sequenced [...] before the value computation of the
12448     //  assignment expression.
12449     // C11 6.5.16/3 has no such rule.
12450     Region = OldRegion;
12451     if (O)
12452       notePostMod(O, BO,
12453                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12454                                                   : UK_ModAsSideEffect);
12455     if (SemaRef.getLangOpts().CPlusPlus17) {
12456       Tree.merge(RHSRegion);
12457       Tree.merge(LHSRegion);
12458     }
12459   }
12460 
12461   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
12462     VisitBinAssign(CAO);
12463   }
12464 
12465   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12466   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12467   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
12468     Object O = getObject(UO->getSubExpr(), true);
12469     if (!O)
12470       return VisitExpr(UO);
12471 
12472     notePreMod(O, UO);
12473     Visit(UO->getSubExpr());
12474     // C++11 [expr.pre.incr]p1:
12475     //   the expression ++x is equivalent to x+=1
12476     notePostMod(O, UO,
12477                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12478                                                 : UK_ModAsSideEffect);
12479   }
12480 
12481   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12482   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12483   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
12484     Object O = getObject(UO->getSubExpr(), true);
12485     if (!O)
12486       return VisitExpr(UO);
12487 
12488     notePreMod(O, UO);
12489     Visit(UO->getSubExpr());
12490     notePostMod(O, UO, UK_ModAsSideEffect);
12491   }
12492 
12493   void VisitBinLOr(const BinaryOperator *BO) {
12494     // C++11 [expr.log.or]p2:
12495     //  If the second expression is evaluated, every value computation and
12496     //  side effect associated with the first expression is sequenced before
12497     //  every value computation and side effect associated with the
12498     //  second expression.
12499     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
12500     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
12501     SequenceTree::Seq OldRegion = Region;
12502 
12503     EvaluationTracker Eval(*this);
12504     {
12505       SequencedSubexpression Sequenced(*this);
12506       Region = LHSRegion;
12507       Visit(BO->getLHS());
12508     }
12509 
12510     // C++11 [expr.log.or]p1:
12511     //  [...] the second operand is not evaluated if the first operand
12512     //  evaluates to true.
12513     bool EvalResult = false;
12514     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
12515     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
12516     if (ShouldVisitRHS) {
12517       Region = RHSRegion;
12518       Visit(BO->getRHS());
12519     }
12520 
12521     Region = OldRegion;
12522     Tree.merge(LHSRegion);
12523     Tree.merge(RHSRegion);
12524   }
12525 
12526   void VisitBinLAnd(const BinaryOperator *BO) {
12527     // C++11 [expr.log.and]p2:
12528     //  If the second expression is evaluated, every value computation and
12529     //  side effect associated with the first expression is sequenced before
12530     //  every value computation and side effect associated with the
12531     //  second expression.
12532     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
12533     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
12534     SequenceTree::Seq OldRegion = Region;
12535 
12536     EvaluationTracker Eval(*this);
12537     {
12538       SequencedSubexpression Sequenced(*this);
12539       Region = LHSRegion;
12540       Visit(BO->getLHS());
12541     }
12542 
12543     // C++11 [expr.log.and]p1:
12544     //  [...] the second operand is not evaluated if the first operand is false.
12545     bool EvalResult = false;
12546     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
12547     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
12548     if (ShouldVisitRHS) {
12549       Region = RHSRegion;
12550       Visit(BO->getRHS());
12551     }
12552 
12553     Region = OldRegion;
12554     Tree.merge(LHSRegion);
12555     Tree.merge(RHSRegion);
12556   }
12557 
12558   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
12559     // C++11 [expr.cond]p1:
12560     //  [...] Every value computation and side effect associated with the first
12561     //  expression is sequenced before every value computation and side effect
12562     //  associated with the second or third expression.
12563     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
12564 
12565     // No sequencing is specified between the true and false expression.
12566     // However since exactly one of both is going to be evaluated we can
12567     // consider them to be sequenced. This is needed to avoid warning on
12568     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
12569     // both the true and false expressions because we can't evaluate x.
12570     // This will still allow us to detect an expression like (pre C++17)
12571     // "(x ? y += 1 : y += 2) = y".
12572     //
12573     // We don't wrap the visitation of the true and false expression with
12574     // SequencedSubexpression because we don't want to downgrade modifications
12575     // as side effect in the true and false expressions after the visition
12576     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
12577     // not warn between the two "y++", but we should warn between the "y++"
12578     // and the "y".
12579     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
12580     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
12581     SequenceTree::Seq OldRegion = Region;
12582 
12583     EvaluationTracker Eval(*this);
12584     {
12585       SequencedSubexpression Sequenced(*this);
12586       Region = ConditionRegion;
12587       Visit(CO->getCond());
12588     }
12589 
12590     // C++11 [expr.cond]p1:
12591     // [...] The first expression is contextually converted to bool (Clause 4).
12592     // It is evaluated and if it is true, the result of the conditional
12593     // expression is the value of the second expression, otherwise that of the
12594     // third expression. Only one of the second and third expressions is
12595     // evaluated. [...]
12596     bool EvalResult = false;
12597     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
12598     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
12599     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
12600     if (ShouldVisitTrueExpr) {
12601       Region = TrueRegion;
12602       Visit(CO->getTrueExpr());
12603     }
12604     if (ShouldVisitFalseExpr) {
12605       Region = FalseRegion;
12606       Visit(CO->getFalseExpr());
12607     }
12608 
12609     Region = OldRegion;
12610     Tree.merge(ConditionRegion);
12611     Tree.merge(TrueRegion);
12612     Tree.merge(FalseRegion);
12613   }
12614 
12615   void VisitCallExpr(const CallExpr *CE) {
12616     // C++11 [intro.execution]p15:
12617     //   When calling a function [...], every value computation and side effect
12618     //   associated with any argument expression, or with the postfix expression
12619     //   designating the called function, is sequenced before execution of every
12620     //   expression or statement in the body of the function [and thus before
12621     //   the value computation of its result].
12622     SequencedSubexpression Sequenced(*this);
12623     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(),
12624                                         [&] { Base::VisitCallExpr(CE); });
12625 
12626     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
12627   }
12628 
12629   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
12630     // This is a call, so all subexpressions are sequenced before the result.
12631     SequencedSubexpression Sequenced(*this);
12632 
12633     if (!CCE->isListInitialization())
12634       return VisitExpr(CCE);
12635 
12636     // In C++11, list initializations are sequenced.
12637     SmallVector<SequenceTree::Seq, 32> Elts;
12638     SequenceTree::Seq Parent = Region;
12639     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
12640                                               E = CCE->arg_end();
12641          I != E; ++I) {
12642       Region = Tree.allocate(Parent);
12643       Elts.push_back(Region);
12644       Visit(*I);
12645     }
12646 
12647     // Forget that the initializers are sequenced.
12648     Region = Parent;
12649     for (unsigned I = 0; I < Elts.size(); ++I)
12650       Tree.merge(Elts[I]);
12651   }
12652 
12653   void VisitInitListExpr(const InitListExpr *ILE) {
12654     if (!SemaRef.getLangOpts().CPlusPlus11)
12655       return VisitExpr(ILE);
12656 
12657     // In C++11, list initializations are sequenced.
12658     SmallVector<SequenceTree::Seq, 32> Elts;
12659     SequenceTree::Seq Parent = Region;
12660     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
12661       const Expr *E = ILE->getInit(I);
12662       if (!E)
12663         continue;
12664       Region = Tree.allocate(Parent);
12665       Elts.push_back(Region);
12666       Visit(E);
12667     }
12668 
12669     // Forget that the initializers are sequenced.
12670     Region = Parent;
12671     for (unsigned I = 0; I < Elts.size(); ++I)
12672       Tree.merge(Elts[I]);
12673   }
12674 };
12675 
12676 } // namespace
12677 
12678 void Sema::CheckUnsequencedOperations(const Expr *E) {
12679   SmallVector<const Expr *, 8> WorkList;
12680   WorkList.push_back(E);
12681   while (!WorkList.empty()) {
12682     const Expr *Item = WorkList.pop_back_val();
12683     SequenceChecker(*this, Item, WorkList);
12684   }
12685 }
12686 
12687 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
12688                               bool IsConstexpr) {
12689   llvm::SaveAndRestore<bool> ConstantContext(
12690       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
12691   CheckImplicitConversions(E, CheckLoc);
12692   if (!E->isInstantiationDependent())
12693     CheckUnsequencedOperations(E);
12694   if (!IsConstexpr && !E->isValueDependent())
12695     CheckForIntOverflow(E);
12696   DiagnoseMisalignedMembers();
12697 }
12698 
12699 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
12700                                        FieldDecl *BitField,
12701                                        Expr *Init) {
12702   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
12703 }
12704 
12705 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
12706                                          SourceLocation Loc) {
12707   if (!PType->isVariablyModifiedType())
12708     return;
12709   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
12710     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
12711     return;
12712   }
12713   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
12714     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
12715     return;
12716   }
12717   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
12718     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
12719     return;
12720   }
12721 
12722   const ArrayType *AT = S.Context.getAsArrayType(PType);
12723   if (!AT)
12724     return;
12725 
12726   if (AT->getSizeModifier() != ArrayType::Star) {
12727     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
12728     return;
12729   }
12730 
12731   S.Diag(Loc, diag::err_array_star_in_function_definition);
12732 }
12733 
12734 /// CheckParmsForFunctionDef - Check that the parameters of the given
12735 /// function are appropriate for the definition of a function. This
12736 /// takes care of any checks that cannot be performed on the
12737 /// declaration itself, e.g., that the types of each of the function
12738 /// parameters are complete.
12739 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
12740                                     bool CheckParameterNames) {
12741   bool HasInvalidParm = false;
12742   for (ParmVarDecl *Param : Parameters) {
12743     // C99 6.7.5.3p4: the parameters in a parameter type list in a
12744     // function declarator that is part of a function definition of
12745     // that function shall not have incomplete type.
12746     //
12747     // This is also C++ [dcl.fct]p6.
12748     if (!Param->isInvalidDecl() &&
12749         RequireCompleteType(Param->getLocation(), Param->getType(),
12750                             diag::err_typecheck_decl_incomplete_type)) {
12751       Param->setInvalidDecl();
12752       HasInvalidParm = true;
12753     }
12754 
12755     // C99 6.9.1p5: If the declarator includes a parameter type list, the
12756     // declaration of each parameter shall include an identifier.
12757     if (CheckParameterNames &&
12758         Param->getIdentifier() == nullptr &&
12759         !Param->isImplicit() &&
12760         !getLangOpts().CPlusPlus)
12761       Diag(Param->getLocation(), diag::err_parameter_name_omitted);
12762 
12763     // C99 6.7.5.3p12:
12764     //   If the function declarator is not part of a definition of that
12765     //   function, parameters may have incomplete type and may use the [*]
12766     //   notation in their sequences of declarator specifiers to specify
12767     //   variable length array types.
12768     QualType PType = Param->getOriginalType();
12769     // FIXME: This diagnostic should point the '[*]' if source-location
12770     // information is added for it.
12771     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
12772 
12773     // If the parameter is a c++ class type and it has to be destructed in the
12774     // callee function, declare the destructor so that it can be called by the
12775     // callee function. Do not perform any direct access check on the dtor here.
12776     if (!Param->isInvalidDecl()) {
12777       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
12778         if (!ClassDecl->isInvalidDecl() &&
12779             !ClassDecl->hasIrrelevantDestructor() &&
12780             !ClassDecl->isDependentContext() &&
12781             ClassDecl->isParamDestroyedInCallee()) {
12782           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
12783           MarkFunctionReferenced(Param->getLocation(), Destructor);
12784           DiagnoseUseOfDecl(Destructor, Param->getLocation());
12785         }
12786       }
12787     }
12788 
12789     // Parameters with the pass_object_size attribute only need to be marked
12790     // constant at function definitions. Because we lack information about
12791     // whether we're on a declaration or definition when we're instantiating the
12792     // attribute, we need to check for constness here.
12793     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
12794       if (!Param->getType().isConstQualified())
12795         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
12796             << Attr->getSpelling() << 1;
12797 
12798     // Check for parameter names shadowing fields from the class.
12799     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
12800       // The owning context for the parameter should be the function, but we
12801       // want to see if this function's declaration context is a record.
12802       DeclContext *DC = Param->getDeclContext();
12803       if (DC && DC->isFunctionOrMethod()) {
12804         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
12805           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
12806                                      RD, /*DeclIsField*/ false);
12807       }
12808     }
12809   }
12810 
12811   return HasInvalidParm;
12812 }
12813 
12814 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
12815 /// or MemberExpr.
12816 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
12817                               ASTContext &Context) {
12818   if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
12819     return Context.getDeclAlign(DRE->getDecl());
12820 
12821   if (const auto *ME = dyn_cast<MemberExpr>(E))
12822     return Context.getDeclAlign(ME->getMemberDecl());
12823 
12824   return TypeAlign;
12825 }
12826 
12827 /// CheckCastAlign - Implements -Wcast-align, which warns when a
12828 /// pointer cast increases the alignment requirements.
12829 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
12830   // This is actually a lot of work to potentially be doing on every
12831   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
12832   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
12833     return;
12834 
12835   // Ignore dependent types.
12836   if (T->isDependentType() || Op->getType()->isDependentType())
12837     return;
12838 
12839   // Require that the destination be a pointer type.
12840   const PointerType *DestPtr = T->getAs<PointerType>();
12841   if (!DestPtr) return;
12842 
12843   // If the destination has alignment 1, we're done.
12844   QualType DestPointee = DestPtr->getPointeeType();
12845   if (DestPointee->isIncompleteType()) return;
12846   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
12847   if (DestAlign.isOne()) return;
12848 
12849   // Require that the source be a pointer type.
12850   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
12851   if (!SrcPtr) return;
12852   QualType SrcPointee = SrcPtr->getPointeeType();
12853 
12854   // Whitelist casts from cv void*.  We already implicitly
12855   // whitelisted casts to cv void*, since they have alignment 1.
12856   // Also whitelist casts involving incomplete types, which implicitly
12857   // includes 'void'.
12858   if (SrcPointee->isIncompleteType()) return;
12859 
12860   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
12861 
12862   if (auto *CE = dyn_cast<CastExpr>(Op)) {
12863     if (CE->getCastKind() == CK_ArrayToPointerDecay)
12864       SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
12865   } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
12866     if (UO->getOpcode() == UO_AddrOf)
12867       SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
12868   }
12869 
12870   if (SrcAlign >= DestAlign) return;
12871 
12872   Diag(TRange.getBegin(), diag::warn_cast_align)
12873     << Op->getType() << T
12874     << static_cast<unsigned>(SrcAlign.getQuantity())
12875     << static_cast<unsigned>(DestAlign.getQuantity())
12876     << TRange << Op->getSourceRange();
12877 }
12878 
12879 /// Check whether this array fits the idiom of a size-one tail padded
12880 /// array member of a struct.
12881 ///
12882 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
12883 /// commonly used to emulate flexible arrays in C89 code.
12884 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
12885                                     const NamedDecl *ND) {
12886   if (Size != 1 || !ND) return false;
12887 
12888   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
12889   if (!FD) return false;
12890 
12891   // Don't consider sizes resulting from macro expansions or template argument
12892   // substitution to form C89 tail-padded arrays.
12893 
12894   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
12895   while (TInfo) {
12896     TypeLoc TL = TInfo->getTypeLoc();
12897     // Look through typedefs.
12898     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
12899       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
12900       TInfo = TDL->getTypeSourceInfo();
12901       continue;
12902     }
12903     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
12904       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
12905       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
12906         return false;
12907     }
12908     break;
12909   }
12910 
12911   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
12912   if (!RD) return false;
12913   if (RD->isUnion()) return false;
12914   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
12915     if (!CRD->isStandardLayout()) return false;
12916   }
12917 
12918   // See if this is the last field decl in the record.
12919   const Decl *D = FD;
12920   while ((D = D->getNextDeclInContext()))
12921     if (isa<FieldDecl>(D))
12922       return false;
12923   return true;
12924 }
12925 
12926 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
12927                             const ArraySubscriptExpr *ASE,
12928                             bool AllowOnePastEnd, bool IndexNegated) {
12929   // Already diagnosed by the constant evaluator.
12930   if (isConstantEvaluated())
12931     return;
12932 
12933   IndexExpr = IndexExpr->IgnoreParenImpCasts();
12934   if (IndexExpr->isValueDependent())
12935     return;
12936 
12937   const Type *EffectiveType =
12938       BaseExpr->getType()->getPointeeOrArrayElementType();
12939   BaseExpr = BaseExpr->IgnoreParenCasts();
12940   const ConstantArrayType *ArrayTy =
12941       Context.getAsConstantArrayType(BaseExpr->getType());
12942 
12943   if (!ArrayTy)
12944     return;
12945 
12946   const Type *BaseType = ArrayTy->getElementType().getTypePtr();
12947   if (EffectiveType->isDependentType() || BaseType->isDependentType())
12948     return;
12949 
12950   Expr::EvalResult Result;
12951   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
12952     return;
12953 
12954   llvm::APSInt index = Result.Val.getInt();
12955   if (IndexNegated)
12956     index = -index;
12957 
12958   const NamedDecl *ND = nullptr;
12959   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
12960     ND = DRE->getDecl();
12961   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
12962     ND = ME->getMemberDecl();
12963 
12964   if (index.isUnsigned() || !index.isNegative()) {
12965     // It is possible that the type of the base expression after
12966     // IgnoreParenCasts is incomplete, even though the type of the base
12967     // expression before IgnoreParenCasts is complete (see PR39746 for an
12968     // example). In this case we have no information about whether the array
12969     // access exceeds the array bounds. However we can still diagnose an array
12970     // access which precedes the array bounds.
12971     if (BaseType->isIncompleteType())
12972       return;
12973 
12974     llvm::APInt size = ArrayTy->getSize();
12975     if (!size.isStrictlyPositive())
12976       return;
12977 
12978     if (BaseType != EffectiveType) {
12979       // Make sure we're comparing apples to apples when comparing index to size
12980       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
12981       uint64_t array_typesize = Context.getTypeSize(BaseType);
12982       // Handle ptrarith_typesize being zero, such as when casting to void*
12983       if (!ptrarith_typesize) ptrarith_typesize = 1;
12984       if (ptrarith_typesize != array_typesize) {
12985         // There's a cast to a different size type involved
12986         uint64_t ratio = array_typesize / ptrarith_typesize;
12987         // TODO: Be smarter about handling cases where array_typesize is not a
12988         // multiple of ptrarith_typesize
12989         if (ptrarith_typesize * ratio == array_typesize)
12990           size *= llvm::APInt(size.getBitWidth(), ratio);
12991       }
12992     }
12993 
12994     if (size.getBitWidth() > index.getBitWidth())
12995       index = index.zext(size.getBitWidth());
12996     else if (size.getBitWidth() < index.getBitWidth())
12997       size = size.zext(index.getBitWidth());
12998 
12999     // For array subscripting the index must be less than size, but for pointer
13000     // arithmetic also allow the index (offset) to be equal to size since
13001     // computing the next address after the end of the array is legal and
13002     // commonly done e.g. in C++ iterators and range-based for loops.
13003     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
13004       return;
13005 
13006     // Also don't warn for arrays of size 1 which are members of some
13007     // structure. These are often used to approximate flexible arrays in C89
13008     // code.
13009     if (IsTailPaddedMemberArray(*this, size, ND))
13010       return;
13011 
13012     // Suppress the warning if the subscript expression (as identified by the
13013     // ']' location) and the index expression are both from macro expansions
13014     // within a system header.
13015     if (ASE) {
13016       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
13017           ASE->getRBracketLoc());
13018       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
13019         SourceLocation IndexLoc =
13020             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
13021         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
13022           return;
13023       }
13024     }
13025 
13026     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
13027     if (ASE)
13028       DiagID = diag::warn_array_index_exceeds_bounds;
13029 
13030     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
13031                         PDiag(DiagID) << index.toString(10, true)
13032                                       << size.toString(10, true)
13033                                       << (unsigned)size.getLimitedValue(~0U)
13034                                       << IndexExpr->getSourceRange());
13035   } else {
13036     unsigned DiagID = diag::warn_array_index_precedes_bounds;
13037     if (!ASE) {
13038       DiagID = diag::warn_ptr_arith_precedes_bounds;
13039       if (index.isNegative()) index = -index;
13040     }
13041 
13042     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
13043                         PDiag(DiagID) << index.toString(10, true)
13044                                       << IndexExpr->getSourceRange());
13045   }
13046 
13047   if (!ND) {
13048     // Try harder to find a NamedDecl to point at in the note.
13049     while (const ArraySubscriptExpr *ASE =
13050            dyn_cast<ArraySubscriptExpr>(BaseExpr))
13051       BaseExpr = ASE->getBase()->IgnoreParenCasts();
13052     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
13053       ND = DRE->getDecl();
13054     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
13055       ND = ME->getMemberDecl();
13056   }
13057 
13058   if (ND)
13059     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
13060                         PDiag(diag::note_array_declared_here)
13061                             << ND->getDeclName());
13062 }
13063 
13064 void Sema::CheckArrayAccess(const Expr *expr) {
13065   int AllowOnePastEnd = 0;
13066   while (expr) {
13067     expr = expr->IgnoreParenImpCasts();
13068     switch (expr->getStmtClass()) {
13069       case Stmt::ArraySubscriptExprClass: {
13070         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
13071         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
13072                          AllowOnePastEnd > 0);
13073         expr = ASE->getBase();
13074         break;
13075       }
13076       case Stmt::MemberExprClass: {
13077         expr = cast<MemberExpr>(expr)->getBase();
13078         break;
13079       }
13080       case Stmt::OMPArraySectionExprClass: {
13081         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
13082         if (ASE->getLowerBound())
13083           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
13084                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
13085         return;
13086       }
13087       case Stmt::UnaryOperatorClass: {
13088         // Only unwrap the * and & unary operators
13089         const UnaryOperator *UO = cast<UnaryOperator>(expr);
13090         expr = UO->getSubExpr();
13091         switch (UO->getOpcode()) {
13092           case UO_AddrOf:
13093             AllowOnePastEnd++;
13094             break;
13095           case UO_Deref:
13096             AllowOnePastEnd--;
13097             break;
13098           default:
13099             return;
13100         }
13101         break;
13102       }
13103       case Stmt::ConditionalOperatorClass: {
13104         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
13105         if (const Expr *lhs = cond->getLHS())
13106           CheckArrayAccess(lhs);
13107         if (const Expr *rhs = cond->getRHS())
13108           CheckArrayAccess(rhs);
13109         return;
13110       }
13111       case Stmt::CXXOperatorCallExprClass: {
13112         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
13113         for (const auto *Arg : OCE->arguments())
13114           CheckArrayAccess(Arg);
13115         return;
13116       }
13117       default:
13118         return;
13119     }
13120   }
13121 }
13122 
13123 //===--- CHECK: Objective-C retain cycles ----------------------------------//
13124 
13125 namespace {
13126 
13127 struct RetainCycleOwner {
13128   VarDecl *Variable = nullptr;
13129   SourceRange Range;
13130   SourceLocation Loc;
13131   bool Indirect = false;
13132 
13133   RetainCycleOwner() = default;
13134 
13135   void setLocsFrom(Expr *e) {
13136     Loc = e->getExprLoc();
13137     Range = e->getSourceRange();
13138   }
13139 };
13140 
13141 } // namespace
13142 
13143 /// Consider whether capturing the given variable can possibly lead to
13144 /// a retain cycle.
13145 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
13146   // In ARC, it's captured strongly iff the variable has __strong
13147   // lifetime.  In MRR, it's captured strongly if the variable is
13148   // __block and has an appropriate type.
13149   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
13150     return false;
13151 
13152   owner.Variable = var;
13153   if (ref)
13154     owner.setLocsFrom(ref);
13155   return true;
13156 }
13157 
13158 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
13159   while (true) {
13160     e = e->IgnoreParens();
13161     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
13162       switch (cast->getCastKind()) {
13163       case CK_BitCast:
13164       case CK_LValueBitCast:
13165       case CK_LValueToRValue:
13166       case CK_ARCReclaimReturnedObject:
13167         e = cast->getSubExpr();
13168         continue;
13169 
13170       default:
13171         return false;
13172       }
13173     }
13174 
13175     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
13176       ObjCIvarDecl *ivar = ref->getDecl();
13177       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
13178         return false;
13179 
13180       // Try to find a retain cycle in the base.
13181       if (!findRetainCycleOwner(S, ref->getBase(), owner))
13182         return false;
13183 
13184       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
13185       owner.Indirect = true;
13186       return true;
13187     }
13188 
13189     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
13190       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
13191       if (!var) return false;
13192       return considerVariable(var, ref, owner);
13193     }
13194 
13195     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
13196       if (member->isArrow()) return false;
13197 
13198       // Don't count this as an indirect ownership.
13199       e = member->getBase();
13200       continue;
13201     }
13202 
13203     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
13204       // Only pay attention to pseudo-objects on property references.
13205       ObjCPropertyRefExpr *pre
13206         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
13207                                               ->IgnoreParens());
13208       if (!pre) return false;
13209       if (pre->isImplicitProperty()) return false;
13210       ObjCPropertyDecl *property = pre->getExplicitProperty();
13211       if (!property->isRetaining() &&
13212           !(property->getPropertyIvarDecl() &&
13213             property->getPropertyIvarDecl()->getType()
13214               .getObjCLifetime() == Qualifiers::OCL_Strong))
13215           return false;
13216 
13217       owner.Indirect = true;
13218       if (pre->isSuperReceiver()) {
13219         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
13220         if (!owner.Variable)
13221           return false;
13222         owner.Loc = pre->getLocation();
13223         owner.Range = pre->getSourceRange();
13224         return true;
13225       }
13226       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
13227                               ->getSourceExpr());
13228       continue;
13229     }
13230 
13231     // Array ivars?
13232 
13233     return false;
13234   }
13235 }
13236 
13237 namespace {
13238 
13239   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
13240     ASTContext &Context;
13241     VarDecl *Variable;
13242     Expr *Capturer = nullptr;
13243     bool VarWillBeReased = false;
13244 
13245     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
13246         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
13247           Context(Context), Variable(variable) {}
13248 
13249     void VisitDeclRefExpr(DeclRefExpr *ref) {
13250       if (ref->getDecl() == Variable && !Capturer)
13251         Capturer = ref;
13252     }
13253 
13254     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
13255       if (Capturer) return;
13256       Visit(ref->getBase());
13257       if (Capturer && ref->isFreeIvar())
13258         Capturer = ref;
13259     }
13260 
13261     void VisitBlockExpr(BlockExpr *block) {
13262       // Look inside nested blocks
13263       if (block->getBlockDecl()->capturesVariable(Variable))
13264         Visit(block->getBlockDecl()->getBody());
13265     }
13266 
13267     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
13268       if (Capturer) return;
13269       if (OVE->getSourceExpr())
13270         Visit(OVE->getSourceExpr());
13271     }
13272 
13273     void VisitBinaryOperator(BinaryOperator *BinOp) {
13274       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
13275         return;
13276       Expr *LHS = BinOp->getLHS();
13277       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
13278         if (DRE->getDecl() != Variable)
13279           return;
13280         if (Expr *RHS = BinOp->getRHS()) {
13281           RHS = RHS->IgnoreParenCasts();
13282           llvm::APSInt Value;
13283           VarWillBeReased =
13284             (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
13285         }
13286       }
13287     }
13288   };
13289 
13290 } // namespace
13291 
13292 /// Check whether the given argument is a block which captures a
13293 /// variable.
13294 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
13295   assert(owner.Variable && owner.Loc.isValid());
13296 
13297   e = e->IgnoreParenCasts();
13298 
13299   // Look through [^{...} copy] and Block_copy(^{...}).
13300   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
13301     Selector Cmd = ME->getSelector();
13302     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
13303       e = ME->getInstanceReceiver();
13304       if (!e)
13305         return nullptr;
13306       e = e->IgnoreParenCasts();
13307     }
13308   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
13309     if (CE->getNumArgs() == 1) {
13310       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
13311       if (Fn) {
13312         const IdentifierInfo *FnI = Fn->getIdentifier();
13313         if (FnI && FnI->isStr("_Block_copy")) {
13314           e = CE->getArg(0)->IgnoreParenCasts();
13315         }
13316       }
13317     }
13318   }
13319 
13320   BlockExpr *block = dyn_cast<BlockExpr>(e);
13321   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
13322     return nullptr;
13323 
13324   FindCaptureVisitor visitor(S.Context, owner.Variable);
13325   visitor.Visit(block->getBlockDecl()->getBody());
13326   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
13327 }
13328 
13329 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
13330                                 RetainCycleOwner &owner) {
13331   assert(capturer);
13332   assert(owner.Variable && owner.Loc.isValid());
13333 
13334   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
13335     << owner.Variable << capturer->getSourceRange();
13336   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
13337     << owner.Indirect << owner.Range;
13338 }
13339 
13340 /// Check for a keyword selector that starts with the word 'add' or
13341 /// 'set'.
13342 static bool isSetterLikeSelector(Selector sel) {
13343   if (sel.isUnarySelector()) return false;
13344 
13345   StringRef str = sel.getNameForSlot(0);
13346   while (!str.empty() && str.front() == '_') str = str.substr(1);
13347   if (str.startswith("set"))
13348     str = str.substr(3);
13349   else if (str.startswith("add")) {
13350     // Specially whitelist 'addOperationWithBlock:'.
13351     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
13352       return false;
13353     str = str.substr(3);
13354   }
13355   else
13356     return false;
13357 
13358   if (str.empty()) return true;
13359   return !isLowercase(str.front());
13360 }
13361 
13362 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
13363                                                     ObjCMessageExpr *Message) {
13364   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
13365                                                 Message->getReceiverInterface(),
13366                                                 NSAPI::ClassId_NSMutableArray);
13367   if (!IsMutableArray) {
13368     return None;
13369   }
13370 
13371   Selector Sel = Message->getSelector();
13372 
13373   Optional<NSAPI::NSArrayMethodKind> MKOpt =
13374     S.NSAPIObj->getNSArrayMethodKind(Sel);
13375   if (!MKOpt) {
13376     return None;
13377   }
13378 
13379   NSAPI::NSArrayMethodKind MK = *MKOpt;
13380 
13381   switch (MK) {
13382     case NSAPI::NSMutableArr_addObject:
13383     case NSAPI::NSMutableArr_insertObjectAtIndex:
13384     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
13385       return 0;
13386     case NSAPI::NSMutableArr_replaceObjectAtIndex:
13387       return 1;
13388 
13389     default:
13390       return None;
13391   }
13392 
13393   return None;
13394 }
13395 
13396 static
13397 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
13398                                                   ObjCMessageExpr *Message) {
13399   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
13400                                             Message->getReceiverInterface(),
13401                                             NSAPI::ClassId_NSMutableDictionary);
13402   if (!IsMutableDictionary) {
13403     return None;
13404   }
13405 
13406   Selector Sel = Message->getSelector();
13407 
13408   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
13409     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
13410   if (!MKOpt) {
13411     return None;
13412   }
13413 
13414   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
13415 
13416   switch (MK) {
13417     case NSAPI::NSMutableDict_setObjectForKey:
13418     case NSAPI::NSMutableDict_setValueForKey:
13419     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
13420       return 0;
13421 
13422     default:
13423       return None;
13424   }
13425 
13426   return None;
13427 }
13428 
13429 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
13430   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
13431                                                 Message->getReceiverInterface(),
13432                                                 NSAPI::ClassId_NSMutableSet);
13433 
13434   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
13435                                             Message->getReceiverInterface(),
13436                                             NSAPI::ClassId_NSMutableOrderedSet);
13437   if (!IsMutableSet && !IsMutableOrderedSet) {
13438     return None;
13439   }
13440 
13441   Selector Sel = Message->getSelector();
13442 
13443   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
13444   if (!MKOpt) {
13445     return None;
13446   }
13447 
13448   NSAPI::NSSetMethodKind MK = *MKOpt;
13449 
13450   switch (MK) {
13451     case NSAPI::NSMutableSet_addObject:
13452     case NSAPI::NSOrderedSet_setObjectAtIndex:
13453     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
13454     case NSAPI::NSOrderedSet_insertObjectAtIndex:
13455       return 0;
13456     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
13457       return 1;
13458   }
13459 
13460   return None;
13461 }
13462 
13463 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
13464   if (!Message->isInstanceMessage()) {
13465     return;
13466   }
13467 
13468   Optional<int> ArgOpt;
13469 
13470   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
13471       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
13472       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
13473     return;
13474   }
13475 
13476   int ArgIndex = *ArgOpt;
13477 
13478   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
13479   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
13480     Arg = OE->getSourceExpr()->IgnoreImpCasts();
13481   }
13482 
13483   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
13484     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
13485       if (ArgRE->isObjCSelfExpr()) {
13486         Diag(Message->getSourceRange().getBegin(),
13487              diag::warn_objc_circular_container)
13488           << ArgRE->getDecl() << StringRef("'super'");
13489       }
13490     }
13491   } else {
13492     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
13493 
13494     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
13495       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
13496     }
13497 
13498     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
13499       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
13500         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
13501           ValueDecl *Decl = ReceiverRE->getDecl();
13502           Diag(Message->getSourceRange().getBegin(),
13503                diag::warn_objc_circular_container)
13504             << Decl << Decl;
13505           if (!ArgRE->isObjCSelfExpr()) {
13506             Diag(Decl->getLocation(),
13507                  diag::note_objc_circular_container_declared_here)
13508               << Decl;
13509           }
13510         }
13511       }
13512     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
13513       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
13514         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
13515           ObjCIvarDecl *Decl = IvarRE->getDecl();
13516           Diag(Message->getSourceRange().getBegin(),
13517                diag::warn_objc_circular_container)
13518             << Decl << Decl;
13519           Diag(Decl->getLocation(),
13520                diag::note_objc_circular_container_declared_here)
13521             << Decl;
13522         }
13523       }
13524     }
13525   }
13526 }
13527 
13528 /// Check a message send to see if it's likely to cause a retain cycle.
13529 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
13530   // Only check instance methods whose selector looks like a setter.
13531   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
13532     return;
13533 
13534   // Try to find a variable that the receiver is strongly owned by.
13535   RetainCycleOwner owner;
13536   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
13537     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
13538       return;
13539   } else {
13540     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
13541     owner.Variable = getCurMethodDecl()->getSelfDecl();
13542     owner.Loc = msg->getSuperLoc();
13543     owner.Range = msg->getSuperLoc();
13544   }
13545 
13546   // Check whether the receiver is captured by any of the arguments.
13547   const ObjCMethodDecl *MD = msg->getMethodDecl();
13548   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
13549     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
13550       // noescape blocks should not be retained by the method.
13551       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
13552         continue;
13553       return diagnoseRetainCycle(*this, capturer, owner);
13554     }
13555   }
13556 }
13557 
13558 /// Check a property assign to see if it's likely to cause a retain cycle.
13559 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
13560   RetainCycleOwner owner;
13561   if (!findRetainCycleOwner(*this, receiver, owner))
13562     return;
13563 
13564   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
13565     diagnoseRetainCycle(*this, capturer, owner);
13566 }
13567 
13568 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
13569   RetainCycleOwner Owner;
13570   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
13571     return;
13572 
13573   // Because we don't have an expression for the variable, we have to set the
13574   // location explicitly here.
13575   Owner.Loc = Var->getLocation();
13576   Owner.Range = Var->getSourceRange();
13577 
13578   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
13579     diagnoseRetainCycle(*this, Capturer, Owner);
13580 }
13581 
13582 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
13583                                      Expr *RHS, bool isProperty) {
13584   // Check if RHS is an Objective-C object literal, which also can get
13585   // immediately zapped in a weak reference.  Note that we explicitly
13586   // allow ObjCStringLiterals, since those are designed to never really die.
13587   RHS = RHS->IgnoreParenImpCasts();
13588 
13589   // This enum needs to match with the 'select' in
13590   // warn_objc_arc_literal_assign (off-by-1).
13591   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
13592   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
13593     return false;
13594 
13595   S.Diag(Loc, diag::warn_arc_literal_assign)
13596     << (unsigned) Kind
13597     << (isProperty ? 0 : 1)
13598     << RHS->getSourceRange();
13599 
13600   return true;
13601 }
13602 
13603 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
13604                                     Qualifiers::ObjCLifetime LT,
13605                                     Expr *RHS, bool isProperty) {
13606   // Strip off any implicit cast added to get to the one ARC-specific.
13607   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
13608     if (cast->getCastKind() == CK_ARCConsumeObject) {
13609       S.Diag(Loc, diag::warn_arc_retained_assign)
13610         << (LT == Qualifiers::OCL_ExplicitNone)
13611         << (isProperty ? 0 : 1)
13612         << RHS->getSourceRange();
13613       return true;
13614     }
13615     RHS = cast->getSubExpr();
13616   }
13617 
13618   if (LT == Qualifiers::OCL_Weak &&
13619       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
13620     return true;
13621 
13622   return false;
13623 }
13624 
13625 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
13626                               QualType LHS, Expr *RHS) {
13627   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
13628 
13629   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
13630     return false;
13631 
13632   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
13633     return true;
13634 
13635   return false;
13636 }
13637 
13638 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
13639                               Expr *LHS, Expr *RHS) {
13640   QualType LHSType;
13641   // PropertyRef on LHS type need be directly obtained from
13642   // its declaration as it has a PseudoType.
13643   ObjCPropertyRefExpr *PRE
13644     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
13645   if (PRE && !PRE->isImplicitProperty()) {
13646     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
13647     if (PD)
13648       LHSType = PD->getType();
13649   }
13650 
13651   if (LHSType.isNull())
13652     LHSType = LHS->getType();
13653 
13654   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
13655 
13656   if (LT == Qualifiers::OCL_Weak) {
13657     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
13658       getCurFunction()->markSafeWeakUse(LHS);
13659   }
13660 
13661   if (checkUnsafeAssigns(Loc, LHSType, RHS))
13662     return;
13663 
13664   // FIXME. Check for other life times.
13665   if (LT != Qualifiers::OCL_None)
13666     return;
13667 
13668   if (PRE) {
13669     if (PRE->isImplicitProperty())
13670       return;
13671     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
13672     if (!PD)
13673       return;
13674 
13675     unsigned Attributes = PD->getPropertyAttributes();
13676     if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
13677       // when 'assign' attribute was not explicitly specified
13678       // by user, ignore it and rely on property type itself
13679       // for lifetime info.
13680       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
13681       if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
13682           LHSType->isObjCRetainableType())
13683         return;
13684 
13685       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
13686         if (cast->getCastKind() == CK_ARCConsumeObject) {
13687           Diag(Loc, diag::warn_arc_retained_property_assign)
13688           << RHS->getSourceRange();
13689           return;
13690         }
13691         RHS = cast->getSubExpr();
13692       }
13693     }
13694     else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
13695       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
13696         return;
13697     }
13698   }
13699 }
13700 
13701 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
13702 
13703 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
13704                                         SourceLocation StmtLoc,
13705                                         const NullStmt *Body) {
13706   // Do not warn if the body is a macro that expands to nothing, e.g:
13707   //
13708   // #define CALL(x)
13709   // if (condition)
13710   //   CALL(0);
13711   if (Body->hasLeadingEmptyMacro())
13712     return false;
13713 
13714   // Get line numbers of statement and body.
13715   bool StmtLineInvalid;
13716   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
13717                                                       &StmtLineInvalid);
13718   if (StmtLineInvalid)
13719     return false;
13720 
13721   bool BodyLineInvalid;
13722   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
13723                                                       &BodyLineInvalid);
13724   if (BodyLineInvalid)
13725     return false;
13726 
13727   // Warn if null statement and body are on the same line.
13728   if (StmtLine != BodyLine)
13729     return false;
13730 
13731   return true;
13732 }
13733 
13734 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
13735                                  const Stmt *Body,
13736                                  unsigned DiagID) {
13737   // Since this is a syntactic check, don't emit diagnostic for template
13738   // instantiations, this just adds noise.
13739   if (CurrentInstantiationScope)
13740     return;
13741 
13742   // The body should be a null statement.
13743   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
13744   if (!NBody)
13745     return;
13746 
13747   // Do the usual checks.
13748   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
13749     return;
13750 
13751   Diag(NBody->getSemiLoc(), DiagID);
13752   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
13753 }
13754 
13755 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
13756                                  const Stmt *PossibleBody) {
13757   assert(!CurrentInstantiationScope); // Ensured by caller
13758 
13759   SourceLocation StmtLoc;
13760   const Stmt *Body;
13761   unsigned DiagID;
13762   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
13763     StmtLoc = FS->getRParenLoc();
13764     Body = FS->getBody();
13765     DiagID = diag::warn_empty_for_body;
13766   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
13767     StmtLoc = WS->getCond()->getSourceRange().getEnd();
13768     Body = WS->getBody();
13769     DiagID = diag::warn_empty_while_body;
13770   } else
13771     return; // Neither `for' nor `while'.
13772 
13773   // The body should be a null statement.
13774   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
13775   if (!NBody)
13776     return;
13777 
13778   // Skip expensive checks if diagnostic is disabled.
13779   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
13780     return;
13781 
13782   // Do the usual checks.
13783   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
13784     return;
13785 
13786   // `for(...);' and `while(...);' are popular idioms, so in order to keep
13787   // noise level low, emit diagnostics only if for/while is followed by a
13788   // CompoundStmt, e.g.:
13789   //    for (int i = 0; i < n; i++);
13790   //    {
13791   //      a(i);
13792   //    }
13793   // or if for/while is followed by a statement with more indentation
13794   // than for/while itself:
13795   //    for (int i = 0; i < n; i++);
13796   //      a(i);
13797   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
13798   if (!ProbableTypo) {
13799     bool BodyColInvalid;
13800     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
13801         PossibleBody->getBeginLoc(), &BodyColInvalid);
13802     if (BodyColInvalid)
13803       return;
13804 
13805     bool StmtColInvalid;
13806     unsigned StmtCol =
13807         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
13808     if (StmtColInvalid)
13809       return;
13810 
13811     if (BodyCol > StmtCol)
13812       ProbableTypo = true;
13813   }
13814 
13815   if (ProbableTypo) {
13816     Diag(NBody->getSemiLoc(), DiagID);
13817     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
13818   }
13819 }
13820 
13821 //===--- CHECK: Warn on self move with std::move. -------------------------===//
13822 
13823 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
13824 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
13825                              SourceLocation OpLoc) {
13826   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
13827     return;
13828 
13829   if (inTemplateInstantiation())
13830     return;
13831 
13832   // Strip parens and casts away.
13833   LHSExpr = LHSExpr->IgnoreParenImpCasts();
13834   RHSExpr = RHSExpr->IgnoreParenImpCasts();
13835 
13836   // Check for a call expression
13837   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
13838   if (!CE || CE->getNumArgs() != 1)
13839     return;
13840 
13841   // Check for a call to std::move
13842   if (!CE->isCallToStdMove())
13843     return;
13844 
13845   // Get argument from std::move
13846   RHSExpr = CE->getArg(0);
13847 
13848   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
13849   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
13850 
13851   // Two DeclRefExpr's, check that the decls are the same.
13852   if (LHSDeclRef && RHSDeclRef) {
13853     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
13854       return;
13855     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
13856         RHSDeclRef->getDecl()->getCanonicalDecl())
13857       return;
13858 
13859     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
13860                                         << LHSExpr->getSourceRange()
13861                                         << RHSExpr->getSourceRange();
13862     return;
13863   }
13864 
13865   // Member variables require a different approach to check for self moves.
13866   // MemberExpr's are the same if every nested MemberExpr refers to the same
13867   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
13868   // the base Expr's are CXXThisExpr's.
13869   const Expr *LHSBase = LHSExpr;
13870   const Expr *RHSBase = RHSExpr;
13871   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
13872   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
13873   if (!LHSME || !RHSME)
13874     return;
13875 
13876   while (LHSME && RHSME) {
13877     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
13878         RHSME->getMemberDecl()->getCanonicalDecl())
13879       return;
13880 
13881     LHSBase = LHSME->getBase();
13882     RHSBase = RHSME->getBase();
13883     LHSME = dyn_cast<MemberExpr>(LHSBase);
13884     RHSME = dyn_cast<MemberExpr>(RHSBase);
13885   }
13886 
13887   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
13888   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
13889   if (LHSDeclRef && RHSDeclRef) {
13890     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
13891       return;
13892     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
13893         RHSDeclRef->getDecl()->getCanonicalDecl())
13894       return;
13895 
13896     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
13897                                         << LHSExpr->getSourceRange()
13898                                         << RHSExpr->getSourceRange();
13899     return;
13900   }
13901 
13902   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
13903     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
13904                                         << LHSExpr->getSourceRange()
13905                                         << RHSExpr->getSourceRange();
13906 }
13907 
13908 //===--- Layout compatibility ----------------------------------------------//
13909 
13910 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
13911 
13912 /// Check if two enumeration types are layout-compatible.
13913 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
13914   // C++11 [dcl.enum] p8:
13915   // Two enumeration types are layout-compatible if they have the same
13916   // underlying type.
13917   return ED1->isComplete() && ED2->isComplete() &&
13918          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
13919 }
13920 
13921 /// Check if two fields are layout-compatible.
13922 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
13923                                FieldDecl *Field2) {
13924   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
13925     return false;
13926 
13927   if (Field1->isBitField() != Field2->isBitField())
13928     return false;
13929 
13930   if (Field1->isBitField()) {
13931     // Make sure that the bit-fields are the same length.
13932     unsigned Bits1 = Field1->getBitWidthValue(C);
13933     unsigned Bits2 = Field2->getBitWidthValue(C);
13934 
13935     if (Bits1 != Bits2)
13936       return false;
13937   }
13938 
13939   return true;
13940 }
13941 
13942 /// Check if two standard-layout structs are layout-compatible.
13943 /// (C++11 [class.mem] p17)
13944 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
13945                                      RecordDecl *RD2) {
13946   // If both records are C++ classes, check that base classes match.
13947   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
13948     // If one of records is a CXXRecordDecl we are in C++ mode,
13949     // thus the other one is a CXXRecordDecl, too.
13950     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
13951     // Check number of base classes.
13952     if (D1CXX->getNumBases() != D2CXX->getNumBases())
13953       return false;
13954 
13955     // Check the base classes.
13956     for (CXXRecordDecl::base_class_const_iterator
13957                Base1 = D1CXX->bases_begin(),
13958            BaseEnd1 = D1CXX->bases_end(),
13959               Base2 = D2CXX->bases_begin();
13960          Base1 != BaseEnd1;
13961          ++Base1, ++Base2) {
13962       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
13963         return false;
13964     }
13965   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
13966     // If only RD2 is a C++ class, it should have zero base classes.
13967     if (D2CXX->getNumBases() > 0)
13968       return false;
13969   }
13970 
13971   // Check the fields.
13972   RecordDecl::field_iterator Field2 = RD2->field_begin(),
13973                              Field2End = RD2->field_end(),
13974                              Field1 = RD1->field_begin(),
13975                              Field1End = RD1->field_end();
13976   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
13977     if (!isLayoutCompatible(C, *Field1, *Field2))
13978       return false;
13979   }
13980   if (Field1 != Field1End || Field2 != Field2End)
13981     return false;
13982 
13983   return true;
13984 }
13985 
13986 /// Check if two standard-layout unions are layout-compatible.
13987 /// (C++11 [class.mem] p18)
13988 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
13989                                     RecordDecl *RD2) {
13990   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
13991   for (auto *Field2 : RD2->fields())
13992     UnmatchedFields.insert(Field2);
13993 
13994   for (auto *Field1 : RD1->fields()) {
13995     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
13996         I = UnmatchedFields.begin(),
13997         E = UnmatchedFields.end();
13998 
13999     for ( ; I != E; ++I) {
14000       if (isLayoutCompatible(C, Field1, *I)) {
14001         bool Result = UnmatchedFields.erase(*I);
14002         (void) Result;
14003         assert(Result);
14004         break;
14005       }
14006     }
14007     if (I == E)
14008       return false;
14009   }
14010 
14011   return UnmatchedFields.empty();
14012 }
14013 
14014 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
14015                                RecordDecl *RD2) {
14016   if (RD1->isUnion() != RD2->isUnion())
14017     return false;
14018 
14019   if (RD1->isUnion())
14020     return isLayoutCompatibleUnion(C, RD1, RD2);
14021   else
14022     return isLayoutCompatibleStruct(C, RD1, RD2);
14023 }
14024 
14025 /// Check if two types are layout-compatible in C++11 sense.
14026 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
14027   if (T1.isNull() || T2.isNull())
14028     return false;
14029 
14030   // C++11 [basic.types] p11:
14031   // If two types T1 and T2 are the same type, then T1 and T2 are
14032   // layout-compatible types.
14033   if (C.hasSameType(T1, T2))
14034     return true;
14035 
14036   T1 = T1.getCanonicalType().getUnqualifiedType();
14037   T2 = T2.getCanonicalType().getUnqualifiedType();
14038 
14039   const Type::TypeClass TC1 = T1->getTypeClass();
14040   const Type::TypeClass TC2 = T2->getTypeClass();
14041 
14042   if (TC1 != TC2)
14043     return false;
14044 
14045   if (TC1 == Type::Enum) {
14046     return isLayoutCompatible(C,
14047                               cast<EnumType>(T1)->getDecl(),
14048                               cast<EnumType>(T2)->getDecl());
14049   } else if (TC1 == Type::Record) {
14050     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
14051       return false;
14052 
14053     return isLayoutCompatible(C,
14054                               cast<RecordType>(T1)->getDecl(),
14055                               cast<RecordType>(T2)->getDecl());
14056   }
14057 
14058   return false;
14059 }
14060 
14061 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
14062 
14063 /// Given a type tag expression find the type tag itself.
14064 ///
14065 /// \param TypeExpr Type tag expression, as it appears in user's code.
14066 ///
14067 /// \param VD Declaration of an identifier that appears in a type tag.
14068 ///
14069 /// \param MagicValue Type tag magic value.
14070 ///
14071 /// \param isConstantEvaluated wether the evalaution should be performed in
14072 
14073 /// constant context.
14074 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
14075                             const ValueDecl **VD, uint64_t *MagicValue,
14076                             bool isConstantEvaluated) {
14077   while(true) {
14078     if (!TypeExpr)
14079       return false;
14080 
14081     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
14082 
14083     switch (TypeExpr->getStmtClass()) {
14084     case Stmt::UnaryOperatorClass: {
14085       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
14086       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
14087         TypeExpr = UO->getSubExpr();
14088         continue;
14089       }
14090       return false;
14091     }
14092 
14093     case Stmt::DeclRefExprClass: {
14094       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
14095       *VD = DRE->getDecl();
14096       return true;
14097     }
14098 
14099     case Stmt::IntegerLiteralClass: {
14100       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
14101       llvm::APInt MagicValueAPInt = IL->getValue();
14102       if (MagicValueAPInt.getActiveBits() <= 64) {
14103         *MagicValue = MagicValueAPInt.getZExtValue();
14104         return true;
14105       } else
14106         return false;
14107     }
14108 
14109     case Stmt::BinaryConditionalOperatorClass:
14110     case Stmt::ConditionalOperatorClass: {
14111       const AbstractConditionalOperator *ACO =
14112           cast<AbstractConditionalOperator>(TypeExpr);
14113       bool Result;
14114       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
14115                                                      isConstantEvaluated)) {
14116         if (Result)
14117           TypeExpr = ACO->getTrueExpr();
14118         else
14119           TypeExpr = ACO->getFalseExpr();
14120         continue;
14121       }
14122       return false;
14123     }
14124 
14125     case Stmt::BinaryOperatorClass: {
14126       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
14127       if (BO->getOpcode() == BO_Comma) {
14128         TypeExpr = BO->getRHS();
14129         continue;
14130       }
14131       return false;
14132     }
14133 
14134     default:
14135       return false;
14136     }
14137   }
14138 }
14139 
14140 /// Retrieve the C type corresponding to type tag TypeExpr.
14141 ///
14142 /// \param TypeExpr Expression that specifies a type tag.
14143 ///
14144 /// \param MagicValues Registered magic values.
14145 ///
14146 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
14147 ///        kind.
14148 ///
14149 /// \param TypeInfo Information about the corresponding C type.
14150 ///
14151 /// \param isConstantEvaluated wether the evalaution should be performed in
14152 /// constant context.
14153 ///
14154 /// \returns true if the corresponding C type was found.
14155 static bool GetMatchingCType(
14156     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
14157     const ASTContext &Ctx,
14158     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
14159         *MagicValues,
14160     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
14161     bool isConstantEvaluated) {
14162   FoundWrongKind = false;
14163 
14164   // Variable declaration that has type_tag_for_datatype attribute.
14165   const ValueDecl *VD = nullptr;
14166 
14167   uint64_t MagicValue;
14168 
14169   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
14170     return false;
14171 
14172   if (VD) {
14173     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
14174       if (I->getArgumentKind() != ArgumentKind) {
14175         FoundWrongKind = true;
14176         return false;
14177       }
14178       TypeInfo.Type = I->getMatchingCType();
14179       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
14180       TypeInfo.MustBeNull = I->getMustBeNull();
14181       return true;
14182     }
14183     return false;
14184   }
14185 
14186   if (!MagicValues)
14187     return false;
14188 
14189   llvm::DenseMap<Sema::TypeTagMagicValue,
14190                  Sema::TypeTagData>::const_iterator I =
14191       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
14192   if (I == MagicValues->end())
14193     return false;
14194 
14195   TypeInfo = I->second;
14196   return true;
14197 }
14198 
14199 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
14200                                       uint64_t MagicValue, QualType Type,
14201                                       bool LayoutCompatible,
14202                                       bool MustBeNull) {
14203   if (!TypeTagForDatatypeMagicValues)
14204     TypeTagForDatatypeMagicValues.reset(
14205         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
14206 
14207   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
14208   (*TypeTagForDatatypeMagicValues)[Magic] =
14209       TypeTagData(Type, LayoutCompatible, MustBeNull);
14210 }
14211 
14212 static bool IsSameCharType(QualType T1, QualType T2) {
14213   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
14214   if (!BT1)
14215     return false;
14216 
14217   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
14218   if (!BT2)
14219     return false;
14220 
14221   BuiltinType::Kind T1Kind = BT1->getKind();
14222   BuiltinType::Kind T2Kind = BT2->getKind();
14223 
14224   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
14225          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
14226          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
14227          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
14228 }
14229 
14230 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
14231                                     const ArrayRef<const Expr *> ExprArgs,
14232                                     SourceLocation CallSiteLoc) {
14233   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
14234   bool IsPointerAttr = Attr->getIsPointer();
14235 
14236   // Retrieve the argument representing the 'type_tag'.
14237   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
14238   if (TypeTagIdxAST >= ExprArgs.size()) {
14239     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
14240         << 0 << Attr->getTypeTagIdx().getSourceIndex();
14241     return;
14242   }
14243   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
14244   bool FoundWrongKind;
14245   TypeTagData TypeInfo;
14246   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
14247                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
14248                         TypeInfo, isConstantEvaluated())) {
14249     if (FoundWrongKind)
14250       Diag(TypeTagExpr->getExprLoc(),
14251            diag::warn_type_tag_for_datatype_wrong_kind)
14252         << TypeTagExpr->getSourceRange();
14253     return;
14254   }
14255 
14256   // Retrieve the argument representing the 'arg_idx'.
14257   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
14258   if (ArgumentIdxAST >= ExprArgs.size()) {
14259     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
14260         << 1 << Attr->getArgumentIdx().getSourceIndex();
14261     return;
14262   }
14263   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
14264   if (IsPointerAttr) {
14265     // Skip implicit cast of pointer to `void *' (as a function argument).
14266     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
14267       if (ICE->getType()->isVoidPointerType() &&
14268           ICE->getCastKind() == CK_BitCast)
14269         ArgumentExpr = ICE->getSubExpr();
14270   }
14271   QualType ArgumentType = ArgumentExpr->getType();
14272 
14273   // Passing a `void*' pointer shouldn't trigger a warning.
14274   if (IsPointerAttr && ArgumentType->isVoidPointerType())
14275     return;
14276 
14277   if (TypeInfo.MustBeNull) {
14278     // Type tag with matching void type requires a null pointer.
14279     if (!ArgumentExpr->isNullPointerConstant(Context,
14280                                              Expr::NPC_ValueDependentIsNotNull)) {
14281       Diag(ArgumentExpr->getExprLoc(),
14282            diag::warn_type_safety_null_pointer_required)
14283           << ArgumentKind->getName()
14284           << ArgumentExpr->getSourceRange()
14285           << TypeTagExpr->getSourceRange();
14286     }
14287     return;
14288   }
14289 
14290   QualType RequiredType = TypeInfo.Type;
14291   if (IsPointerAttr)
14292     RequiredType = Context.getPointerType(RequiredType);
14293 
14294   bool mismatch = false;
14295   if (!TypeInfo.LayoutCompatible) {
14296     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
14297 
14298     // C++11 [basic.fundamental] p1:
14299     // Plain char, signed char, and unsigned char are three distinct types.
14300     //
14301     // But we treat plain `char' as equivalent to `signed char' or `unsigned
14302     // char' depending on the current char signedness mode.
14303     if (mismatch)
14304       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
14305                                            RequiredType->getPointeeType())) ||
14306           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
14307         mismatch = false;
14308   } else
14309     if (IsPointerAttr)
14310       mismatch = !isLayoutCompatible(Context,
14311                                      ArgumentType->getPointeeType(),
14312                                      RequiredType->getPointeeType());
14313     else
14314       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
14315 
14316   if (mismatch)
14317     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
14318         << ArgumentType << ArgumentKind
14319         << TypeInfo.LayoutCompatible << RequiredType
14320         << ArgumentExpr->getSourceRange()
14321         << TypeTagExpr->getSourceRange();
14322 }
14323 
14324 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
14325                                          CharUnits Alignment) {
14326   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
14327 }
14328 
14329 void Sema::DiagnoseMisalignedMembers() {
14330   for (MisalignedMember &m : MisalignedMembers) {
14331     const NamedDecl *ND = m.RD;
14332     if (ND->getName().empty()) {
14333       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
14334         ND = TD;
14335     }
14336     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
14337         << m.MD << ND << m.E->getSourceRange();
14338   }
14339   MisalignedMembers.clear();
14340 }
14341 
14342 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
14343   E = E->IgnoreParens();
14344   if (!T->isPointerType() && !T->isIntegerType())
14345     return;
14346   if (isa<UnaryOperator>(E) &&
14347       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
14348     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
14349     if (isa<MemberExpr>(Op)) {
14350       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
14351       if (MA != MisalignedMembers.end() &&
14352           (T->isIntegerType() ||
14353            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
14354                                    Context.getTypeAlignInChars(
14355                                        T->getPointeeType()) <= MA->Alignment))))
14356         MisalignedMembers.erase(MA);
14357     }
14358   }
14359 }
14360 
14361 void Sema::RefersToMemberWithReducedAlignment(
14362     Expr *E,
14363     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
14364         Action) {
14365   const auto *ME = dyn_cast<MemberExpr>(E);
14366   if (!ME)
14367     return;
14368 
14369   // No need to check expressions with an __unaligned-qualified type.
14370   if (E->getType().getQualifiers().hasUnaligned())
14371     return;
14372 
14373   // For a chain of MemberExpr like "a.b.c.d" this list
14374   // will keep FieldDecl's like [d, c, b].
14375   SmallVector<FieldDecl *, 4> ReverseMemberChain;
14376   const MemberExpr *TopME = nullptr;
14377   bool AnyIsPacked = false;
14378   do {
14379     QualType BaseType = ME->getBase()->getType();
14380     if (BaseType->isDependentType())
14381       return;
14382     if (ME->isArrow())
14383       BaseType = BaseType->getPointeeType();
14384     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
14385     if (RD->isInvalidDecl())
14386       return;
14387 
14388     ValueDecl *MD = ME->getMemberDecl();
14389     auto *FD = dyn_cast<FieldDecl>(MD);
14390     // We do not care about non-data members.
14391     if (!FD || FD->isInvalidDecl())
14392       return;
14393 
14394     AnyIsPacked =
14395         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
14396     ReverseMemberChain.push_back(FD);
14397 
14398     TopME = ME;
14399     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
14400   } while (ME);
14401   assert(TopME && "We did not compute a topmost MemberExpr!");
14402 
14403   // Not the scope of this diagnostic.
14404   if (!AnyIsPacked)
14405     return;
14406 
14407   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
14408   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
14409   // TODO: The innermost base of the member expression may be too complicated.
14410   // For now, just disregard these cases. This is left for future
14411   // improvement.
14412   if (!DRE && !isa<CXXThisExpr>(TopBase))
14413       return;
14414 
14415   // Alignment expected by the whole expression.
14416   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
14417 
14418   // No need to do anything else with this case.
14419   if (ExpectedAlignment.isOne())
14420     return;
14421 
14422   // Synthesize offset of the whole access.
14423   CharUnits Offset;
14424   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
14425        I++) {
14426     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
14427   }
14428 
14429   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
14430   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
14431       ReverseMemberChain.back()->getParent()->getTypeForDecl());
14432 
14433   // The base expression of the innermost MemberExpr may give
14434   // stronger guarantees than the class containing the member.
14435   if (DRE && !TopME->isArrow()) {
14436     const ValueDecl *VD = DRE->getDecl();
14437     if (!VD->getType()->isReferenceType())
14438       CompleteObjectAlignment =
14439           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
14440   }
14441 
14442   // Check if the synthesized offset fulfills the alignment.
14443   if (Offset % ExpectedAlignment != 0 ||
14444       // It may fulfill the offset it but the effective alignment may still be
14445       // lower than the expected expression alignment.
14446       CompleteObjectAlignment < ExpectedAlignment) {
14447     // If this happens, we want to determine a sensible culprit of this.
14448     // Intuitively, watching the chain of member expressions from right to
14449     // left, we start with the required alignment (as required by the field
14450     // type) but some packed attribute in that chain has reduced the alignment.
14451     // It may happen that another packed structure increases it again. But if
14452     // we are here such increase has not been enough. So pointing the first
14453     // FieldDecl that either is packed or else its RecordDecl is,
14454     // seems reasonable.
14455     FieldDecl *FD = nullptr;
14456     CharUnits Alignment;
14457     for (FieldDecl *FDI : ReverseMemberChain) {
14458       if (FDI->hasAttr<PackedAttr>() ||
14459           FDI->getParent()->hasAttr<PackedAttr>()) {
14460         FD = FDI;
14461         Alignment = std::min(
14462             Context.getTypeAlignInChars(FD->getType()),
14463             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
14464         break;
14465       }
14466     }
14467     assert(FD && "We did not find a packed FieldDecl!");
14468     Action(E, FD->getParent(), FD, Alignment);
14469   }
14470 }
14471 
14472 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
14473   using namespace std::placeholders;
14474 
14475   RefersToMemberWithReducedAlignment(
14476       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
14477                      _2, _3, _4));
14478 }
14479