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/raw_ostream.h"
88 #include <algorithm>
89 #include <cassert>
90 #include <cstddef>
91 #include <cstdint>
92 #include <functional>
93 #include <limits>
94 #include <string>
95 #include <tuple>
96 #include <utility>
97 
98 using namespace clang;
99 using namespace sema;
100 
101 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
102                                                     unsigned ByteNo) const {
103   return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
104                                Context.getTargetInfo());
105 }
106 
107 /// Checks that a call expression's argument count is the desired number.
108 /// This is useful when doing custom type-checking.  Returns true on error.
109 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
110   unsigned argCount = call->getNumArgs();
111   if (argCount == desiredArgCount) return false;
112 
113   if (argCount < desiredArgCount)
114     return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args)
115            << 0 /*function call*/ << desiredArgCount << argCount
116            << call->getSourceRange();
117 
118   // Highlight all the excess arguments.
119   SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(),
120                     call->getArg(argCount - 1)->getEndLoc());
121 
122   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
123     << 0 /*function call*/ << desiredArgCount << argCount
124     << call->getArg(1)->getSourceRange();
125 }
126 
127 /// Check that the first argument to __builtin_annotation is an integer
128 /// and the second argument is a non-wide string literal.
129 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
130   if (checkArgCount(S, TheCall, 2))
131     return true;
132 
133   // First argument should be an integer.
134   Expr *ValArg = TheCall->getArg(0);
135   QualType Ty = ValArg->getType();
136   if (!Ty->isIntegerType()) {
137     S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
138         << ValArg->getSourceRange();
139     return true;
140   }
141 
142   // Second argument should be a constant string.
143   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
144   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
145   if (!Literal || !Literal->isAscii()) {
146     S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
147         << StrArg->getSourceRange();
148     return true;
149   }
150 
151   TheCall->setType(Ty);
152   return false;
153 }
154 
155 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
156   // We need at least one argument.
157   if (TheCall->getNumArgs() < 1) {
158     S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
159         << 0 << 1 << TheCall->getNumArgs()
160         << TheCall->getCallee()->getSourceRange();
161     return true;
162   }
163 
164   // All arguments should be wide string literals.
165   for (Expr *Arg : TheCall->arguments()) {
166     auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
167     if (!Literal || !Literal->isWide()) {
168       S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
169           << Arg->getSourceRange();
170       return true;
171     }
172   }
173 
174   return false;
175 }
176 
177 /// Check that the argument to __builtin_addressof is a glvalue, and set the
178 /// result type to the corresponding pointer type.
179 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
180   if (checkArgCount(S, TheCall, 1))
181     return true;
182 
183   ExprResult Arg(TheCall->getArg(0));
184   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
185   if (ResultType.isNull())
186     return true;
187 
188   TheCall->setArg(0, Arg.get());
189   TheCall->setType(ResultType);
190   return false;
191 }
192 
193 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
194   if (checkArgCount(S, TheCall, 3))
195     return true;
196 
197   // First two arguments should be integers.
198   for (unsigned I = 0; I < 2; ++I) {
199     ExprResult Arg = TheCall->getArg(I);
200     QualType Ty = Arg.get()->getType();
201     if (!Ty->isIntegerType()) {
202       S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
203           << Ty << Arg.get()->getSourceRange();
204       return true;
205     }
206     InitializedEntity Entity = InitializedEntity::InitializeParameter(
207         S.getASTContext(), Ty, /*consume*/ false);
208     Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
209     if (Arg.isInvalid())
210       return true;
211     TheCall->setArg(I, Arg.get());
212   }
213 
214   // Third argument should be a pointer to a non-const integer.
215   // IRGen correctly handles volatile, restrict, and address spaces, and
216   // the other qualifiers aren't possible.
217   {
218     ExprResult Arg = TheCall->getArg(2);
219     QualType Ty = Arg.get()->getType();
220     const auto *PtrTy = Ty->getAs<PointerType>();
221     if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
222           !PtrTy->getPointeeType().isConstQualified())) {
223       S.Diag(Arg.get()->getBeginLoc(),
224              diag::err_overflow_builtin_must_be_ptr_int)
225           << Ty << Arg.get()->getSourceRange();
226       return true;
227     }
228     InitializedEntity Entity = InitializedEntity::InitializeParameter(
229         S.getASTContext(), Ty, /*consume*/ false);
230     Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
231     if (Arg.isInvalid())
232       return true;
233     TheCall->setArg(2, Arg.get());
234   }
235   return false;
236 }
237 
238 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
239   if (checkArgCount(S, BuiltinCall, 2))
240     return true;
241 
242   SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
243   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
244   Expr *Call = BuiltinCall->getArg(0);
245   Expr *Chain = BuiltinCall->getArg(1);
246 
247   if (Call->getStmtClass() != Stmt::CallExprClass) {
248     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
249         << Call->getSourceRange();
250     return true;
251   }
252 
253   auto CE = cast<CallExpr>(Call);
254   if (CE->getCallee()->getType()->isBlockPointerType()) {
255     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
256         << Call->getSourceRange();
257     return true;
258   }
259 
260   const Decl *TargetDecl = CE->getCalleeDecl();
261   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
262     if (FD->getBuiltinID()) {
263       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
264           << Call->getSourceRange();
265       return true;
266     }
267 
268   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
269     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
270         << Call->getSourceRange();
271     return true;
272   }
273 
274   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
275   if (ChainResult.isInvalid())
276     return true;
277   if (!ChainResult.get()->getType()->isPointerType()) {
278     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
279         << Chain->getSourceRange();
280     return true;
281   }
282 
283   QualType ReturnTy = CE->getCallReturnType(S.Context);
284   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
285   QualType BuiltinTy = S.Context.getFunctionType(
286       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
287   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
288 
289   Builtin =
290       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
291 
292   BuiltinCall->setType(CE->getType());
293   BuiltinCall->setValueKind(CE->getValueKind());
294   BuiltinCall->setObjectKind(CE->getObjectKind());
295   BuiltinCall->setCallee(Builtin);
296   BuiltinCall->setArg(1, ChainResult.get());
297 
298   return false;
299 }
300 
301 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a
302 /// __builtin_*_chk function, then use the object size argument specified in the
303 /// source. Otherwise, infer the object size using __builtin_object_size.
304 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
305                                                CallExpr *TheCall) {
306   // FIXME: There are some more useful checks we could be doing here:
307   //  - Analyze the format string of sprintf to see how much of buffer is used.
308   //  - Evaluate strlen of strcpy arguments, use as object size.
309 
310   if (TheCall->isValueDependent() || TheCall->isTypeDependent())
311     return;
312 
313   unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
314   if (!BuiltinID)
315     return;
316 
317   unsigned DiagID = 0;
318   bool IsChkVariant = false;
319   unsigned SizeIndex, ObjectIndex;
320   switch (BuiltinID) {
321   default:
322     return;
323   case Builtin::BI__builtin___memcpy_chk:
324   case Builtin::BI__builtin___memmove_chk:
325   case Builtin::BI__builtin___memset_chk:
326   case Builtin::BI__builtin___strlcat_chk:
327   case Builtin::BI__builtin___strlcpy_chk:
328   case Builtin::BI__builtin___strncat_chk:
329   case Builtin::BI__builtin___strncpy_chk:
330   case Builtin::BI__builtin___stpncpy_chk:
331   case Builtin::BI__builtin___memccpy_chk: {
332     DiagID = diag::warn_builtin_chk_overflow;
333     IsChkVariant = true;
334     SizeIndex = TheCall->getNumArgs() - 2;
335     ObjectIndex = TheCall->getNumArgs() - 1;
336     break;
337   }
338 
339   case Builtin::BI__builtin___snprintf_chk:
340   case Builtin::BI__builtin___vsnprintf_chk: {
341     DiagID = diag::warn_builtin_chk_overflow;
342     IsChkVariant = true;
343     SizeIndex = 1;
344     ObjectIndex = 3;
345     break;
346   }
347 
348   case Builtin::BIstrncat:
349   case Builtin::BI__builtin_strncat:
350   case Builtin::BIstrncpy:
351   case Builtin::BI__builtin_strncpy:
352   case Builtin::BIstpncpy:
353   case Builtin::BI__builtin_stpncpy: {
354     // Whether these functions overflow depends on the runtime strlen of the
355     // string, not just the buffer size, so emitting the "always overflow"
356     // diagnostic isn't quite right. We should still diagnose passing a buffer
357     // size larger than the destination buffer though; this is a runtime abort
358     // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
359     DiagID = diag::warn_fortify_source_size_mismatch;
360     SizeIndex = TheCall->getNumArgs() - 1;
361     ObjectIndex = 0;
362     break;
363   }
364 
365   case Builtin::BImemcpy:
366   case Builtin::BI__builtin_memcpy:
367   case Builtin::BImemmove:
368   case Builtin::BI__builtin_memmove:
369   case Builtin::BImemset:
370   case Builtin::BI__builtin_memset: {
371     DiagID = diag::warn_fortify_source_overflow;
372     SizeIndex = TheCall->getNumArgs() - 1;
373     ObjectIndex = 0;
374     break;
375   }
376   case Builtin::BIsnprintf:
377   case Builtin::BI__builtin_snprintf:
378   case Builtin::BIvsnprintf:
379   case Builtin::BI__builtin_vsnprintf: {
380     DiagID = diag::warn_fortify_source_size_mismatch;
381     SizeIndex = 1;
382     ObjectIndex = 0;
383     break;
384   }
385   }
386 
387   llvm::APSInt ObjectSize;
388   // For __builtin___*_chk, the object size is explicitly provided by the caller
389   // (usually using __builtin_object_size). Use that value to check this call.
390   if (IsChkVariant) {
391     Expr::EvalResult Result;
392     Expr *SizeArg = TheCall->getArg(ObjectIndex);
393     if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
394       return;
395     ObjectSize = Result.Val.getInt();
396 
397   // Otherwise, try to evaluate an imaginary call to __builtin_object_size.
398   } else {
399     // If the parameter has a pass_object_size attribute, then we should use its
400     // (potentially) more strict checking mode. Otherwise, conservatively assume
401     // type 0.
402     int BOSType = 0;
403     if (const auto *POS =
404             FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>())
405       BOSType = POS->getType();
406 
407     Expr *ObjArg = TheCall->getArg(ObjectIndex);
408     uint64_t Result;
409     if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
410       return;
411     // Get the object size in the target's size_t width.
412     const TargetInfo &TI = getASTContext().getTargetInfo();
413     unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
414     ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
415   }
416 
417   // Evaluate the number of bytes of the object that this call will use.
418   Expr::EvalResult Result;
419   Expr *UsedSizeArg = TheCall->getArg(SizeIndex);
420   if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext()))
421     return;
422   llvm::APSInt UsedSize = Result.Val.getInt();
423 
424   if (UsedSize.ule(ObjectSize))
425     return;
426 
427   StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
428   // Skim off the details of whichever builtin was called to produce a better
429   // diagnostic, as it's unlikley that the user wrote the __builtin explicitly.
430   if (IsChkVariant) {
431     FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
432     FunctionName = FunctionName.drop_back(std::strlen("_chk"));
433   } else if (FunctionName.startswith("__builtin_")) {
434     FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
435   }
436 
437   DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
438                       PDiag(DiagID)
439                           << FunctionName << ObjectSize.toString(/*Radix=*/10)
440                           << UsedSize.toString(/*Radix=*/10));
441 }
442 
443 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
444                                      Scope::ScopeFlags NeededScopeFlags,
445                                      unsigned DiagID) {
446   // Scopes aren't available during instantiation. Fortunately, builtin
447   // functions cannot be template args so they cannot be formed through template
448   // instantiation. Therefore checking once during the parse is sufficient.
449   if (SemaRef.inTemplateInstantiation())
450     return false;
451 
452   Scope *S = SemaRef.getCurScope();
453   while (S && !S->isSEHExceptScope())
454     S = S->getParent();
455   if (!S || !(S->getFlags() & NeededScopeFlags)) {
456     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
457     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
458         << DRE->getDecl()->getIdentifier();
459     return true;
460   }
461 
462   return false;
463 }
464 
465 static inline bool isBlockPointer(Expr *Arg) {
466   return Arg->getType()->isBlockPointerType();
467 }
468 
469 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
470 /// void*, which is a requirement of device side enqueue.
471 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
472   const BlockPointerType *BPT =
473       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
474   ArrayRef<QualType> Params =
475       BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
476   unsigned ArgCounter = 0;
477   bool IllegalParams = false;
478   // Iterate through the block parameters until either one is found that is not
479   // a local void*, or the block is valid.
480   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
481        I != E; ++I, ++ArgCounter) {
482     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
483         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
484             LangAS::opencl_local) {
485       // Get the location of the error. If a block literal has been passed
486       // (BlockExpr) then we can point straight to the offending argument,
487       // else we just point to the variable reference.
488       SourceLocation ErrorLoc;
489       if (isa<BlockExpr>(BlockArg)) {
490         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
491         ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
492       } else if (isa<DeclRefExpr>(BlockArg)) {
493         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
494       }
495       S.Diag(ErrorLoc,
496              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
497       IllegalParams = true;
498     }
499   }
500 
501   return IllegalParams;
502 }
503 
504 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
505   if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
506     S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
507         << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
508     return true;
509   }
510   return false;
511 }
512 
513 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
514   if (checkArgCount(S, TheCall, 2))
515     return true;
516 
517   if (checkOpenCLSubgroupExt(S, TheCall))
518     return true;
519 
520   // First argument is an ndrange_t type.
521   Expr *NDRangeArg = TheCall->getArg(0);
522   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
523     S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
524         << TheCall->getDirectCallee() << "'ndrange_t'";
525     return true;
526   }
527 
528   Expr *BlockArg = TheCall->getArg(1);
529   if (!isBlockPointer(BlockArg)) {
530     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
531         << TheCall->getDirectCallee() << "block";
532     return true;
533   }
534   return checkOpenCLBlockArgs(S, BlockArg);
535 }
536 
537 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
538 /// get_kernel_work_group_size
539 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
540 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
541   if (checkArgCount(S, TheCall, 1))
542     return true;
543 
544   Expr *BlockArg = TheCall->getArg(0);
545   if (!isBlockPointer(BlockArg)) {
546     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
547         << TheCall->getDirectCallee() << "block";
548     return true;
549   }
550   return checkOpenCLBlockArgs(S, BlockArg);
551 }
552 
553 /// Diagnose integer type and any valid implicit conversion to it.
554 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
555                                       const QualType &IntType);
556 
557 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
558                                             unsigned Start, unsigned End) {
559   bool IllegalParams = false;
560   for (unsigned I = Start; I <= End; ++I)
561     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
562                                               S.Context.getSizeType());
563   return IllegalParams;
564 }
565 
566 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
567 /// 'local void*' parameter of passed block.
568 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
569                                            Expr *BlockArg,
570                                            unsigned NumNonVarArgs) {
571   const BlockPointerType *BPT =
572       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
573   unsigned NumBlockParams =
574       BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
575   unsigned TotalNumArgs = TheCall->getNumArgs();
576 
577   // For each argument passed to the block, a corresponding uint needs to
578   // be passed to describe the size of the local memory.
579   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
580     S.Diag(TheCall->getBeginLoc(),
581            diag::err_opencl_enqueue_kernel_local_size_args);
582     return true;
583   }
584 
585   // Check that the sizes of the local memory are specified by integers.
586   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
587                                          TotalNumArgs - 1);
588 }
589 
590 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
591 /// overload formats specified in Table 6.13.17.1.
592 /// int enqueue_kernel(queue_t queue,
593 ///                    kernel_enqueue_flags_t flags,
594 ///                    const ndrange_t ndrange,
595 ///                    void (^block)(void))
596 /// int enqueue_kernel(queue_t queue,
597 ///                    kernel_enqueue_flags_t flags,
598 ///                    const ndrange_t ndrange,
599 ///                    uint num_events_in_wait_list,
600 ///                    clk_event_t *event_wait_list,
601 ///                    clk_event_t *event_ret,
602 ///                    void (^block)(void))
603 /// int enqueue_kernel(queue_t queue,
604 ///                    kernel_enqueue_flags_t flags,
605 ///                    const ndrange_t ndrange,
606 ///                    void (^block)(local void*, ...),
607 ///                    uint size0, ...)
608 /// int enqueue_kernel(queue_t queue,
609 ///                    kernel_enqueue_flags_t flags,
610 ///                    const ndrange_t ndrange,
611 ///                    uint num_events_in_wait_list,
612 ///                    clk_event_t *event_wait_list,
613 ///                    clk_event_t *event_ret,
614 ///                    void (^block)(local void*, ...),
615 ///                    uint size0, ...)
616 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
617   unsigned NumArgs = TheCall->getNumArgs();
618 
619   if (NumArgs < 4) {
620     S.Diag(TheCall->getBeginLoc(), diag::err_typecheck_call_too_few_args);
621     return true;
622   }
623 
624   Expr *Arg0 = TheCall->getArg(0);
625   Expr *Arg1 = TheCall->getArg(1);
626   Expr *Arg2 = TheCall->getArg(2);
627   Expr *Arg3 = TheCall->getArg(3);
628 
629   // First argument always needs to be a queue_t type.
630   if (!Arg0->getType()->isQueueT()) {
631     S.Diag(TheCall->getArg(0)->getBeginLoc(),
632            diag::err_opencl_builtin_expected_type)
633         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
634     return true;
635   }
636 
637   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
638   if (!Arg1->getType()->isIntegerType()) {
639     S.Diag(TheCall->getArg(1)->getBeginLoc(),
640            diag::err_opencl_builtin_expected_type)
641         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
642     return true;
643   }
644 
645   // Third argument is always an ndrange_t type.
646   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
647     S.Diag(TheCall->getArg(2)->getBeginLoc(),
648            diag::err_opencl_builtin_expected_type)
649         << TheCall->getDirectCallee() << "'ndrange_t'";
650     return true;
651   }
652 
653   // With four arguments, there is only one form that the function could be
654   // called in: no events and no variable arguments.
655   if (NumArgs == 4) {
656     // check that the last argument is the right block type.
657     if (!isBlockPointer(Arg3)) {
658       S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
659           << TheCall->getDirectCallee() << "block";
660       return true;
661     }
662     // we have a block type, check the prototype
663     const BlockPointerType *BPT =
664         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
665     if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
666       S.Diag(Arg3->getBeginLoc(),
667              diag::err_opencl_enqueue_kernel_blocks_no_args);
668       return true;
669     }
670     return false;
671   }
672   // we can have block + varargs.
673   if (isBlockPointer(Arg3))
674     return (checkOpenCLBlockArgs(S, Arg3) ||
675             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
676   // last two cases with either exactly 7 args or 7 args and varargs.
677   if (NumArgs >= 7) {
678     // check common block argument.
679     Expr *Arg6 = TheCall->getArg(6);
680     if (!isBlockPointer(Arg6)) {
681       S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
682           << TheCall->getDirectCallee() << "block";
683       return true;
684     }
685     if (checkOpenCLBlockArgs(S, Arg6))
686       return true;
687 
688     // Forth argument has to be any integer type.
689     if (!Arg3->getType()->isIntegerType()) {
690       S.Diag(TheCall->getArg(3)->getBeginLoc(),
691              diag::err_opencl_builtin_expected_type)
692           << TheCall->getDirectCallee() << "integer";
693       return true;
694     }
695     // check remaining common arguments.
696     Expr *Arg4 = TheCall->getArg(4);
697     Expr *Arg5 = TheCall->getArg(5);
698 
699     // Fifth argument is always passed as a pointer to clk_event_t.
700     if (!Arg4->isNullPointerConstant(S.Context,
701                                      Expr::NPC_ValueDependentIsNotNull) &&
702         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
703       S.Diag(TheCall->getArg(4)->getBeginLoc(),
704              diag::err_opencl_builtin_expected_type)
705           << TheCall->getDirectCallee()
706           << S.Context.getPointerType(S.Context.OCLClkEventTy);
707       return true;
708     }
709 
710     // Sixth argument is always passed as a pointer to clk_event_t.
711     if (!Arg5->isNullPointerConstant(S.Context,
712                                      Expr::NPC_ValueDependentIsNotNull) &&
713         !(Arg5->getType()->isPointerType() &&
714           Arg5->getType()->getPointeeType()->isClkEventT())) {
715       S.Diag(TheCall->getArg(5)->getBeginLoc(),
716              diag::err_opencl_builtin_expected_type)
717           << TheCall->getDirectCallee()
718           << S.Context.getPointerType(S.Context.OCLClkEventTy);
719       return true;
720     }
721 
722     if (NumArgs == 7)
723       return false;
724 
725     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
726   }
727 
728   // None of the specific case has been detected, give generic error
729   S.Diag(TheCall->getBeginLoc(),
730          diag::err_opencl_enqueue_kernel_incorrect_args);
731   return true;
732 }
733 
734 /// Returns OpenCL access qual.
735 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
736     return D->getAttr<OpenCLAccessAttr>();
737 }
738 
739 /// Returns true if pipe element type is different from the pointer.
740 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
741   const Expr *Arg0 = Call->getArg(0);
742   // First argument type should always be pipe.
743   if (!Arg0->getType()->isPipeType()) {
744     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
745         << Call->getDirectCallee() << Arg0->getSourceRange();
746     return true;
747   }
748   OpenCLAccessAttr *AccessQual =
749       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
750   // Validates the access qualifier is compatible with the call.
751   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
752   // read_only and write_only, and assumed to be read_only if no qualifier is
753   // specified.
754   switch (Call->getDirectCallee()->getBuiltinID()) {
755   case Builtin::BIread_pipe:
756   case Builtin::BIreserve_read_pipe:
757   case Builtin::BIcommit_read_pipe:
758   case Builtin::BIwork_group_reserve_read_pipe:
759   case Builtin::BIsub_group_reserve_read_pipe:
760   case Builtin::BIwork_group_commit_read_pipe:
761   case Builtin::BIsub_group_commit_read_pipe:
762     if (!(!AccessQual || AccessQual->isReadOnly())) {
763       S.Diag(Arg0->getBeginLoc(),
764              diag::err_opencl_builtin_pipe_invalid_access_modifier)
765           << "read_only" << Arg0->getSourceRange();
766       return true;
767     }
768     break;
769   case Builtin::BIwrite_pipe:
770   case Builtin::BIreserve_write_pipe:
771   case Builtin::BIcommit_write_pipe:
772   case Builtin::BIwork_group_reserve_write_pipe:
773   case Builtin::BIsub_group_reserve_write_pipe:
774   case Builtin::BIwork_group_commit_write_pipe:
775   case Builtin::BIsub_group_commit_write_pipe:
776     if (!(AccessQual && AccessQual->isWriteOnly())) {
777       S.Diag(Arg0->getBeginLoc(),
778              diag::err_opencl_builtin_pipe_invalid_access_modifier)
779           << "write_only" << Arg0->getSourceRange();
780       return true;
781     }
782     break;
783   default:
784     break;
785   }
786   return false;
787 }
788 
789 /// Returns true if pipe element type is different from the pointer.
790 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
791   const Expr *Arg0 = Call->getArg(0);
792   const Expr *ArgIdx = Call->getArg(Idx);
793   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
794   const QualType EltTy = PipeTy->getElementType();
795   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
796   // The Idx argument should be a pointer and the type of the pointer and
797   // the type of pipe element should also be the same.
798   if (!ArgTy ||
799       !S.Context.hasSameType(
800           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
801     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
802         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
803         << ArgIdx->getType() << ArgIdx->getSourceRange();
804     return true;
805   }
806   return false;
807 }
808 
809 // Performs semantic analysis for the read/write_pipe call.
810 // \param S Reference to the semantic analyzer.
811 // \param Call A pointer to the builtin call.
812 // \return True if a semantic error has been found, false otherwise.
813 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
814   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
815   // functions have two forms.
816   switch (Call->getNumArgs()) {
817   case 2:
818     if (checkOpenCLPipeArg(S, Call))
819       return true;
820     // The call with 2 arguments should be
821     // read/write_pipe(pipe T, T*).
822     // Check packet type T.
823     if (checkOpenCLPipePacketType(S, Call, 1))
824       return true;
825     break;
826 
827   case 4: {
828     if (checkOpenCLPipeArg(S, Call))
829       return true;
830     // The call with 4 arguments should be
831     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
832     // Check reserve_id_t.
833     if (!Call->getArg(1)->getType()->isReserveIDT()) {
834       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
835           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
836           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
837       return true;
838     }
839 
840     // Check the index.
841     const Expr *Arg2 = Call->getArg(2);
842     if (!Arg2->getType()->isIntegerType() &&
843         !Arg2->getType()->isUnsignedIntegerType()) {
844       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
845           << Call->getDirectCallee() << S.Context.UnsignedIntTy
846           << Arg2->getType() << Arg2->getSourceRange();
847       return true;
848     }
849 
850     // Check packet type T.
851     if (checkOpenCLPipePacketType(S, Call, 3))
852       return true;
853   } break;
854   default:
855     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
856         << Call->getDirectCallee() << Call->getSourceRange();
857     return true;
858   }
859 
860   return false;
861 }
862 
863 // Performs a semantic analysis on the {work_group_/sub_group_
864 //        /_}reserve_{read/write}_pipe
865 // \param S Reference to the semantic analyzer.
866 // \param Call The call to the builtin function to be analyzed.
867 // \return True if a semantic error was found, false otherwise.
868 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
869   if (checkArgCount(S, Call, 2))
870     return true;
871 
872   if (checkOpenCLPipeArg(S, Call))
873     return true;
874 
875   // Check the reserve size.
876   if (!Call->getArg(1)->getType()->isIntegerType() &&
877       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
878     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
879         << Call->getDirectCallee() << S.Context.UnsignedIntTy
880         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
881     return true;
882   }
883 
884   // Since return type of reserve_read/write_pipe built-in function is
885   // reserve_id_t, which is not defined in the builtin def file , we used int
886   // as return type and need to override the return type of these functions.
887   Call->setType(S.Context.OCLReserveIDTy);
888 
889   return false;
890 }
891 
892 // Performs a semantic analysis on {work_group_/sub_group_
893 //        /_}commit_{read/write}_pipe
894 // \param S Reference to the semantic analyzer.
895 // \param Call The call to the builtin function to be analyzed.
896 // \return True if a semantic error was found, false otherwise.
897 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
898   if (checkArgCount(S, Call, 2))
899     return true;
900 
901   if (checkOpenCLPipeArg(S, Call))
902     return true;
903 
904   // Check reserve_id_t.
905   if (!Call->getArg(1)->getType()->isReserveIDT()) {
906     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
907         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
908         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
909     return true;
910   }
911 
912   return false;
913 }
914 
915 // Performs a semantic analysis on the call to built-in Pipe
916 //        Query Functions.
917 // \param S Reference to the semantic analyzer.
918 // \param Call The call to the builtin function to be analyzed.
919 // \return True if a semantic error was found, false otherwise.
920 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
921   if (checkArgCount(S, Call, 1))
922     return true;
923 
924   if (!Call->getArg(0)->getType()->isPipeType()) {
925     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
926         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
927     return true;
928   }
929 
930   return false;
931 }
932 
933 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
934 // Performs semantic analysis for the to_global/local/private call.
935 // \param S Reference to the semantic analyzer.
936 // \param BuiltinID ID of the builtin function.
937 // \param Call A pointer to the builtin call.
938 // \return True if a semantic error has been found, false otherwise.
939 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
940                                     CallExpr *Call) {
941   if (Call->getNumArgs() != 1) {
942     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num)
943         << Call->getDirectCallee() << Call->getSourceRange();
944     return true;
945   }
946 
947   auto RT = Call->getArg(0)->getType();
948   if (!RT->isPointerType() || RT->getPointeeType()
949       .getAddressSpace() == LangAS::opencl_constant) {
950     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
951         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
952     return true;
953   }
954 
955   if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
956     S.Diag(Call->getArg(0)->getBeginLoc(),
957            diag::warn_opencl_generic_address_space_arg)
958         << Call->getDirectCallee()->getNameInfo().getAsString()
959         << Call->getArg(0)->getSourceRange();
960   }
961 
962   RT = RT->getPointeeType();
963   auto Qual = RT.getQualifiers();
964   switch (BuiltinID) {
965   case Builtin::BIto_global:
966     Qual.setAddressSpace(LangAS::opencl_global);
967     break;
968   case Builtin::BIto_local:
969     Qual.setAddressSpace(LangAS::opencl_local);
970     break;
971   case Builtin::BIto_private:
972     Qual.setAddressSpace(LangAS::opencl_private);
973     break;
974   default:
975     llvm_unreachable("Invalid builtin function");
976   }
977   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
978       RT.getUnqualifiedType(), Qual)));
979 
980   return false;
981 }
982 
983 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
984   if (checkArgCount(S, TheCall, 1))
985     return ExprError();
986 
987   // Compute __builtin_launder's parameter type from the argument.
988   // The parameter type is:
989   //  * The type of the argument if it's not an array or function type,
990   //  Otherwise,
991   //  * The decayed argument type.
992   QualType ParamTy = [&]() {
993     QualType ArgTy = TheCall->getArg(0)->getType();
994     if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
995       return S.Context.getPointerType(Ty->getElementType());
996     if (ArgTy->isFunctionType()) {
997       return S.Context.getPointerType(ArgTy);
998     }
999     return ArgTy;
1000   }();
1001 
1002   TheCall->setType(ParamTy);
1003 
1004   auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1005     if (!ParamTy->isPointerType())
1006       return 0;
1007     if (ParamTy->isFunctionPointerType())
1008       return 1;
1009     if (ParamTy->isVoidPointerType())
1010       return 2;
1011     return llvm::Optional<unsigned>{};
1012   }();
1013   if (DiagSelect.hasValue()) {
1014     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1015         << DiagSelect.getValue() << TheCall->getSourceRange();
1016     return ExprError();
1017   }
1018 
1019   // We either have an incomplete class type, or we have a class template
1020   // whose instantiation has not been forced. Example:
1021   //
1022   //   template <class T> struct Foo { T value; };
1023   //   Foo<int> *p = nullptr;
1024   //   auto *d = __builtin_launder(p);
1025   if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1026                             diag::err_incomplete_type))
1027     return ExprError();
1028 
1029   assert(ParamTy->getPointeeType()->isObjectType() &&
1030          "Unhandled non-object pointer case");
1031 
1032   InitializedEntity Entity =
1033       InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1034   ExprResult Arg =
1035       S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1036   if (Arg.isInvalid())
1037     return ExprError();
1038   TheCall->setArg(0, Arg.get());
1039 
1040   return TheCall;
1041 }
1042 
1043 // Emit an error and return true if the current architecture is not in the list
1044 // of supported architectures.
1045 static bool
1046 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1047                           ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1048   llvm::Triple::ArchType CurArch =
1049       S.getASTContext().getTargetInfo().getTriple().getArch();
1050   if (llvm::is_contained(SupportedArchs, CurArch))
1051     return false;
1052   S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1053       << TheCall->getSourceRange();
1054   return true;
1055 }
1056 
1057 ExprResult
1058 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1059                                CallExpr *TheCall) {
1060   ExprResult TheCallResult(TheCall);
1061 
1062   // Find out if any arguments are required to be integer constant expressions.
1063   unsigned ICEArguments = 0;
1064   ASTContext::GetBuiltinTypeError Error;
1065   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1066   if (Error != ASTContext::GE_None)
1067     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
1068 
1069   // If any arguments are required to be ICE's, check and diagnose.
1070   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1071     // Skip arguments not required to be ICE's.
1072     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1073 
1074     llvm::APSInt Result;
1075     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1076       return true;
1077     ICEArguments &= ~(1 << ArgNo);
1078   }
1079 
1080   switch (BuiltinID) {
1081   case Builtin::BI__builtin___CFStringMakeConstantString:
1082     assert(TheCall->getNumArgs() == 1 &&
1083            "Wrong # arguments to builtin CFStringMakeConstantString");
1084     if (CheckObjCString(TheCall->getArg(0)))
1085       return ExprError();
1086     break;
1087   case Builtin::BI__builtin_ms_va_start:
1088   case Builtin::BI__builtin_stdarg_start:
1089   case Builtin::BI__builtin_va_start:
1090     if (SemaBuiltinVAStart(BuiltinID, TheCall))
1091       return ExprError();
1092     break;
1093   case Builtin::BI__va_start: {
1094     switch (Context.getTargetInfo().getTriple().getArch()) {
1095     case llvm::Triple::aarch64:
1096     case llvm::Triple::arm:
1097     case llvm::Triple::thumb:
1098       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1099         return ExprError();
1100       break;
1101     default:
1102       if (SemaBuiltinVAStart(BuiltinID, TheCall))
1103         return ExprError();
1104       break;
1105     }
1106     break;
1107   }
1108 
1109   // The acquire, release, and no fence variants are ARM and AArch64 only.
1110   case Builtin::BI_interlockedbittestandset_acq:
1111   case Builtin::BI_interlockedbittestandset_rel:
1112   case Builtin::BI_interlockedbittestandset_nf:
1113   case Builtin::BI_interlockedbittestandreset_acq:
1114   case Builtin::BI_interlockedbittestandreset_rel:
1115   case Builtin::BI_interlockedbittestandreset_nf:
1116     if (CheckBuiltinTargetSupport(
1117             *this, BuiltinID, TheCall,
1118             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1119       return ExprError();
1120     break;
1121 
1122   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1123   case Builtin::BI_bittest64:
1124   case Builtin::BI_bittestandcomplement64:
1125   case Builtin::BI_bittestandreset64:
1126   case Builtin::BI_bittestandset64:
1127   case Builtin::BI_interlockedbittestandreset64:
1128   case Builtin::BI_interlockedbittestandset64:
1129     if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1130                                   {llvm::Triple::x86_64, llvm::Triple::arm,
1131                                    llvm::Triple::thumb, llvm::Triple::aarch64}))
1132       return ExprError();
1133     break;
1134 
1135   case Builtin::BI__builtin_isgreater:
1136   case Builtin::BI__builtin_isgreaterequal:
1137   case Builtin::BI__builtin_isless:
1138   case Builtin::BI__builtin_islessequal:
1139   case Builtin::BI__builtin_islessgreater:
1140   case Builtin::BI__builtin_isunordered:
1141     if (SemaBuiltinUnorderedCompare(TheCall))
1142       return ExprError();
1143     break;
1144   case Builtin::BI__builtin_fpclassify:
1145     if (SemaBuiltinFPClassification(TheCall, 6))
1146       return ExprError();
1147     break;
1148   case Builtin::BI__builtin_isfinite:
1149   case Builtin::BI__builtin_isinf:
1150   case Builtin::BI__builtin_isinf_sign:
1151   case Builtin::BI__builtin_isnan:
1152   case Builtin::BI__builtin_isnormal:
1153   case Builtin::BI__builtin_signbit:
1154   case Builtin::BI__builtin_signbitf:
1155   case Builtin::BI__builtin_signbitl:
1156     if (SemaBuiltinFPClassification(TheCall, 1))
1157       return ExprError();
1158     break;
1159   case Builtin::BI__builtin_shufflevector:
1160     return SemaBuiltinShuffleVector(TheCall);
1161     // TheCall will be freed by the smart pointer here, but that's fine, since
1162     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1163   case Builtin::BI__builtin_prefetch:
1164     if (SemaBuiltinPrefetch(TheCall))
1165       return ExprError();
1166     break;
1167   case Builtin::BI__builtin_alloca_with_align:
1168     if (SemaBuiltinAllocaWithAlign(TheCall))
1169       return ExprError();
1170     break;
1171   case Builtin::BI__assume:
1172   case Builtin::BI__builtin_assume:
1173     if (SemaBuiltinAssume(TheCall))
1174       return ExprError();
1175     break;
1176   case Builtin::BI__builtin_assume_aligned:
1177     if (SemaBuiltinAssumeAligned(TheCall))
1178       return ExprError();
1179     break;
1180   case Builtin::BI__builtin_dynamic_object_size:
1181   case Builtin::BI__builtin_object_size:
1182     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1183       return ExprError();
1184     break;
1185   case Builtin::BI__builtin_longjmp:
1186     if (SemaBuiltinLongjmp(TheCall))
1187       return ExprError();
1188     break;
1189   case Builtin::BI__builtin_setjmp:
1190     if (SemaBuiltinSetjmp(TheCall))
1191       return ExprError();
1192     break;
1193   case Builtin::BI_setjmp:
1194   case Builtin::BI_setjmpex:
1195     if (checkArgCount(*this, TheCall, 1))
1196       return true;
1197     break;
1198   case Builtin::BI__builtin_classify_type:
1199     if (checkArgCount(*this, TheCall, 1)) return true;
1200     TheCall->setType(Context.IntTy);
1201     break;
1202   case Builtin::BI__builtin_constant_p:
1203     if (checkArgCount(*this, TheCall, 1)) return true;
1204     TheCall->setType(Context.IntTy);
1205     break;
1206   case Builtin::BI__builtin_launder:
1207     return SemaBuiltinLaunder(*this, TheCall);
1208   case Builtin::BI__sync_fetch_and_add:
1209   case Builtin::BI__sync_fetch_and_add_1:
1210   case Builtin::BI__sync_fetch_and_add_2:
1211   case Builtin::BI__sync_fetch_and_add_4:
1212   case Builtin::BI__sync_fetch_and_add_8:
1213   case Builtin::BI__sync_fetch_and_add_16:
1214   case Builtin::BI__sync_fetch_and_sub:
1215   case Builtin::BI__sync_fetch_and_sub_1:
1216   case Builtin::BI__sync_fetch_and_sub_2:
1217   case Builtin::BI__sync_fetch_and_sub_4:
1218   case Builtin::BI__sync_fetch_and_sub_8:
1219   case Builtin::BI__sync_fetch_and_sub_16:
1220   case Builtin::BI__sync_fetch_and_or:
1221   case Builtin::BI__sync_fetch_and_or_1:
1222   case Builtin::BI__sync_fetch_and_or_2:
1223   case Builtin::BI__sync_fetch_and_or_4:
1224   case Builtin::BI__sync_fetch_and_or_8:
1225   case Builtin::BI__sync_fetch_and_or_16:
1226   case Builtin::BI__sync_fetch_and_and:
1227   case Builtin::BI__sync_fetch_and_and_1:
1228   case Builtin::BI__sync_fetch_and_and_2:
1229   case Builtin::BI__sync_fetch_and_and_4:
1230   case Builtin::BI__sync_fetch_and_and_8:
1231   case Builtin::BI__sync_fetch_and_and_16:
1232   case Builtin::BI__sync_fetch_and_xor:
1233   case Builtin::BI__sync_fetch_and_xor_1:
1234   case Builtin::BI__sync_fetch_and_xor_2:
1235   case Builtin::BI__sync_fetch_and_xor_4:
1236   case Builtin::BI__sync_fetch_and_xor_8:
1237   case Builtin::BI__sync_fetch_and_xor_16:
1238   case Builtin::BI__sync_fetch_and_nand:
1239   case Builtin::BI__sync_fetch_and_nand_1:
1240   case Builtin::BI__sync_fetch_and_nand_2:
1241   case Builtin::BI__sync_fetch_and_nand_4:
1242   case Builtin::BI__sync_fetch_and_nand_8:
1243   case Builtin::BI__sync_fetch_and_nand_16:
1244   case Builtin::BI__sync_add_and_fetch:
1245   case Builtin::BI__sync_add_and_fetch_1:
1246   case Builtin::BI__sync_add_and_fetch_2:
1247   case Builtin::BI__sync_add_and_fetch_4:
1248   case Builtin::BI__sync_add_and_fetch_8:
1249   case Builtin::BI__sync_add_and_fetch_16:
1250   case Builtin::BI__sync_sub_and_fetch:
1251   case Builtin::BI__sync_sub_and_fetch_1:
1252   case Builtin::BI__sync_sub_and_fetch_2:
1253   case Builtin::BI__sync_sub_and_fetch_4:
1254   case Builtin::BI__sync_sub_and_fetch_8:
1255   case Builtin::BI__sync_sub_and_fetch_16:
1256   case Builtin::BI__sync_and_and_fetch:
1257   case Builtin::BI__sync_and_and_fetch_1:
1258   case Builtin::BI__sync_and_and_fetch_2:
1259   case Builtin::BI__sync_and_and_fetch_4:
1260   case Builtin::BI__sync_and_and_fetch_8:
1261   case Builtin::BI__sync_and_and_fetch_16:
1262   case Builtin::BI__sync_or_and_fetch:
1263   case Builtin::BI__sync_or_and_fetch_1:
1264   case Builtin::BI__sync_or_and_fetch_2:
1265   case Builtin::BI__sync_or_and_fetch_4:
1266   case Builtin::BI__sync_or_and_fetch_8:
1267   case Builtin::BI__sync_or_and_fetch_16:
1268   case Builtin::BI__sync_xor_and_fetch:
1269   case Builtin::BI__sync_xor_and_fetch_1:
1270   case Builtin::BI__sync_xor_and_fetch_2:
1271   case Builtin::BI__sync_xor_and_fetch_4:
1272   case Builtin::BI__sync_xor_and_fetch_8:
1273   case Builtin::BI__sync_xor_and_fetch_16:
1274   case Builtin::BI__sync_nand_and_fetch:
1275   case Builtin::BI__sync_nand_and_fetch_1:
1276   case Builtin::BI__sync_nand_and_fetch_2:
1277   case Builtin::BI__sync_nand_and_fetch_4:
1278   case Builtin::BI__sync_nand_and_fetch_8:
1279   case Builtin::BI__sync_nand_and_fetch_16:
1280   case Builtin::BI__sync_val_compare_and_swap:
1281   case Builtin::BI__sync_val_compare_and_swap_1:
1282   case Builtin::BI__sync_val_compare_and_swap_2:
1283   case Builtin::BI__sync_val_compare_and_swap_4:
1284   case Builtin::BI__sync_val_compare_and_swap_8:
1285   case Builtin::BI__sync_val_compare_and_swap_16:
1286   case Builtin::BI__sync_bool_compare_and_swap:
1287   case Builtin::BI__sync_bool_compare_and_swap_1:
1288   case Builtin::BI__sync_bool_compare_and_swap_2:
1289   case Builtin::BI__sync_bool_compare_and_swap_4:
1290   case Builtin::BI__sync_bool_compare_and_swap_8:
1291   case Builtin::BI__sync_bool_compare_and_swap_16:
1292   case Builtin::BI__sync_lock_test_and_set:
1293   case Builtin::BI__sync_lock_test_and_set_1:
1294   case Builtin::BI__sync_lock_test_and_set_2:
1295   case Builtin::BI__sync_lock_test_and_set_4:
1296   case Builtin::BI__sync_lock_test_and_set_8:
1297   case Builtin::BI__sync_lock_test_and_set_16:
1298   case Builtin::BI__sync_lock_release:
1299   case Builtin::BI__sync_lock_release_1:
1300   case Builtin::BI__sync_lock_release_2:
1301   case Builtin::BI__sync_lock_release_4:
1302   case Builtin::BI__sync_lock_release_8:
1303   case Builtin::BI__sync_lock_release_16:
1304   case Builtin::BI__sync_swap:
1305   case Builtin::BI__sync_swap_1:
1306   case Builtin::BI__sync_swap_2:
1307   case Builtin::BI__sync_swap_4:
1308   case Builtin::BI__sync_swap_8:
1309   case Builtin::BI__sync_swap_16:
1310     return SemaBuiltinAtomicOverloaded(TheCallResult);
1311   case Builtin::BI__sync_synchronize:
1312     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1313         << TheCall->getCallee()->getSourceRange();
1314     break;
1315   case Builtin::BI__builtin_nontemporal_load:
1316   case Builtin::BI__builtin_nontemporal_store:
1317     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1318 #define BUILTIN(ID, TYPE, ATTRS)
1319 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1320   case Builtin::BI##ID: \
1321     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1322 #include "clang/Basic/Builtins.def"
1323   case Builtin::BI__annotation:
1324     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1325       return ExprError();
1326     break;
1327   case Builtin::BI__builtin_annotation:
1328     if (SemaBuiltinAnnotation(*this, TheCall))
1329       return ExprError();
1330     break;
1331   case Builtin::BI__builtin_addressof:
1332     if (SemaBuiltinAddressof(*this, TheCall))
1333       return ExprError();
1334     break;
1335   case Builtin::BI__builtin_add_overflow:
1336   case Builtin::BI__builtin_sub_overflow:
1337   case Builtin::BI__builtin_mul_overflow:
1338     if (SemaBuiltinOverflow(*this, TheCall))
1339       return ExprError();
1340     break;
1341   case Builtin::BI__builtin_operator_new:
1342   case Builtin::BI__builtin_operator_delete: {
1343     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1344     ExprResult Res =
1345         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1346     if (Res.isInvalid())
1347       CorrectDelayedTyposInExpr(TheCallResult.get());
1348     return Res;
1349   }
1350   case Builtin::BI__builtin_dump_struct: {
1351     // We first want to ensure we are called with 2 arguments
1352     if (checkArgCount(*this, TheCall, 2))
1353       return ExprError();
1354     // Ensure that the first argument is of type 'struct XX *'
1355     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1356     const QualType PtrArgType = PtrArg->getType();
1357     if (!PtrArgType->isPointerType() ||
1358         !PtrArgType->getPointeeType()->isRecordType()) {
1359       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1360           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1361           << "structure pointer";
1362       return ExprError();
1363     }
1364 
1365     // Ensure that the second argument is of type 'FunctionType'
1366     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1367     const QualType FnPtrArgType = FnPtrArg->getType();
1368     if (!FnPtrArgType->isPointerType()) {
1369       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1370           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1371           << FnPtrArgType << "'int (*)(const char *, ...)'";
1372       return ExprError();
1373     }
1374 
1375     const auto *FuncType =
1376         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1377 
1378     if (!FuncType) {
1379       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1380           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1381           << FnPtrArgType << "'int (*)(const char *, ...)'";
1382       return ExprError();
1383     }
1384 
1385     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1386       if (!FT->getNumParams()) {
1387         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1388             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1389             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1390         return ExprError();
1391       }
1392       QualType PT = FT->getParamType(0);
1393       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1394           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1395           !PT->getPointeeType().isConstQualified()) {
1396         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1397             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1398             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1399         return ExprError();
1400       }
1401     }
1402 
1403     TheCall->setType(Context.IntTy);
1404     break;
1405   }
1406   case Builtin::BI__builtin_call_with_static_chain:
1407     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1408       return ExprError();
1409     break;
1410   case Builtin::BI__exception_code:
1411   case Builtin::BI_exception_code:
1412     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1413                                  diag::err_seh___except_block))
1414       return ExprError();
1415     break;
1416   case Builtin::BI__exception_info:
1417   case Builtin::BI_exception_info:
1418     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1419                                  diag::err_seh___except_filter))
1420       return ExprError();
1421     break;
1422   case Builtin::BI__GetExceptionInfo:
1423     if (checkArgCount(*this, TheCall, 1))
1424       return ExprError();
1425 
1426     if (CheckCXXThrowOperand(
1427             TheCall->getBeginLoc(),
1428             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1429             TheCall))
1430       return ExprError();
1431 
1432     TheCall->setType(Context.VoidPtrTy);
1433     break;
1434   // OpenCL v2.0, s6.13.16 - Pipe functions
1435   case Builtin::BIread_pipe:
1436   case Builtin::BIwrite_pipe:
1437     // Since those two functions are declared with var args, we need a semantic
1438     // check for the argument.
1439     if (SemaBuiltinRWPipe(*this, TheCall))
1440       return ExprError();
1441     break;
1442   case Builtin::BIreserve_read_pipe:
1443   case Builtin::BIreserve_write_pipe:
1444   case Builtin::BIwork_group_reserve_read_pipe:
1445   case Builtin::BIwork_group_reserve_write_pipe:
1446     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1447       return ExprError();
1448     break;
1449   case Builtin::BIsub_group_reserve_read_pipe:
1450   case Builtin::BIsub_group_reserve_write_pipe:
1451     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1452         SemaBuiltinReserveRWPipe(*this, TheCall))
1453       return ExprError();
1454     break;
1455   case Builtin::BIcommit_read_pipe:
1456   case Builtin::BIcommit_write_pipe:
1457   case Builtin::BIwork_group_commit_read_pipe:
1458   case Builtin::BIwork_group_commit_write_pipe:
1459     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1460       return ExprError();
1461     break;
1462   case Builtin::BIsub_group_commit_read_pipe:
1463   case Builtin::BIsub_group_commit_write_pipe:
1464     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1465         SemaBuiltinCommitRWPipe(*this, TheCall))
1466       return ExprError();
1467     break;
1468   case Builtin::BIget_pipe_num_packets:
1469   case Builtin::BIget_pipe_max_packets:
1470     if (SemaBuiltinPipePackets(*this, TheCall))
1471       return ExprError();
1472     break;
1473   case Builtin::BIto_global:
1474   case Builtin::BIto_local:
1475   case Builtin::BIto_private:
1476     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1477       return ExprError();
1478     break;
1479   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1480   case Builtin::BIenqueue_kernel:
1481     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1482       return ExprError();
1483     break;
1484   case Builtin::BIget_kernel_work_group_size:
1485   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1486     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1487       return ExprError();
1488     break;
1489   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1490   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1491     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1492       return ExprError();
1493     break;
1494   case Builtin::BI__builtin_os_log_format:
1495   case Builtin::BI__builtin_os_log_format_buffer_size:
1496     if (SemaBuiltinOSLogFormat(TheCall))
1497       return ExprError();
1498     break;
1499   }
1500 
1501   // Since the target specific builtins for each arch overlap, only check those
1502   // of the arch we are compiling for.
1503   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1504     switch (Context.getTargetInfo().getTriple().getArch()) {
1505       case llvm::Triple::arm:
1506       case llvm::Triple::armeb:
1507       case llvm::Triple::thumb:
1508       case llvm::Triple::thumbeb:
1509         if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1510           return ExprError();
1511         break;
1512       case llvm::Triple::aarch64:
1513       case llvm::Triple::aarch64_be:
1514         if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
1515           return ExprError();
1516         break;
1517       case llvm::Triple::hexagon:
1518         if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall))
1519           return ExprError();
1520         break;
1521       case llvm::Triple::mips:
1522       case llvm::Triple::mipsel:
1523       case llvm::Triple::mips64:
1524       case llvm::Triple::mips64el:
1525         if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1526           return ExprError();
1527         break;
1528       case llvm::Triple::systemz:
1529         if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1530           return ExprError();
1531         break;
1532       case llvm::Triple::x86:
1533       case llvm::Triple::x86_64:
1534         if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1535           return ExprError();
1536         break;
1537       case llvm::Triple::ppc:
1538       case llvm::Triple::ppc64:
1539       case llvm::Triple::ppc64le:
1540         if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1541           return ExprError();
1542         break;
1543       default:
1544         break;
1545     }
1546   }
1547 
1548   return TheCallResult;
1549 }
1550 
1551 // Get the valid immediate range for the specified NEON type code.
1552 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1553   NeonTypeFlags Type(t);
1554   int IsQuad = ForceQuad ? true : Type.isQuad();
1555   switch (Type.getEltType()) {
1556   case NeonTypeFlags::Int8:
1557   case NeonTypeFlags::Poly8:
1558     return shift ? 7 : (8 << IsQuad) - 1;
1559   case NeonTypeFlags::Int16:
1560   case NeonTypeFlags::Poly16:
1561     return shift ? 15 : (4 << IsQuad) - 1;
1562   case NeonTypeFlags::Int32:
1563     return shift ? 31 : (2 << IsQuad) - 1;
1564   case NeonTypeFlags::Int64:
1565   case NeonTypeFlags::Poly64:
1566     return shift ? 63 : (1 << IsQuad) - 1;
1567   case NeonTypeFlags::Poly128:
1568     return shift ? 127 : (1 << IsQuad) - 1;
1569   case NeonTypeFlags::Float16:
1570     assert(!shift && "cannot shift float types!");
1571     return (4 << IsQuad) - 1;
1572   case NeonTypeFlags::Float32:
1573     assert(!shift && "cannot shift float types!");
1574     return (2 << IsQuad) - 1;
1575   case NeonTypeFlags::Float64:
1576     assert(!shift && "cannot shift float types!");
1577     return (1 << IsQuad) - 1;
1578   }
1579   llvm_unreachable("Invalid NeonTypeFlag!");
1580 }
1581 
1582 /// getNeonEltType - Return the QualType corresponding to the elements of
1583 /// the vector type specified by the NeonTypeFlags.  This is used to check
1584 /// the pointer arguments for Neon load/store intrinsics.
1585 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
1586                                bool IsPolyUnsigned, bool IsInt64Long) {
1587   switch (Flags.getEltType()) {
1588   case NeonTypeFlags::Int8:
1589     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1590   case NeonTypeFlags::Int16:
1591     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1592   case NeonTypeFlags::Int32:
1593     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1594   case NeonTypeFlags::Int64:
1595     if (IsInt64Long)
1596       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1597     else
1598       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1599                                 : Context.LongLongTy;
1600   case NeonTypeFlags::Poly8:
1601     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
1602   case NeonTypeFlags::Poly16:
1603     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
1604   case NeonTypeFlags::Poly64:
1605     if (IsInt64Long)
1606       return Context.UnsignedLongTy;
1607     else
1608       return Context.UnsignedLongLongTy;
1609   case NeonTypeFlags::Poly128:
1610     break;
1611   case NeonTypeFlags::Float16:
1612     return Context.HalfTy;
1613   case NeonTypeFlags::Float32:
1614     return Context.FloatTy;
1615   case NeonTypeFlags::Float64:
1616     return Context.DoubleTy;
1617   }
1618   llvm_unreachable("Invalid NeonTypeFlag!");
1619 }
1620 
1621 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1622   llvm::APSInt Result;
1623   uint64_t mask = 0;
1624   unsigned TV = 0;
1625   int PtrArgNum = -1;
1626   bool HasConstPtr = false;
1627   switch (BuiltinID) {
1628 #define GET_NEON_OVERLOAD_CHECK
1629 #include "clang/Basic/arm_neon.inc"
1630 #include "clang/Basic/arm_fp16.inc"
1631 #undef GET_NEON_OVERLOAD_CHECK
1632   }
1633 
1634   // For NEON intrinsics which are overloaded on vector element type, validate
1635   // the immediate which specifies which variant to emit.
1636   unsigned ImmArg = TheCall->getNumArgs()-1;
1637   if (mask) {
1638     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1639       return true;
1640 
1641     TV = Result.getLimitedValue(64);
1642     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1643       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
1644              << TheCall->getArg(ImmArg)->getSourceRange();
1645   }
1646 
1647   if (PtrArgNum >= 0) {
1648     // Check that pointer arguments have the specified type.
1649     Expr *Arg = TheCall->getArg(PtrArgNum);
1650     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1651       Arg = ICE->getSubExpr();
1652     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1653     QualType RHSTy = RHS.get()->getType();
1654 
1655     llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
1656     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1657                           Arch == llvm::Triple::aarch64_be;
1658     bool IsInt64Long =
1659         Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1660     QualType EltTy =
1661         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
1662     if (HasConstPtr)
1663       EltTy = EltTy.withConst();
1664     QualType LHSTy = Context.getPointerType(EltTy);
1665     AssignConvertType ConvTy;
1666     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1667     if (RHS.isInvalid())
1668       return true;
1669     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
1670                                  RHS.get(), AA_Assigning))
1671       return true;
1672   }
1673 
1674   // For NEON intrinsics which take an immediate value as part of the
1675   // instruction, range check them here.
1676   unsigned i = 0, l = 0, u = 0;
1677   switch (BuiltinID) {
1678   default:
1679     return false;
1680   #define GET_NEON_IMMEDIATE_CHECK
1681   #include "clang/Basic/arm_neon.inc"
1682   #include "clang/Basic/arm_fp16.inc"
1683   #undef GET_NEON_IMMEDIATE_CHECK
1684   }
1685 
1686   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1687 }
1688 
1689 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1690                                         unsigned MaxWidth) {
1691   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
1692           BuiltinID == ARM::BI__builtin_arm_ldaex ||
1693           BuiltinID == ARM::BI__builtin_arm_strex ||
1694           BuiltinID == ARM::BI__builtin_arm_stlex ||
1695           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1696           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1697           BuiltinID == AArch64::BI__builtin_arm_strex ||
1698           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
1699          "unexpected ARM builtin");
1700   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
1701                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
1702                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1703                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
1704 
1705   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1706 
1707   // Ensure that we have the proper number of arguments.
1708   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1709     return true;
1710 
1711   // Inspect the pointer argument of the atomic builtin.  This should always be
1712   // a pointer type, whose element is an integral scalar or pointer type.
1713   // Because it is a pointer type, we don't have to worry about any implicit
1714   // casts here.
1715   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1716   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1717   if (PointerArgRes.isInvalid())
1718     return true;
1719   PointerArg = PointerArgRes.get();
1720 
1721   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1722   if (!pointerType) {
1723     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
1724         << PointerArg->getType() << PointerArg->getSourceRange();
1725     return true;
1726   }
1727 
1728   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1729   // task is to insert the appropriate casts into the AST. First work out just
1730   // what the appropriate type is.
1731   QualType ValType = pointerType->getPointeeType();
1732   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1733   if (IsLdrex)
1734     AddrType.addConst();
1735 
1736   // Issue a warning if the cast is dodgy.
1737   CastKind CastNeeded = CK_NoOp;
1738   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1739     CastNeeded = CK_BitCast;
1740     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
1741         << PointerArg->getType() << Context.getPointerType(AddrType)
1742         << AA_Passing << PointerArg->getSourceRange();
1743   }
1744 
1745   // Finally, do the cast and replace the argument with the corrected version.
1746   AddrType = Context.getPointerType(AddrType);
1747   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1748   if (PointerArgRes.isInvalid())
1749     return true;
1750   PointerArg = PointerArgRes.get();
1751 
1752   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1753 
1754   // In general, we allow ints, floats and pointers to be loaded and stored.
1755   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1756       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1757     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1758         << PointerArg->getType() << PointerArg->getSourceRange();
1759     return true;
1760   }
1761 
1762   // But ARM doesn't have instructions to deal with 128-bit versions.
1763   if (Context.getTypeSize(ValType) > MaxWidth) {
1764     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
1765     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
1766         << PointerArg->getType() << PointerArg->getSourceRange();
1767     return true;
1768   }
1769 
1770   switch (ValType.getObjCLifetime()) {
1771   case Qualifiers::OCL_None:
1772   case Qualifiers::OCL_ExplicitNone:
1773     // okay
1774     break;
1775 
1776   case Qualifiers::OCL_Weak:
1777   case Qualifiers::OCL_Strong:
1778   case Qualifiers::OCL_Autoreleasing:
1779     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
1780         << ValType << PointerArg->getSourceRange();
1781     return true;
1782   }
1783 
1784   if (IsLdrex) {
1785     TheCall->setType(ValType);
1786     return false;
1787   }
1788 
1789   // Initialize the argument to be stored.
1790   ExprResult ValArg = TheCall->getArg(0);
1791   InitializedEntity Entity = InitializedEntity::InitializeParameter(
1792       Context, ValType, /*consume*/ false);
1793   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1794   if (ValArg.isInvalid())
1795     return true;
1796   TheCall->setArg(0, ValArg.get());
1797 
1798   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1799   // but the custom checker bypasses all default analysis.
1800   TheCall->setType(Context.IntTy);
1801   return false;
1802 }
1803 
1804 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1805   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
1806       BuiltinID == ARM::BI__builtin_arm_ldaex ||
1807       BuiltinID == ARM::BI__builtin_arm_strex ||
1808       BuiltinID == ARM::BI__builtin_arm_stlex) {
1809     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
1810   }
1811 
1812   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1813     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1814       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1815   }
1816 
1817   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1818       BuiltinID == ARM::BI__builtin_arm_wsr64)
1819     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1820 
1821   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1822       BuiltinID == ARM::BI__builtin_arm_rsrp ||
1823       BuiltinID == ARM::BI__builtin_arm_wsr ||
1824       BuiltinID == ARM::BI__builtin_arm_wsrp)
1825     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1826 
1827   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1828     return true;
1829 
1830   // For intrinsics which take an immediate value as part of the instruction,
1831   // range check them here.
1832   // FIXME: VFP Intrinsics should error if VFP not present.
1833   switch (BuiltinID) {
1834   default: return false;
1835   case ARM::BI__builtin_arm_ssat:
1836     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
1837   case ARM::BI__builtin_arm_usat:
1838     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
1839   case ARM::BI__builtin_arm_ssat16:
1840     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
1841   case ARM::BI__builtin_arm_usat16:
1842     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
1843   case ARM::BI__builtin_arm_vcvtr_f:
1844   case ARM::BI__builtin_arm_vcvtr_d:
1845     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
1846   case ARM::BI__builtin_arm_dmb:
1847   case ARM::BI__builtin_arm_dsb:
1848   case ARM::BI__builtin_arm_isb:
1849   case ARM::BI__builtin_arm_dbg:
1850     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
1851   }
1852 }
1853 
1854 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
1855                                          CallExpr *TheCall) {
1856   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1857       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1858       BuiltinID == AArch64::BI__builtin_arm_strex ||
1859       BuiltinID == AArch64::BI__builtin_arm_stlex) {
1860     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1861   }
1862 
1863   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1864     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1865       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1866       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1867       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1868   }
1869 
1870   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1871       BuiltinID == AArch64::BI__builtin_arm_wsr64)
1872     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1873 
1874   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1875       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1876       BuiltinID == AArch64::BI__builtin_arm_wsr ||
1877       BuiltinID == AArch64::BI__builtin_arm_wsrp)
1878     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1879 
1880   // Only check the valid encoding range. Any constant in this range would be
1881   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
1882   // an exception for incorrect registers. This matches MSVC behavior.
1883   if (BuiltinID == AArch64::BI_ReadStatusReg ||
1884       BuiltinID == AArch64::BI_WriteStatusReg)
1885     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
1886 
1887   if (BuiltinID == AArch64::BI__getReg)
1888     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
1889 
1890   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1891     return true;
1892 
1893   // For intrinsics which take an immediate value as part of the instruction,
1894   // range check them here.
1895   unsigned i = 0, l = 0, u = 0;
1896   switch (BuiltinID) {
1897   default: return false;
1898   case AArch64::BI__builtin_arm_dmb:
1899   case AArch64::BI__builtin_arm_dsb:
1900   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1901   }
1902 
1903   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1904 }
1905 
1906 bool Sema::CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) {
1907   struct BuiltinAndString {
1908     unsigned BuiltinID;
1909     const char *Str;
1910   };
1911 
1912   static BuiltinAndString ValidCPU[] = {
1913     { Hexagon::BI__builtin_HEXAGON_A6_vcmpbeq_notany, "v65,v66" },
1914     { Hexagon::BI__builtin_HEXAGON_A6_vminub_RdP, "v62,v65,v66" },
1915     { Hexagon::BI__builtin_HEXAGON_F2_dfadd, "v66" },
1916     { Hexagon::BI__builtin_HEXAGON_F2_dfsub, "v66" },
1917     { Hexagon::BI__builtin_HEXAGON_M2_mnaci, "v66" },
1918     { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffb, "v62,v65,v66" },
1919     { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffub, "v62,v65,v66" },
1920     { Hexagon::BI__builtin_HEXAGON_S2_mask, "v66" },
1921     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, "v60,v62,v65,v66" },
1922     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, "v60,v62,v65,v66" },
1923     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, "v60,v62,v65,v66" },
1924     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, "v60,v62,v65,v66" },
1925     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, "v60,v62,v65,v66" },
1926     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, "v60,v62,v65,v66" },
1927     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, "v60,v62,v65,v66" },
1928     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, "v60,v62,v65,v66" },
1929     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, "v60,v62,v65,v66" },
1930     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, "v60,v62,v65,v66" },
1931     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, "v60,v62,v65,v66" },
1932     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, "v60,v62,v65,v66" },
1933     { Hexagon::BI__builtin_HEXAGON_S6_vsplatrbp, "v62,v65,v66" },
1934     { Hexagon::BI__builtin_HEXAGON_S6_vtrunehb_ppp, "v62,v65,v66" },
1935     { Hexagon::BI__builtin_HEXAGON_S6_vtrunohb_ppp, "v62,v65,v66" },
1936   };
1937 
1938   static BuiltinAndString ValidHVX[] = {
1939     { Hexagon::BI__builtin_HEXAGON_V6_hi, "v60,v62,v65,v66" },
1940     { Hexagon::BI__builtin_HEXAGON_V6_hi_128B, "v60,v62,v65,v66" },
1941     { Hexagon::BI__builtin_HEXAGON_V6_lo, "v60,v62,v65,v66" },
1942     { Hexagon::BI__builtin_HEXAGON_V6_lo_128B, "v60,v62,v65,v66" },
1943     { Hexagon::BI__builtin_HEXAGON_V6_extractw, "v60,v62,v65,v66" },
1944     { Hexagon::BI__builtin_HEXAGON_V6_extractw_128B, "v60,v62,v65,v66" },
1945     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb, "v62,v65,v66" },
1946     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb_128B, "v62,v65,v66" },
1947     { Hexagon::BI__builtin_HEXAGON_V6_lvsplath, "v62,v65,v66" },
1948     { Hexagon::BI__builtin_HEXAGON_V6_lvsplath_128B, "v62,v65,v66" },
1949     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw, "v60,v62,v65,v66" },
1950     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw_128B, "v60,v62,v65,v66" },
1951     { Hexagon::BI__builtin_HEXAGON_V6_pred_and, "v60,v62,v65,v66" },
1952     { Hexagon::BI__builtin_HEXAGON_V6_pred_and_128B, "v60,v62,v65,v66" },
1953     { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n, "v60,v62,v65,v66" },
1954     { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n_128B, "v60,v62,v65,v66" },
1955     { Hexagon::BI__builtin_HEXAGON_V6_pred_not, "v60,v62,v65,v66" },
1956     { Hexagon::BI__builtin_HEXAGON_V6_pred_not_128B, "v60,v62,v65,v66" },
1957     { Hexagon::BI__builtin_HEXAGON_V6_pred_or, "v60,v62,v65,v66" },
1958     { Hexagon::BI__builtin_HEXAGON_V6_pred_or_128B, "v60,v62,v65,v66" },
1959     { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n, "v60,v62,v65,v66" },
1960     { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n_128B, "v60,v62,v65,v66" },
1961     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2, "v60,v62,v65,v66" },
1962     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2_128B, "v60,v62,v65,v66" },
1963     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2, "v62,v65,v66" },
1964     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2_128B, "v62,v65,v66" },
1965     { Hexagon::BI__builtin_HEXAGON_V6_pred_xor, "v60,v62,v65,v66" },
1966     { Hexagon::BI__builtin_HEXAGON_V6_pred_xor_128B, "v60,v62,v65,v66" },
1967     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh, "v62,v65,v66" },
1968     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh_128B, "v62,v65,v66" },
1969     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw, "v62,v65,v66" },
1970     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw_128B, "v62,v65,v66" },
1971     { Hexagon::BI__builtin_HEXAGON_V6_vabsb, "v65,v66" },
1972     { Hexagon::BI__builtin_HEXAGON_V6_vabsb_128B, "v65,v66" },
1973     { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat, "v65,v66" },
1974     { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat_128B, "v65,v66" },
1975     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh, "v60,v62,v65,v66" },
1976     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh_128B, "v60,v62,v65,v66" },
1977     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub, "v60,v62,v65,v66" },
1978     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub_128B, "v60,v62,v65,v66" },
1979     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh, "v60,v62,v65,v66" },
1980     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh_128B, "v60,v62,v65,v66" },
1981     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw, "v60,v62,v65,v66" },
1982     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw_128B, "v60,v62,v65,v66" },
1983     { Hexagon::BI__builtin_HEXAGON_V6_vabsh, "v60,v62,v65,v66" },
1984     { Hexagon::BI__builtin_HEXAGON_V6_vabsh_128B, "v60,v62,v65,v66" },
1985     { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat, "v60,v62,v65,v66" },
1986     { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat_128B, "v60,v62,v65,v66" },
1987     { Hexagon::BI__builtin_HEXAGON_V6_vabsw, "v60,v62,v65,v66" },
1988     { Hexagon::BI__builtin_HEXAGON_V6_vabsw_128B, "v60,v62,v65,v66" },
1989     { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat, "v60,v62,v65,v66" },
1990     { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat_128B, "v60,v62,v65,v66" },
1991     { Hexagon::BI__builtin_HEXAGON_V6_vaddb, "v60,v62,v65,v66" },
1992     { Hexagon::BI__builtin_HEXAGON_V6_vaddb_128B, "v60,v62,v65,v66" },
1993     { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv, "v60,v62,v65,v66" },
1994     { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv_128B, "v60,v62,v65,v66" },
1995     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat, "v62,v65,v66" },
1996     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_128B, "v62,v65,v66" },
1997     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv, "v62,v65,v66" },
1998     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv_128B, "v62,v65,v66" },
1999     { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry, "v62,v65,v66" },
2000     { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry_128B, "v62,v65,v66" },
2001     { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat, "v66" },
2002     { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat_128B, "v66" },
2003     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh, "v62,v65,v66" },
2004     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh_128B, "v62,v65,v66" },
2005     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw, "v62,v65,v66" },
2006     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw_128B, "v62,v65,v66" },
2007     { Hexagon::BI__builtin_HEXAGON_V6_vaddh, "v60,v62,v65,v66" },
2008     { Hexagon::BI__builtin_HEXAGON_V6_vaddh_128B, "v60,v62,v65,v66" },
2009     { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv, "v60,v62,v65,v66" },
2010     { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv_128B, "v60,v62,v65,v66" },
2011     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat, "v60,v62,v65,v66" },
2012     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_128B, "v60,v62,v65,v66" },
2013     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv, "v60,v62,v65,v66" },
2014     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv_128B, "v60,v62,v65,v66" },
2015     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw, "v60,v62,v65,v66" },
2016     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_128B, "v60,v62,v65,v66" },
2017     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc, "v62,v65,v66" },
2018     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc_128B, "v62,v65,v66" },
2019     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh, "v60,v62,v65,v66" },
2020     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_128B, "v60,v62,v65,v66" },
2021     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc, "v62,v65,v66" },
2022     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc_128B, "v62,v65,v66" },
2023     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat, "v60,v62,v65,v66" },
2024     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_128B, "v60,v62,v65,v66" },
2025     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv, "v60,v62,v65,v66" },
2026     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv_128B, "v60,v62,v65,v66" },
2027     { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat, "v62,v65,v66" },
2028     { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat_128B, "v62,v65,v66" },
2029     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat, "v60,v62,v65,v66" },
2030     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_128B, "v60,v62,v65,v66" },
2031     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv, "v60,v62,v65,v66" },
2032     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv_128B, "v60,v62,v65,v66" },
2033     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw, "v60,v62,v65,v66" },
2034     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_128B, "v60,v62,v65,v66" },
2035     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc, "v62,v65,v66" },
2036     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc_128B, "v62,v65,v66" },
2037     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat, "v62,v65,v66" },
2038     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_128B, "v62,v65,v66" },
2039     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv, "v62,v65,v66" },
2040     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv_128B, "v62,v65,v66" },
2041     { Hexagon::BI__builtin_HEXAGON_V6_vaddw, "v60,v62,v65,v66" },
2042     { Hexagon::BI__builtin_HEXAGON_V6_vaddw_128B, "v60,v62,v65,v66" },
2043     { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv, "v60,v62,v65,v66" },
2044     { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv_128B, "v60,v62,v65,v66" },
2045     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat, "v60,v62,v65,v66" },
2046     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_128B, "v60,v62,v65,v66" },
2047     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv, "v60,v62,v65,v66" },
2048     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv_128B, "v60,v62,v65,v66" },
2049     { Hexagon::BI__builtin_HEXAGON_V6_valignb, "v60,v62,v65,v66" },
2050     { Hexagon::BI__builtin_HEXAGON_V6_valignb_128B, "v60,v62,v65,v66" },
2051     { Hexagon::BI__builtin_HEXAGON_V6_valignbi, "v60,v62,v65,v66" },
2052     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, "v60,v62,v65,v66" },
2053     { Hexagon::BI__builtin_HEXAGON_V6_vand, "v60,v62,v65,v66" },
2054     { Hexagon::BI__builtin_HEXAGON_V6_vand_128B, "v60,v62,v65,v66" },
2055     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt, "v62,v65,v66" },
2056     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_128B, "v62,v65,v66" },
2057     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc, "v62,v65,v66" },
2058     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc_128B, "v62,v65,v66" },
2059     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt, "v60,v62,v65,v66" },
2060     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_128B, "v60,v62,v65,v66" },
2061     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc, "v60,v62,v65,v66" },
2062     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc_128B, "v60,v62,v65,v66" },
2063     { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv, "v62,v65,v66" },
2064     { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv_128B, "v62,v65,v66" },
2065     { Hexagon::BI__builtin_HEXAGON_V6_vandvqv, "v62,v65,v66" },
2066     { Hexagon::BI__builtin_HEXAGON_V6_vandvqv_128B, "v62,v65,v66" },
2067     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt, "v60,v62,v65,v66" },
2068     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_128B, "v60,v62,v65,v66" },
2069     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc, "v60,v62,v65,v66" },
2070     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc_128B, "v60,v62,v65,v66" },
2071     { Hexagon::BI__builtin_HEXAGON_V6_vaslh, "v60,v62,v65,v66" },
2072     { Hexagon::BI__builtin_HEXAGON_V6_vaslh_128B, "v60,v62,v65,v66" },
2073     { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc, "v65,v66" },
2074     { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc_128B, "v65,v66" },
2075     { Hexagon::BI__builtin_HEXAGON_V6_vaslhv, "v60,v62,v65,v66" },
2076     { Hexagon::BI__builtin_HEXAGON_V6_vaslhv_128B, "v60,v62,v65,v66" },
2077     { Hexagon::BI__builtin_HEXAGON_V6_vaslw, "v60,v62,v65,v66" },
2078     { Hexagon::BI__builtin_HEXAGON_V6_vaslw_128B, "v60,v62,v65,v66" },
2079     { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc, "v60,v62,v65,v66" },
2080     { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc_128B, "v60,v62,v65,v66" },
2081     { Hexagon::BI__builtin_HEXAGON_V6_vaslwv, "v60,v62,v65,v66" },
2082     { Hexagon::BI__builtin_HEXAGON_V6_vaslwv_128B, "v60,v62,v65,v66" },
2083     { Hexagon::BI__builtin_HEXAGON_V6_vasrh, "v60,v62,v65,v66" },
2084     { Hexagon::BI__builtin_HEXAGON_V6_vasrh_128B, "v60,v62,v65,v66" },
2085     { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc, "v65,v66" },
2086     { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc_128B, "v65,v66" },
2087     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat, "v60,v62,v65,v66" },
2088     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat_128B, "v60,v62,v65,v66" },
2089     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat, "v62,v65,v66" },
2090     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat_128B, "v62,v65,v66" },
2091     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat, "v60,v62,v65,v66" },
2092     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat_128B, "v60,v62,v65,v66" },
2093     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat, "v60,v62,v65,v66" },
2094     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat_128B, "v60,v62,v65,v66" },
2095     { Hexagon::BI__builtin_HEXAGON_V6_vasrhv, "v60,v62,v65,v66" },
2096     { Hexagon::BI__builtin_HEXAGON_V6_vasrhv_128B, "v60,v62,v65,v66" },
2097     { Hexagon::BI__builtin_HEXAGON_V6_vasr_into, "v66" },
2098     { Hexagon::BI__builtin_HEXAGON_V6_vasr_into_128B, "v66" },
2099     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat, "v65,v66" },
2100     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat_128B, "v65,v66" },
2101     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat, "v65,v66" },
2102     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat_128B, "v65,v66" },
2103     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat, "v62,v65,v66" },
2104     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat_128B, "v62,v65,v66" },
2105     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat, "v65,v66" },
2106     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat_128B, "v65,v66" },
2107     { Hexagon::BI__builtin_HEXAGON_V6_vasrw, "v60,v62,v65,v66" },
2108     { Hexagon::BI__builtin_HEXAGON_V6_vasrw_128B, "v60,v62,v65,v66" },
2109     { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc, "v60,v62,v65,v66" },
2110     { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc_128B, "v60,v62,v65,v66" },
2111     { Hexagon::BI__builtin_HEXAGON_V6_vasrwh, "v60,v62,v65,v66" },
2112     { Hexagon::BI__builtin_HEXAGON_V6_vasrwh_128B, "v60,v62,v65,v66" },
2113     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat, "v60,v62,v65,v66" },
2114     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat_128B, "v60,v62,v65,v66" },
2115     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat, "v60,v62,v65,v66" },
2116     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat_128B, "v60,v62,v65,v66" },
2117     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat, "v62,v65,v66" },
2118     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat_128B, "v62,v65,v66" },
2119     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat, "v60,v62,v65,v66" },
2120     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat_128B, "v60,v62,v65,v66" },
2121     { Hexagon::BI__builtin_HEXAGON_V6_vasrwv, "v60,v62,v65,v66" },
2122     { Hexagon::BI__builtin_HEXAGON_V6_vasrwv_128B, "v60,v62,v65,v66" },
2123     { Hexagon::BI__builtin_HEXAGON_V6_vassign, "v60,v62,v65,v66" },
2124     { Hexagon::BI__builtin_HEXAGON_V6_vassign_128B, "v60,v62,v65,v66" },
2125     { Hexagon::BI__builtin_HEXAGON_V6_vassignp, "v60,v62,v65,v66" },
2126     { Hexagon::BI__builtin_HEXAGON_V6_vassignp_128B, "v60,v62,v65,v66" },
2127     { Hexagon::BI__builtin_HEXAGON_V6_vavgb, "v65,v66" },
2128     { Hexagon::BI__builtin_HEXAGON_V6_vavgb_128B, "v65,v66" },
2129     { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd, "v65,v66" },
2130     { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd_128B, "v65,v66" },
2131     { Hexagon::BI__builtin_HEXAGON_V6_vavgh, "v60,v62,v65,v66" },
2132     { Hexagon::BI__builtin_HEXAGON_V6_vavgh_128B, "v60,v62,v65,v66" },
2133     { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd, "v60,v62,v65,v66" },
2134     { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd_128B, "v60,v62,v65,v66" },
2135     { Hexagon::BI__builtin_HEXAGON_V6_vavgub, "v60,v62,v65,v66" },
2136     { Hexagon::BI__builtin_HEXAGON_V6_vavgub_128B, "v60,v62,v65,v66" },
2137     { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd, "v60,v62,v65,v66" },
2138     { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd_128B, "v60,v62,v65,v66" },
2139     { Hexagon::BI__builtin_HEXAGON_V6_vavguh, "v60,v62,v65,v66" },
2140     { Hexagon::BI__builtin_HEXAGON_V6_vavguh_128B, "v60,v62,v65,v66" },
2141     { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd, "v60,v62,v65,v66" },
2142     { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd_128B, "v60,v62,v65,v66" },
2143     { Hexagon::BI__builtin_HEXAGON_V6_vavguw, "v65,v66" },
2144     { Hexagon::BI__builtin_HEXAGON_V6_vavguw_128B, "v65,v66" },
2145     { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd, "v65,v66" },
2146     { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd_128B, "v65,v66" },
2147     { Hexagon::BI__builtin_HEXAGON_V6_vavgw, "v60,v62,v65,v66" },
2148     { Hexagon::BI__builtin_HEXAGON_V6_vavgw_128B, "v60,v62,v65,v66" },
2149     { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd, "v60,v62,v65,v66" },
2150     { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd_128B, "v60,v62,v65,v66" },
2151     { Hexagon::BI__builtin_HEXAGON_V6_vcl0h, "v60,v62,v65,v66" },
2152     { Hexagon::BI__builtin_HEXAGON_V6_vcl0h_128B, "v60,v62,v65,v66" },
2153     { Hexagon::BI__builtin_HEXAGON_V6_vcl0w, "v60,v62,v65,v66" },
2154     { Hexagon::BI__builtin_HEXAGON_V6_vcl0w_128B, "v60,v62,v65,v66" },
2155     { Hexagon::BI__builtin_HEXAGON_V6_vcombine, "v60,v62,v65,v66" },
2156     { Hexagon::BI__builtin_HEXAGON_V6_vcombine_128B, "v60,v62,v65,v66" },
2157     { Hexagon::BI__builtin_HEXAGON_V6_vd0, "v60,v62,v65,v66" },
2158     { Hexagon::BI__builtin_HEXAGON_V6_vd0_128B, "v60,v62,v65,v66" },
2159     { Hexagon::BI__builtin_HEXAGON_V6_vdd0, "v65,v66" },
2160     { Hexagon::BI__builtin_HEXAGON_V6_vdd0_128B, "v65,v66" },
2161     { Hexagon::BI__builtin_HEXAGON_V6_vdealb, "v60,v62,v65,v66" },
2162     { Hexagon::BI__builtin_HEXAGON_V6_vdealb_128B, "v60,v62,v65,v66" },
2163     { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w, "v60,v62,v65,v66" },
2164     { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w_128B, "v60,v62,v65,v66" },
2165     { Hexagon::BI__builtin_HEXAGON_V6_vdealh, "v60,v62,v65,v66" },
2166     { Hexagon::BI__builtin_HEXAGON_V6_vdealh_128B, "v60,v62,v65,v66" },
2167     { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd, "v60,v62,v65,v66" },
2168     { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd_128B, "v60,v62,v65,v66" },
2169     { Hexagon::BI__builtin_HEXAGON_V6_vdelta, "v60,v62,v65,v66" },
2170     { Hexagon::BI__builtin_HEXAGON_V6_vdelta_128B, "v60,v62,v65,v66" },
2171     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus, "v60,v62,v65,v66" },
2172     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_128B, "v60,v62,v65,v66" },
2173     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc, "v60,v62,v65,v66" },
2174     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc_128B, "v60,v62,v65,v66" },
2175     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv, "v60,v62,v65,v66" },
2176     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_128B, "v60,v62,v65,v66" },
2177     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc, "v60,v62,v65,v66" },
2178     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc_128B, "v60,v62,v65,v66" },
2179     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb, "v60,v62,v65,v66" },
2180     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_128B, "v60,v62,v65,v66" },
2181     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc, "v60,v62,v65,v66" },
2182     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc_128B, "v60,v62,v65,v66" },
2183     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv, "v60,v62,v65,v66" },
2184     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_128B, "v60,v62,v65,v66" },
2185     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc, "v60,v62,v65,v66" },
2186     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc_128B, "v60,v62,v65,v66" },
2187     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat, "v60,v62,v65,v66" },
2188     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_128B, "v60,v62,v65,v66" },
2189     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc, "v60,v62,v65,v66" },
2190     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc_128B, "v60,v62,v65,v66" },
2191     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat, "v60,v62,v65,v66" },
2192     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_128B, "v60,v62,v65,v66" },
2193     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc, "v60,v62,v65,v66" },
2194     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc_128B, "v60,v62,v65,v66" },
2195     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat, "v60,v62,v65,v66" },
2196     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_128B, "v60,v62,v65,v66" },
2197     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc, "v60,v62,v65,v66" },
2198     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc_128B, "v60,v62,v65,v66" },
2199     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat, "v60,v62,v65,v66" },
2200     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_128B, "v60,v62,v65,v66" },
2201     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc, "v60,v62,v65,v66" },
2202     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc_128B, "v60,v62,v65,v66" },
2203     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat, "v60,v62,v65,v66" },
2204     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_128B, "v60,v62,v65,v66" },
2205     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc, "v60,v62,v65,v66" },
2206     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc_128B, "v60,v62,v65,v66" },
2207     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh, "v60,v62,v65,v66" },
2208     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_128B, "v60,v62,v65,v66" },
2209     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc, "v60,v62,v65,v66" },
2210     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc_128B, "v60,v62,v65,v66" },
2211     { Hexagon::BI__builtin_HEXAGON_V6_veqb, "v60,v62,v65,v66" },
2212     { Hexagon::BI__builtin_HEXAGON_V6_veqb_128B, "v60,v62,v65,v66" },
2213     { Hexagon::BI__builtin_HEXAGON_V6_veqb_and, "v60,v62,v65,v66" },
2214     { Hexagon::BI__builtin_HEXAGON_V6_veqb_and_128B, "v60,v62,v65,v66" },
2215     { Hexagon::BI__builtin_HEXAGON_V6_veqb_or, "v60,v62,v65,v66" },
2216     { Hexagon::BI__builtin_HEXAGON_V6_veqb_or_128B, "v60,v62,v65,v66" },
2217     { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor, "v60,v62,v65,v66" },
2218     { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor_128B, "v60,v62,v65,v66" },
2219     { Hexagon::BI__builtin_HEXAGON_V6_veqh, "v60,v62,v65,v66" },
2220     { Hexagon::BI__builtin_HEXAGON_V6_veqh_128B, "v60,v62,v65,v66" },
2221     { Hexagon::BI__builtin_HEXAGON_V6_veqh_and, "v60,v62,v65,v66" },
2222     { Hexagon::BI__builtin_HEXAGON_V6_veqh_and_128B, "v60,v62,v65,v66" },
2223     { Hexagon::BI__builtin_HEXAGON_V6_veqh_or, "v60,v62,v65,v66" },
2224     { Hexagon::BI__builtin_HEXAGON_V6_veqh_or_128B, "v60,v62,v65,v66" },
2225     { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor, "v60,v62,v65,v66" },
2226     { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor_128B, "v60,v62,v65,v66" },
2227     { Hexagon::BI__builtin_HEXAGON_V6_veqw, "v60,v62,v65,v66" },
2228     { Hexagon::BI__builtin_HEXAGON_V6_veqw_128B, "v60,v62,v65,v66" },
2229     { Hexagon::BI__builtin_HEXAGON_V6_veqw_and, "v60,v62,v65,v66" },
2230     { Hexagon::BI__builtin_HEXAGON_V6_veqw_and_128B, "v60,v62,v65,v66" },
2231     { Hexagon::BI__builtin_HEXAGON_V6_veqw_or, "v60,v62,v65,v66" },
2232     { Hexagon::BI__builtin_HEXAGON_V6_veqw_or_128B, "v60,v62,v65,v66" },
2233     { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor, "v60,v62,v65,v66" },
2234     { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor_128B, "v60,v62,v65,v66" },
2235     { Hexagon::BI__builtin_HEXAGON_V6_vgtb, "v60,v62,v65,v66" },
2236     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_128B, "v60,v62,v65,v66" },
2237     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and, "v60,v62,v65,v66" },
2238     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and_128B, "v60,v62,v65,v66" },
2239     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or, "v60,v62,v65,v66" },
2240     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or_128B, "v60,v62,v65,v66" },
2241     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor, "v60,v62,v65,v66" },
2242     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor_128B, "v60,v62,v65,v66" },
2243     { Hexagon::BI__builtin_HEXAGON_V6_vgth, "v60,v62,v65,v66" },
2244     { Hexagon::BI__builtin_HEXAGON_V6_vgth_128B, "v60,v62,v65,v66" },
2245     { Hexagon::BI__builtin_HEXAGON_V6_vgth_and, "v60,v62,v65,v66" },
2246     { Hexagon::BI__builtin_HEXAGON_V6_vgth_and_128B, "v60,v62,v65,v66" },
2247     { Hexagon::BI__builtin_HEXAGON_V6_vgth_or, "v60,v62,v65,v66" },
2248     { Hexagon::BI__builtin_HEXAGON_V6_vgth_or_128B, "v60,v62,v65,v66" },
2249     { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor, "v60,v62,v65,v66" },
2250     { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor_128B, "v60,v62,v65,v66" },
2251     { Hexagon::BI__builtin_HEXAGON_V6_vgtub, "v60,v62,v65,v66" },
2252     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_128B, "v60,v62,v65,v66" },
2253     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and, "v60,v62,v65,v66" },
2254     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and_128B, "v60,v62,v65,v66" },
2255     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or, "v60,v62,v65,v66" },
2256     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or_128B, "v60,v62,v65,v66" },
2257     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor, "v60,v62,v65,v66" },
2258     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor_128B, "v60,v62,v65,v66" },
2259     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh, "v60,v62,v65,v66" },
2260     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_128B, "v60,v62,v65,v66" },
2261     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and, "v60,v62,v65,v66" },
2262     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and_128B, "v60,v62,v65,v66" },
2263     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or, "v60,v62,v65,v66" },
2264     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or_128B, "v60,v62,v65,v66" },
2265     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor, "v60,v62,v65,v66" },
2266     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor_128B, "v60,v62,v65,v66" },
2267     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw, "v60,v62,v65,v66" },
2268     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_128B, "v60,v62,v65,v66" },
2269     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and, "v60,v62,v65,v66" },
2270     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and_128B, "v60,v62,v65,v66" },
2271     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or, "v60,v62,v65,v66" },
2272     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or_128B, "v60,v62,v65,v66" },
2273     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor, "v60,v62,v65,v66" },
2274     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor_128B, "v60,v62,v65,v66" },
2275     { Hexagon::BI__builtin_HEXAGON_V6_vgtw, "v60,v62,v65,v66" },
2276     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_128B, "v60,v62,v65,v66" },
2277     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and, "v60,v62,v65,v66" },
2278     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and_128B, "v60,v62,v65,v66" },
2279     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or, "v60,v62,v65,v66" },
2280     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or_128B, "v60,v62,v65,v66" },
2281     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor, "v60,v62,v65,v66" },
2282     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor_128B, "v60,v62,v65,v66" },
2283     { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr, "v60,v62,v65,v66" },
2284     { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr_128B, "v60,v62,v65,v66" },
2285     { Hexagon::BI__builtin_HEXAGON_V6_vlalignb, "v60,v62,v65,v66" },
2286     { Hexagon::BI__builtin_HEXAGON_V6_vlalignb_128B, "v60,v62,v65,v66" },
2287     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, "v60,v62,v65,v66" },
2288     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, "v60,v62,v65,v66" },
2289     { Hexagon::BI__builtin_HEXAGON_V6_vlsrb, "v62,v65,v66" },
2290     { Hexagon::BI__builtin_HEXAGON_V6_vlsrb_128B, "v62,v65,v66" },
2291     { Hexagon::BI__builtin_HEXAGON_V6_vlsrh, "v60,v62,v65,v66" },
2292     { Hexagon::BI__builtin_HEXAGON_V6_vlsrh_128B, "v60,v62,v65,v66" },
2293     { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv, "v60,v62,v65,v66" },
2294     { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv_128B, "v60,v62,v65,v66" },
2295     { Hexagon::BI__builtin_HEXAGON_V6_vlsrw, "v60,v62,v65,v66" },
2296     { Hexagon::BI__builtin_HEXAGON_V6_vlsrw_128B, "v60,v62,v65,v66" },
2297     { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv, "v60,v62,v65,v66" },
2298     { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv_128B, "v60,v62,v65,v66" },
2299     { Hexagon::BI__builtin_HEXAGON_V6_vlut4, "v65,v66" },
2300     { Hexagon::BI__builtin_HEXAGON_V6_vlut4_128B, "v65,v66" },
2301     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb, "v60,v62,v65,v66" },
2302     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_128B, "v60,v62,v65,v66" },
2303     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi, "v62,v65,v66" },
2304     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi_128B, "v62,v65,v66" },
2305     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm, "v62,v65,v66" },
2306     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm_128B, "v62,v65,v66" },
2307     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc, "v60,v62,v65,v66" },
2308     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc_128B, "v60,v62,v65,v66" },
2309     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci, "v62,v65,v66" },
2310     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci_128B, "v62,v65,v66" },
2311     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh, "v60,v62,v65,v66" },
2312     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_128B, "v60,v62,v65,v66" },
2313     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi, "v62,v65,v66" },
2314     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi_128B, "v62,v65,v66" },
2315     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm, "v62,v65,v66" },
2316     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm_128B, "v62,v65,v66" },
2317     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc, "v60,v62,v65,v66" },
2318     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc_128B, "v60,v62,v65,v66" },
2319     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci, "v62,v65,v66" },
2320     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci_128B, "v62,v65,v66" },
2321     { Hexagon::BI__builtin_HEXAGON_V6_vmaxb, "v62,v65,v66" },
2322     { Hexagon::BI__builtin_HEXAGON_V6_vmaxb_128B, "v62,v65,v66" },
2323     { Hexagon::BI__builtin_HEXAGON_V6_vmaxh, "v60,v62,v65,v66" },
2324     { Hexagon::BI__builtin_HEXAGON_V6_vmaxh_128B, "v60,v62,v65,v66" },
2325     { Hexagon::BI__builtin_HEXAGON_V6_vmaxub, "v60,v62,v65,v66" },
2326     { Hexagon::BI__builtin_HEXAGON_V6_vmaxub_128B, "v60,v62,v65,v66" },
2327     { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh, "v60,v62,v65,v66" },
2328     { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh_128B, "v60,v62,v65,v66" },
2329     { Hexagon::BI__builtin_HEXAGON_V6_vmaxw, "v60,v62,v65,v66" },
2330     { Hexagon::BI__builtin_HEXAGON_V6_vmaxw_128B, "v60,v62,v65,v66" },
2331     { Hexagon::BI__builtin_HEXAGON_V6_vminb, "v62,v65,v66" },
2332     { Hexagon::BI__builtin_HEXAGON_V6_vminb_128B, "v62,v65,v66" },
2333     { Hexagon::BI__builtin_HEXAGON_V6_vminh, "v60,v62,v65,v66" },
2334     { Hexagon::BI__builtin_HEXAGON_V6_vminh_128B, "v60,v62,v65,v66" },
2335     { Hexagon::BI__builtin_HEXAGON_V6_vminub, "v60,v62,v65,v66" },
2336     { Hexagon::BI__builtin_HEXAGON_V6_vminub_128B, "v60,v62,v65,v66" },
2337     { Hexagon::BI__builtin_HEXAGON_V6_vminuh, "v60,v62,v65,v66" },
2338     { Hexagon::BI__builtin_HEXAGON_V6_vminuh_128B, "v60,v62,v65,v66" },
2339     { Hexagon::BI__builtin_HEXAGON_V6_vminw, "v60,v62,v65,v66" },
2340     { Hexagon::BI__builtin_HEXAGON_V6_vminw_128B, "v60,v62,v65,v66" },
2341     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus, "v60,v62,v65,v66" },
2342     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_128B, "v60,v62,v65,v66" },
2343     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc, "v60,v62,v65,v66" },
2344     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc_128B, "v60,v62,v65,v66" },
2345     { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv, "v60,v62,v65,v66" },
2346     { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv_128B, "v60,v62,v65,v66" },
2347     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu, "v65,v66" },
2348     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_128B, "v65,v66" },
2349     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc, "v65,v66" },
2350     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc_128B, "v65,v66" },
2351     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv, "v60,v62,v65,v66" },
2352     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv_128B, "v60,v62,v65,v66" },
2353     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb, "v60,v62,v65,v66" },
2354     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_128B, "v60,v62,v65,v66" },
2355     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc, "v60,v62,v65,v66" },
2356     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc_128B, "v60,v62,v65,v66" },
2357     { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat, "v65,v66" },
2358     { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat_128B, "v65,v66" },
2359     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb, "v62,v65,v66" },
2360     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_128B, "v62,v65,v66" },
2361     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc, "v62,v65,v66" },
2362     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc_128B, "v62,v65,v66" },
2363     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat, "v65,v66" },
2364     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat_128B, "v65,v66" },
2365     { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat, "v65,v66" },
2366     { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat_128B, "v65,v66" },
2367     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus, "v60,v62,v65,v66" },
2368     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_128B, "v60,v62,v65,v66" },
2369     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc, "v60,v62,v65,v66" },
2370     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc_128B, "v60,v62,v65,v66" },
2371     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv, "v60,v62,v65,v66" },
2372     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_128B, "v60,v62,v65,v66" },
2373     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc, "v60,v62,v65,v66" },
2374     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc_128B, "v60,v62,v65,v66" },
2375     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv, "v60,v62,v65,v66" },
2376     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_128B, "v60,v62,v65,v66" },
2377     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc, "v60,v62,v65,v66" },
2378     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc_128B, "v60,v62,v65,v66" },
2379     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh, "v60,v62,v65,v66" },
2380     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_128B, "v60,v62,v65,v66" },
2381     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64, "v62,v65,v66" },
2382     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64_128B, "v62,v65,v66" },
2383     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh, "v60,v62,v65,v66" },
2384     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_128B, "v60,v62,v65,v66" },
2385     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc, "v65,v66" },
2386     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc_128B, "v65,v66" },
2387     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc, "v60,v62,v65,v66" },
2388     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc_128B, "v60,v62,v65,v66" },
2389     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs, "v60,v62,v65,v66" },
2390     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs_128B, "v60,v62,v65,v66" },
2391     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss, "v60,v62,v65,v66" },
2392     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss_128B, "v60,v62,v65,v66" },
2393     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus, "v60,v62,v65,v66" },
2394     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_128B, "v60,v62,v65,v66" },
2395     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc, "v60,v62,v65,v66" },
2396     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc_128B, "v60,v62,v65,v66" },
2397     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv, "v60,v62,v65,v66" },
2398     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_128B, "v60,v62,v65,v66" },
2399     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc, "v60,v62,v65,v66" },
2400     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc_128B, "v60,v62,v65,v66" },
2401     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs, "v60,v62,v65,v66" },
2402     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs_128B, "v60,v62,v65,v66" },
2403     { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh, "v60,v62,v65,v66" },
2404     { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh_128B, "v60,v62,v65,v66" },
2405     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc, "v60,v62,v65,v66" },
2406     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc_128B, "v60,v62,v65,v66" },
2407     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh, "v60,v62,v65,v66" },
2408     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_128B, "v60,v62,v65,v66" },
2409     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc, "v60,v62,v65,v66" },
2410     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc_128B, "v60,v62,v65,v66" },
2411     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih, "v60,v62,v65,v66" },
2412     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_128B, "v60,v62,v65,v66" },
2413     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc, "v60,v62,v65,v66" },
2414     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc_128B, "v60,v62,v65,v66" },
2415     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb, "v60,v62,v65,v66" },
2416     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_128B, "v60,v62,v65,v66" },
2417     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc, "v60,v62,v65,v66" },
2418     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc_128B, "v60,v62,v65,v66" },
2419     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh, "v60,v62,v65,v66" },
2420     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh_128B, "v60,v62,v65,v66" },
2421     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb, "v60,v62,v65,v66" },
2422     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_128B, "v60,v62,v65,v66" },
2423     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc, "v60,v62,v65,v66" },
2424     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc_128B, "v60,v62,v65,v66" },
2425     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh, "v60,v62,v65,v66" },
2426     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_128B, "v60,v62,v65,v66" },
2427     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc, "v60,v62,v65,v66" },
2428     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc_128B, "v60,v62,v65,v66" },
2429     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub, "v62,v65,v66" },
2430     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_128B, "v62,v65,v66" },
2431     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc, "v62,v65,v66" },
2432     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc_128B, "v62,v65,v66" },
2433     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh, "v60,v62,v65,v66" },
2434     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_128B, "v60,v62,v65,v66" },
2435     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc, "v62,v65,v66" },
2436     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc_128B, "v62,v65,v66" },
2437     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd, "v60,v62,v65,v66" },
2438     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_128B, "v60,v62,v65,v66" },
2439     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc, "v60,v62,v65,v66" },
2440     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc_128B, "v60,v62,v65,v66" },
2441     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc, "v60,v62,v65,v66" },
2442     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc_128B, "v60,v62,v65,v66" },
2443     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub, "v60,v62,v65,v66" },
2444     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_128B, "v60,v62,v65,v66" },
2445     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc, "v60,v62,v65,v66" },
2446     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc_128B, "v60,v62,v65,v66" },
2447     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv, "v60,v62,v65,v66" },
2448     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_128B, "v60,v62,v65,v66" },
2449     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc, "v60,v62,v65,v66" },
2450     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc_128B, "v60,v62,v65,v66" },
2451     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh, "v60,v62,v65,v66" },
2452     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_128B, "v60,v62,v65,v66" },
2453     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc, "v60,v62,v65,v66" },
2454     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc_128B, "v60,v62,v65,v66" },
2455     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe, "v65,v66" },
2456     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_128B, "v65,v66" },
2457     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc, "v65,v66" },
2458     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc_128B, "v65,v66" },
2459     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv, "v60,v62,v65,v66" },
2460     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_128B, "v60,v62,v65,v66" },
2461     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc, "v60,v62,v65,v66" },
2462     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc_128B, "v60,v62,v65,v66" },
2463     { Hexagon::BI__builtin_HEXAGON_V6_vmux, "v60,v62,v65,v66" },
2464     { Hexagon::BI__builtin_HEXAGON_V6_vmux_128B, "v60,v62,v65,v66" },
2465     { Hexagon::BI__builtin_HEXAGON_V6_vnavgb, "v65,v66" },
2466     { Hexagon::BI__builtin_HEXAGON_V6_vnavgb_128B, "v65,v66" },
2467     { Hexagon::BI__builtin_HEXAGON_V6_vnavgh, "v60,v62,v65,v66" },
2468     { Hexagon::BI__builtin_HEXAGON_V6_vnavgh_128B, "v60,v62,v65,v66" },
2469     { Hexagon::BI__builtin_HEXAGON_V6_vnavgub, "v60,v62,v65,v66" },
2470     { Hexagon::BI__builtin_HEXAGON_V6_vnavgub_128B, "v60,v62,v65,v66" },
2471     { Hexagon::BI__builtin_HEXAGON_V6_vnavgw, "v60,v62,v65,v66" },
2472     { Hexagon::BI__builtin_HEXAGON_V6_vnavgw_128B, "v60,v62,v65,v66" },
2473     { Hexagon::BI__builtin_HEXAGON_V6_vnormamth, "v60,v62,v65,v66" },
2474     { Hexagon::BI__builtin_HEXAGON_V6_vnormamth_128B, "v60,v62,v65,v66" },
2475     { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw, "v60,v62,v65,v66" },
2476     { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw_128B, "v60,v62,v65,v66" },
2477     { Hexagon::BI__builtin_HEXAGON_V6_vnot, "v60,v62,v65,v66" },
2478     { Hexagon::BI__builtin_HEXAGON_V6_vnot_128B, "v60,v62,v65,v66" },
2479     { Hexagon::BI__builtin_HEXAGON_V6_vor, "v60,v62,v65,v66" },
2480     { Hexagon::BI__builtin_HEXAGON_V6_vor_128B, "v60,v62,v65,v66" },
2481     { Hexagon::BI__builtin_HEXAGON_V6_vpackeb, "v60,v62,v65,v66" },
2482     { Hexagon::BI__builtin_HEXAGON_V6_vpackeb_128B, "v60,v62,v65,v66" },
2483     { Hexagon::BI__builtin_HEXAGON_V6_vpackeh, "v60,v62,v65,v66" },
2484     { Hexagon::BI__builtin_HEXAGON_V6_vpackeh_128B, "v60,v62,v65,v66" },
2485     { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat, "v60,v62,v65,v66" },
2486     { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat_128B, "v60,v62,v65,v66" },
2487     { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat, "v60,v62,v65,v66" },
2488     { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat_128B, "v60,v62,v65,v66" },
2489     { Hexagon::BI__builtin_HEXAGON_V6_vpackob, "v60,v62,v65,v66" },
2490     { Hexagon::BI__builtin_HEXAGON_V6_vpackob_128B, "v60,v62,v65,v66" },
2491     { Hexagon::BI__builtin_HEXAGON_V6_vpackoh, "v60,v62,v65,v66" },
2492     { Hexagon::BI__builtin_HEXAGON_V6_vpackoh_128B, "v60,v62,v65,v66" },
2493     { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat, "v60,v62,v65,v66" },
2494     { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat_128B, "v60,v62,v65,v66" },
2495     { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat, "v60,v62,v65,v66" },
2496     { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat_128B, "v60,v62,v65,v66" },
2497     { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth, "v60,v62,v65,v66" },
2498     { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth_128B, "v60,v62,v65,v66" },
2499     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb, "v65,v66" },
2500     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb_128B, "v65,v66" },
2501     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh, "v65,v66" },
2502     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh_128B, "v65,v66" },
2503     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw, "v65,v66" },
2504     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw_128B, "v65,v66" },
2505     { Hexagon::BI__builtin_HEXAGON_V6_vrdelta, "v60,v62,v65,v66" },
2506     { Hexagon::BI__builtin_HEXAGON_V6_vrdelta_128B, "v60,v62,v65,v66" },
2507     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt, "v65" },
2508     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_128B, "v65" },
2509     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc, "v65" },
2510     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc_128B, "v65" },
2511     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus, "v60,v62,v65,v66" },
2512     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_128B, "v60,v62,v65,v66" },
2513     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc, "v60,v62,v65,v66" },
2514     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc_128B, "v60,v62,v65,v66" },
2515     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, "v60,v62,v65,v66" },
2516     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, "v60,v62,v65,v66" },
2517     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, "v60,v62,v65,v66" },
2518     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, "v60,v62,v65,v66" },
2519     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv, "v60,v62,v65,v66" },
2520     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_128B, "v60,v62,v65,v66" },
2521     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc, "v60,v62,v65,v66" },
2522     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc_128B, "v60,v62,v65,v66" },
2523     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv, "v60,v62,v65,v66" },
2524     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_128B, "v60,v62,v65,v66" },
2525     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc, "v60,v62,v65,v66" },
2526     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc_128B, "v60,v62,v65,v66" },
2527     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub, "v60,v62,v65,v66" },
2528     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_128B, "v60,v62,v65,v66" },
2529     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc, "v60,v62,v65,v66" },
2530     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc_128B, "v60,v62,v65,v66" },
2531     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, "v60,v62,v65,v66" },
2532     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, "v60,v62,v65,v66" },
2533     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, "v60,v62,v65,v66" },
2534     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, "v60,v62,v65,v66" },
2535     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt, "v65" },
2536     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_128B, "v65" },
2537     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc, "v65" },
2538     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc_128B, "v65" },
2539     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv, "v60,v62,v65,v66" },
2540     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_128B, "v60,v62,v65,v66" },
2541     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc, "v60,v62,v65,v66" },
2542     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc_128B, "v60,v62,v65,v66" },
2543     { Hexagon::BI__builtin_HEXAGON_V6_vror, "v60,v62,v65,v66" },
2544     { Hexagon::BI__builtin_HEXAGON_V6_vror_128B, "v60,v62,v65,v66" },
2545     { Hexagon::BI__builtin_HEXAGON_V6_vrotr, "v66" },
2546     { Hexagon::BI__builtin_HEXAGON_V6_vrotr_128B, "v66" },
2547     { Hexagon::BI__builtin_HEXAGON_V6_vroundhb, "v60,v62,v65,v66" },
2548     { Hexagon::BI__builtin_HEXAGON_V6_vroundhb_128B, "v60,v62,v65,v66" },
2549     { Hexagon::BI__builtin_HEXAGON_V6_vroundhub, "v60,v62,v65,v66" },
2550     { Hexagon::BI__builtin_HEXAGON_V6_vroundhub_128B, "v60,v62,v65,v66" },
2551     { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub, "v62,v65,v66" },
2552     { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub_128B, "v62,v65,v66" },
2553     { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh, "v62,v65,v66" },
2554     { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh_128B, "v62,v65,v66" },
2555     { Hexagon::BI__builtin_HEXAGON_V6_vroundwh, "v60,v62,v65,v66" },
2556     { Hexagon::BI__builtin_HEXAGON_V6_vroundwh_128B, "v60,v62,v65,v66" },
2557     { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh, "v60,v62,v65,v66" },
2558     { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh_128B, "v60,v62,v65,v66" },
2559     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, "v60,v62,v65,v66" },
2560     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, "v60,v62,v65,v66" },
2561     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, "v60,v62,v65,v66" },
2562     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, "v60,v62,v65,v66" },
2563     { Hexagon::BI__builtin_HEXAGON_V6_vsatdw, "v66" },
2564     { Hexagon::BI__builtin_HEXAGON_V6_vsatdw_128B, "v66" },
2565     { Hexagon::BI__builtin_HEXAGON_V6_vsathub, "v60,v62,v65,v66" },
2566     { Hexagon::BI__builtin_HEXAGON_V6_vsathub_128B, "v60,v62,v65,v66" },
2567     { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh, "v62,v65,v66" },
2568     { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh_128B, "v62,v65,v66" },
2569     { Hexagon::BI__builtin_HEXAGON_V6_vsatwh, "v60,v62,v65,v66" },
2570     { Hexagon::BI__builtin_HEXAGON_V6_vsatwh_128B, "v60,v62,v65,v66" },
2571     { Hexagon::BI__builtin_HEXAGON_V6_vsb, "v60,v62,v65,v66" },
2572     { Hexagon::BI__builtin_HEXAGON_V6_vsb_128B, "v60,v62,v65,v66" },
2573     { Hexagon::BI__builtin_HEXAGON_V6_vsh, "v60,v62,v65,v66" },
2574     { Hexagon::BI__builtin_HEXAGON_V6_vsh_128B, "v60,v62,v65,v66" },
2575     { Hexagon::BI__builtin_HEXAGON_V6_vshufeh, "v60,v62,v65,v66" },
2576     { Hexagon::BI__builtin_HEXAGON_V6_vshufeh_128B, "v60,v62,v65,v66" },
2577     { Hexagon::BI__builtin_HEXAGON_V6_vshuffb, "v60,v62,v65,v66" },
2578     { Hexagon::BI__builtin_HEXAGON_V6_vshuffb_128B, "v60,v62,v65,v66" },
2579     { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb, "v60,v62,v65,v66" },
2580     { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb_128B, "v60,v62,v65,v66" },
2581     { Hexagon::BI__builtin_HEXAGON_V6_vshuffh, "v60,v62,v65,v66" },
2582     { Hexagon::BI__builtin_HEXAGON_V6_vshuffh_128B, "v60,v62,v65,v66" },
2583     { Hexagon::BI__builtin_HEXAGON_V6_vshuffob, "v60,v62,v65,v66" },
2584     { Hexagon::BI__builtin_HEXAGON_V6_vshuffob_128B, "v60,v62,v65,v66" },
2585     { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd, "v60,v62,v65,v66" },
2586     { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd_128B, "v60,v62,v65,v66" },
2587     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb, "v60,v62,v65,v66" },
2588     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb_128B, "v60,v62,v65,v66" },
2589     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh, "v60,v62,v65,v66" },
2590     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh_128B, "v60,v62,v65,v66" },
2591     { Hexagon::BI__builtin_HEXAGON_V6_vshufoh, "v60,v62,v65,v66" },
2592     { Hexagon::BI__builtin_HEXAGON_V6_vshufoh_128B, "v60,v62,v65,v66" },
2593     { Hexagon::BI__builtin_HEXAGON_V6_vsubb, "v60,v62,v65,v66" },
2594     { Hexagon::BI__builtin_HEXAGON_V6_vsubb_128B, "v60,v62,v65,v66" },
2595     { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv, "v60,v62,v65,v66" },
2596     { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv_128B, "v60,v62,v65,v66" },
2597     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat, "v62,v65,v66" },
2598     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_128B, "v62,v65,v66" },
2599     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv, "v62,v65,v66" },
2600     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv_128B, "v62,v65,v66" },
2601     { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry, "v62,v65,v66" },
2602     { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry_128B, "v62,v65,v66" },
2603     { Hexagon::BI__builtin_HEXAGON_V6_vsubh, "v60,v62,v65,v66" },
2604     { Hexagon::BI__builtin_HEXAGON_V6_vsubh_128B, "v60,v62,v65,v66" },
2605     { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv, "v60,v62,v65,v66" },
2606     { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv_128B, "v60,v62,v65,v66" },
2607     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat, "v60,v62,v65,v66" },
2608     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_128B, "v60,v62,v65,v66" },
2609     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv, "v60,v62,v65,v66" },
2610     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv_128B, "v60,v62,v65,v66" },
2611     { Hexagon::BI__builtin_HEXAGON_V6_vsubhw, "v60,v62,v65,v66" },
2612     { Hexagon::BI__builtin_HEXAGON_V6_vsubhw_128B, "v60,v62,v65,v66" },
2613     { Hexagon::BI__builtin_HEXAGON_V6_vsububh, "v60,v62,v65,v66" },
2614     { Hexagon::BI__builtin_HEXAGON_V6_vsububh_128B, "v60,v62,v65,v66" },
2615     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat, "v60,v62,v65,v66" },
2616     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_128B, "v60,v62,v65,v66" },
2617     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv, "v60,v62,v65,v66" },
2618     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv_128B, "v60,v62,v65,v66" },
2619     { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat, "v62,v65,v66" },
2620     { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat_128B, "v62,v65,v66" },
2621     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat, "v60,v62,v65,v66" },
2622     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_128B, "v60,v62,v65,v66" },
2623     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv, "v60,v62,v65,v66" },
2624     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv_128B, "v60,v62,v65,v66" },
2625     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw, "v60,v62,v65,v66" },
2626     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw_128B, "v60,v62,v65,v66" },
2627     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat, "v62,v65,v66" },
2628     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_128B, "v62,v65,v66" },
2629     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv, "v62,v65,v66" },
2630     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv_128B, "v62,v65,v66" },
2631     { Hexagon::BI__builtin_HEXAGON_V6_vsubw, "v60,v62,v65,v66" },
2632     { Hexagon::BI__builtin_HEXAGON_V6_vsubw_128B, "v60,v62,v65,v66" },
2633     { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv, "v60,v62,v65,v66" },
2634     { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv_128B, "v60,v62,v65,v66" },
2635     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat, "v60,v62,v65,v66" },
2636     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_128B, "v60,v62,v65,v66" },
2637     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv, "v60,v62,v65,v66" },
2638     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv_128B, "v60,v62,v65,v66" },
2639     { Hexagon::BI__builtin_HEXAGON_V6_vswap, "v60,v62,v65,v66" },
2640     { Hexagon::BI__builtin_HEXAGON_V6_vswap_128B, "v60,v62,v65,v66" },
2641     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb, "v60,v62,v65,v66" },
2642     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_128B, "v60,v62,v65,v66" },
2643     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc, "v60,v62,v65,v66" },
2644     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc_128B, "v60,v62,v65,v66" },
2645     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus, "v60,v62,v65,v66" },
2646     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_128B, "v60,v62,v65,v66" },
2647     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc, "v60,v62,v65,v66" },
2648     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc_128B, "v60,v62,v65,v66" },
2649     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb, "v60,v62,v65,v66" },
2650     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_128B, "v60,v62,v65,v66" },
2651     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc, "v60,v62,v65,v66" },
2652     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc_128B, "v60,v62,v65,v66" },
2653     { Hexagon::BI__builtin_HEXAGON_V6_vunpackb, "v60,v62,v65,v66" },
2654     { Hexagon::BI__builtin_HEXAGON_V6_vunpackb_128B, "v60,v62,v65,v66" },
2655     { Hexagon::BI__builtin_HEXAGON_V6_vunpackh, "v60,v62,v65,v66" },
2656     { Hexagon::BI__builtin_HEXAGON_V6_vunpackh_128B, "v60,v62,v65,v66" },
2657     { Hexagon::BI__builtin_HEXAGON_V6_vunpackob, "v60,v62,v65,v66" },
2658     { Hexagon::BI__builtin_HEXAGON_V6_vunpackob_128B, "v60,v62,v65,v66" },
2659     { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh, "v60,v62,v65,v66" },
2660     { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh_128B, "v60,v62,v65,v66" },
2661     { Hexagon::BI__builtin_HEXAGON_V6_vunpackub, "v60,v62,v65,v66" },
2662     { Hexagon::BI__builtin_HEXAGON_V6_vunpackub_128B, "v60,v62,v65,v66" },
2663     { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh, "v60,v62,v65,v66" },
2664     { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh_128B, "v60,v62,v65,v66" },
2665     { Hexagon::BI__builtin_HEXAGON_V6_vxor, "v60,v62,v65,v66" },
2666     { Hexagon::BI__builtin_HEXAGON_V6_vxor_128B, "v60,v62,v65,v66" },
2667     { Hexagon::BI__builtin_HEXAGON_V6_vzb, "v60,v62,v65,v66" },
2668     { Hexagon::BI__builtin_HEXAGON_V6_vzb_128B, "v60,v62,v65,v66" },
2669     { Hexagon::BI__builtin_HEXAGON_V6_vzh, "v60,v62,v65,v66" },
2670     { Hexagon::BI__builtin_HEXAGON_V6_vzh_128B, "v60,v62,v65,v66" },
2671   };
2672 
2673   // Sort the tables on first execution so we can binary search them.
2674   auto SortCmp = [](const BuiltinAndString &LHS, const BuiltinAndString &RHS) {
2675     return LHS.BuiltinID < RHS.BuiltinID;
2676   };
2677   static const bool SortOnce =
2678       (llvm::sort(ValidCPU, SortCmp),
2679        llvm::sort(ValidHVX, SortCmp), true);
2680   (void)SortOnce;
2681   auto LowerBoundCmp = [](const BuiltinAndString &BI, unsigned BuiltinID) {
2682     return BI.BuiltinID < BuiltinID;
2683   };
2684 
2685   const TargetInfo &TI = Context.getTargetInfo();
2686 
2687   const BuiltinAndString *FC =
2688       std::lower_bound(std::begin(ValidCPU), std::end(ValidCPU), BuiltinID,
2689                        LowerBoundCmp);
2690   if (FC != std::end(ValidCPU) && FC->BuiltinID == BuiltinID) {
2691     const TargetOptions &Opts = TI.getTargetOpts();
2692     StringRef CPU = Opts.CPU;
2693     if (!CPU.empty()) {
2694       assert(CPU.startswith("hexagon") && "Unexpected CPU name");
2695       CPU.consume_front("hexagon");
2696       SmallVector<StringRef, 3> CPUs;
2697       StringRef(FC->Str).split(CPUs, ',');
2698       if (llvm::none_of(CPUs, [CPU](StringRef S) { return S == CPU; }))
2699         return Diag(TheCall->getBeginLoc(),
2700                     diag::err_hexagon_builtin_unsupported_cpu);
2701     }
2702   }
2703 
2704   const BuiltinAndString *FH =
2705       std::lower_bound(std::begin(ValidHVX), std::end(ValidHVX), BuiltinID,
2706                        LowerBoundCmp);
2707   if (FH != std::end(ValidHVX) && FH->BuiltinID == BuiltinID) {
2708     if (!TI.hasFeature("hvx"))
2709       return Diag(TheCall->getBeginLoc(),
2710                   diag::err_hexagon_builtin_requires_hvx);
2711 
2712     SmallVector<StringRef, 3> HVXs;
2713     StringRef(FH->Str).split(HVXs, ',');
2714     bool IsValid = llvm::any_of(HVXs,
2715                                 [&TI] (StringRef V) {
2716                                   std::string F = "hvx" + V.str();
2717                                   return TI.hasFeature(F);
2718                                 });
2719     if (!IsValid)
2720       return Diag(TheCall->getBeginLoc(),
2721                   diag::err_hexagon_builtin_unsupported_hvx);
2722   }
2723 
2724   return false;
2725 }
2726 
2727 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2728   struct ArgInfo {
2729     uint8_t OpNum;
2730     bool IsSigned;
2731     uint8_t BitWidth;
2732     uint8_t Align;
2733   };
2734   struct BuiltinInfo {
2735     unsigned BuiltinID;
2736     ArgInfo Infos[2];
2737   };
2738 
2739   static BuiltinInfo Infos[] = {
2740     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2741     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2742     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2743     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  0 }} },
2744     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2745     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2746     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2747     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2748     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2749     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2750     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2751 
2752     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2753     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2754     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2755     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2756     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2757     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2758     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2759     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2760     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2761     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2762     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2763 
2764     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2765     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2766     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2767     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2768     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2769     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2770     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2771     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2772     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2773     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2774     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2775     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2776     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2777     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2778     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2779     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2780     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2781     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2782     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2783     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2784     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2785     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2786     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2787     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2788     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2789     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2790     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2791     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2792     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2793     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2794     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2795     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
2796     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
2797     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
2798     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
2799     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
2800     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
2801     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
2802     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
2803     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
2804     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
2805     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
2806     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
2807     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
2808     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
2809     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
2810     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
2811     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
2812     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
2813     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
2814     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
2815     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2816                                                       {{ 1, false, 6,  0 }} },
2817     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
2818     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
2819     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
2820     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
2821     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
2822     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
2823     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2824                                                       {{ 1, false, 5,  0 }} },
2825     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
2826     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
2827     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
2828     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
2829     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
2830     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
2831                                                        { 2, false, 5,  0 }} },
2832     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
2833                                                        { 2, false, 6,  0 }} },
2834     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
2835                                                        { 3, false, 5,  0 }} },
2836     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
2837                                                        { 3, false, 6,  0 }} },
2838     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
2839     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
2840     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
2841     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
2842     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
2843     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
2844     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
2845     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
2846     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
2847     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
2848     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
2849     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
2850     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
2851     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
2852     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
2853     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2854                                                       {{ 2, false, 4,  0 },
2855                                                        { 3, false, 5,  0 }} },
2856     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2857                                                       {{ 2, false, 4,  0 },
2858                                                        { 3, false, 5,  0 }} },
2859     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2860                                                       {{ 2, false, 4,  0 },
2861                                                        { 3, false, 5,  0 }} },
2862     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2863                                                       {{ 2, false, 4,  0 },
2864                                                        { 3, false, 5,  0 }} },
2865     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
2866     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
2867     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
2868     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
2869     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
2870     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
2871     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
2872     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
2873     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
2874     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
2875     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
2876                                                        { 2, false, 5,  0 }} },
2877     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
2878                                                        { 2, false, 6,  0 }} },
2879     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
2880     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
2881     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
2882     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
2883     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
2884     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
2885     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
2886     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
2887     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2888                                                       {{ 1, false, 4,  0 }} },
2889     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
2890     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2891                                                       {{ 1, false, 4,  0 }} },
2892     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
2893     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
2894     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
2895     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
2896     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
2897     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
2898     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
2899     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
2900     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
2901     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
2902     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
2903     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
2904     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
2905     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
2906     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
2907     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
2908     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
2909     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
2910     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
2911     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2912                                                       {{ 3, false, 1,  0 }} },
2913     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
2914     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
2915     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
2916     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2917                                                       {{ 3, false, 1,  0 }} },
2918     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
2919     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
2920     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
2921     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2922                                                       {{ 3, false, 1,  0 }} },
2923   };
2924 
2925   // Use a dynamically initialized static to sort the table exactly once on
2926   // first run.
2927   static const bool SortOnce =
2928       (llvm::sort(Infos,
2929                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
2930                    return LHS.BuiltinID < RHS.BuiltinID;
2931                  }),
2932        true);
2933   (void)SortOnce;
2934 
2935   const BuiltinInfo *F =
2936       std::lower_bound(std::begin(Infos), std::end(Infos), BuiltinID,
2937                        [](const BuiltinInfo &BI, unsigned BuiltinID) {
2938                          return BI.BuiltinID < BuiltinID;
2939                        });
2940   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
2941     return false;
2942 
2943   bool Error = false;
2944 
2945   for (const ArgInfo &A : F->Infos) {
2946     // Ignore empty ArgInfo elements.
2947     if (A.BitWidth == 0)
2948       continue;
2949 
2950     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
2951     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
2952     if (!A.Align) {
2953       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2954     } else {
2955       unsigned M = 1 << A.Align;
2956       Min *= M;
2957       Max *= M;
2958       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
2959                SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
2960     }
2961   }
2962   return Error;
2963 }
2964 
2965 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
2966                                            CallExpr *TheCall) {
2967   return CheckHexagonBuiltinCpu(BuiltinID, TheCall) ||
2968          CheckHexagonBuiltinArgument(BuiltinID, TheCall);
2969 }
2970 
2971 
2972 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
2973 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
2974 // ordering for DSP is unspecified. MSA is ordered by the data format used
2975 // by the underlying instruction i.e., df/m, df/n and then by size.
2976 //
2977 // FIXME: The size tests here should instead be tablegen'd along with the
2978 //        definitions from include/clang/Basic/BuiltinsMips.def.
2979 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
2980 //        be too.
2981 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2982   unsigned i = 0, l = 0, u = 0, m = 0;
2983   switch (BuiltinID) {
2984   default: return false;
2985   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
2986   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
2987   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
2988   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
2989   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
2990   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
2991   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
2992   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
2993   // df/m field.
2994   // These intrinsics take an unsigned 3 bit immediate.
2995   case Mips::BI__builtin_msa_bclri_b:
2996   case Mips::BI__builtin_msa_bnegi_b:
2997   case Mips::BI__builtin_msa_bseti_b:
2998   case Mips::BI__builtin_msa_sat_s_b:
2999   case Mips::BI__builtin_msa_sat_u_b:
3000   case Mips::BI__builtin_msa_slli_b:
3001   case Mips::BI__builtin_msa_srai_b:
3002   case Mips::BI__builtin_msa_srari_b:
3003   case Mips::BI__builtin_msa_srli_b:
3004   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3005   case Mips::BI__builtin_msa_binsli_b:
3006   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3007   // These intrinsics take an unsigned 4 bit immediate.
3008   case Mips::BI__builtin_msa_bclri_h:
3009   case Mips::BI__builtin_msa_bnegi_h:
3010   case Mips::BI__builtin_msa_bseti_h:
3011   case Mips::BI__builtin_msa_sat_s_h:
3012   case Mips::BI__builtin_msa_sat_u_h:
3013   case Mips::BI__builtin_msa_slli_h:
3014   case Mips::BI__builtin_msa_srai_h:
3015   case Mips::BI__builtin_msa_srari_h:
3016   case Mips::BI__builtin_msa_srli_h:
3017   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3018   case Mips::BI__builtin_msa_binsli_h:
3019   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
3020   // These intrinsics take an unsigned 5 bit immediate.
3021   // The first block of intrinsics actually have an unsigned 5 bit field,
3022   // not a df/n field.
3023   case Mips::BI__builtin_msa_clei_u_b:
3024   case Mips::BI__builtin_msa_clei_u_h:
3025   case Mips::BI__builtin_msa_clei_u_w:
3026   case Mips::BI__builtin_msa_clei_u_d:
3027   case Mips::BI__builtin_msa_clti_u_b:
3028   case Mips::BI__builtin_msa_clti_u_h:
3029   case Mips::BI__builtin_msa_clti_u_w:
3030   case Mips::BI__builtin_msa_clti_u_d:
3031   case Mips::BI__builtin_msa_maxi_u_b:
3032   case Mips::BI__builtin_msa_maxi_u_h:
3033   case Mips::BI__builtin_msa_maxi_u_w:
3034   case Mips::BI__builtin_msa_maxi_u_d:
3035   case Mips::BI__builtin_msa_mini_u_b:
3036   case Mips::BI__builtin_msa_mini_u_h:
3037   case Mips::BI__builtin_msa_mini_u_w:
3038   case Mips::BI__builtin_msa_mini_u_d:
3039   case Mips::BI__builtin_msa_addvi_b:
3040   case Mips::BI__builtin_msa_addvi_h:
3041   case Mips::BI__builtin_msa_addvi_w:
3042   case Mips::BI__builtin_msa_addvi_d:
3043   case Mips::BI__builtin_msa_bclri_w:
3044   case Mips::BI__builtin_msa_bnegi_w:
3045   case Mips::BI__builtin_msa_bseti_w:
3046   case Mips::BI__builtin_msa_sat_s_w:
3047   case Mips::BI__builtin_msa_sat_u_w:
3048   case Mips::BI__builtin_msa_slli_w:
3049   case Mips::BI__builtin_msa_srai_w:
3050   case Mips::BI__builtin_msa_srari_w:
3051   case Mips::BI__builtin_msa_srli_w:
3052   case Mips::BI__builtin_msa_srlri_w:
3053   case Mips::BI__builtin_msa_subvi_b:
3054   case Mips::BI__builtin_msa_subvi_h:
3055   case Mips::BI__builtin_msa_subvi_w:
3056   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3057   case Mips::BI__builtin_msa_binsli_w:
3058   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3059   // These intrinsics take an unsigned 6 bit immediate.
3060   case Mips::BI__builtin_msa_bclri_d:
3061   case Mips::BI__builtin_msa_bnegi_d:
3062   case Mips::BI__builtin_msa_bseti_d:
3063   case Mips::BI__builtin_msa_sat_s_d:
3064   case Mips::BI__builtin_msa_sat_u_d:
3065   case Mips::BI__builtin_msa_slli_d:
3066   case Mips::BI__builtin_msa_srai_d:
3067   case Mips::BI__builtin_msa_srari_d:
3068   case Mips::BI__builtin_msa_srli_d:
3069   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3070   case Mips::BI__builtin_msa_binsli_d:
3071   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3072   // These intrinsics take a signed 5 bit immediate.
3073   case Mips::BI__builtin_msa_ceqi_b:
3074   case Mips::BI__builtin_msa_ceqi_h:
3075   case Mips::BI__builtin_msa_ceqi_w:
3076   case Mips::BI__builtin_msa_ceqi_d:
3077   case Mips::BI__builtin_msa_clti_s_b:
3078   case Mips::BI__builtin_msa_clti_s_h:
3079   case Mips::BI__builtin_msa_clti_s_w:
3080   case Mips::BI__builtin_msa_clti_s_d:
3081   case Mips::BI__builtin_msa_clei_s_b:
3082   case Mips::BI__builtin_msa_clei_s_h:
3083   case Mips::BI__builtin_msa_clei_s_w:
3084   case Mips::BI__builtin_msa_clei_s_d:
3085   case Mips::BI__builtin_msa_maxi_s_b:
3086   case Mips::BI__builtin_msa_maxi_s_h:
3087   case Mips::BI__builtin_msa_maxi_s_w:
3088   case Mips::BI__builtin_msa_maxi_s_d:
3089   case Mips::BI__builtin_msa_mini_s_b:
3090   case Mips::BI__builtin_msa_mini_s_h:
3091   case Mips::BI__builtin_msa_mini_s_w:
3092   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3093   // These intrinsics take an unsigned 8 bit immediate.
3094   case Mips::BI__builtin_msa_andi_b:
3095   case Mips::BI__builtin_msa_nori_b:
3096   case Mips::BI__builtin_msa_ori_b:
3097   case Mips::BI__builtin_msa_shf_b:
3098   case Mips::BI__builtin_msa_shf_h:
3099   case Mips::BI__builtin_msa_shf_w:
3100   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3101   case Mips::BI__builtin_msa_bseli_b:
3102   case Mips::BI__builtin_msa_bmnzi_b:
3103   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3104   // df/n format
3105   // These intrinsics take an unsigned 4 bit immediate.
3106   case Mips::BI__builtin_msa_copy_s_b:
3107   case Mips::BI__builtin_msa_copy_u_b:
3108   case Mips::BI__builtin_msa_insve_b:
3109   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3110   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3111   // These intrinsics take an unsigned 3 bit immediate.
3112   case Mips::BI__builtin_msa_copy_s_h:
3113   case Mips::BI__builtin_msa_copy_u_h:
3114   case Mips::BI__builtin_msa_insve_h:
3115   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3116   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3117   // These intrinsics take an unsigned 2 bit immediate.
3118   case Mips::BI__builtin_msa_copy_s_w:
3119   case Mips::BI__builtin_msa_copy_u_w:
3120   case Mips::BI__builtin_msa_insve_w:
3121   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3122   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3123   // These intrinsics take an unsigned 1 bit immediate.
3124   case Mips::BI__builtin_msa_copy_s_d:
3125   case Mips::BI__builtin_msa_copy_u_d:
3126   case Mips::BI__builtin_msa_insve_d:
3127   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3128   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3129   // Memory offsets and immediate loads.
3130   // These intrinsics take a signed 10 bit immediate.
3131   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3132   case Mips::BI__builtin_msa_ldi_h:
3133   case Mips::BI__builtin_msa_ldi_w:
3134   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3135   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3136   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3137   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3138   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3139   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3140   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3141   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3142   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3143   }
3144 
3145   if (!m)
3146     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3147 
3148   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3149          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3150 }
3151 
3152 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3153   unsigned i = 0, l = 0, u = 0;
3154   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
3155                       BuiltinID == PPC::BI__builtin_divdeu ||
3156                       BuiltinID == PPC::BI__builtin_bpermd;
3157   bool IsTarget64Bit = Context.getTargetInfo()
3158                               .getTypeWidth(Context
3159                                             .getTargetInfo()
3160                                             .getIntPtrType()) == 64;
3161   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
3162                        BuiltinID == PPC::BI__builtin_divweu ||
3163                        BuiltinID == PPC::BI__builtin_divde ||
3164                        BuiltinID == PPC::BI__builtin_divdeu;
3165 
3166   if (Is64BitBltin && !IsTarget64Bit)
3167     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3168            << TheCall->getSourceRange();
3169 
3170   if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
3171       (BuiltinID == PPC::BI__builtin_bpermd &&
3172        !Context.getTargetInfo().hasFeature("bpermd")))
3173     return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3174            << TheCall->getSourceRange();
3175 
3176   auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
3177     if (!Context.getTargetInfo().hasFeature("vsx"))
3178       return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3179              << TheCall->getSourceRange();
3180     return false;
3181   };
3182 
3183   switch (BuiltinID) {
3184   default: return false;
3185   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3186   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3187     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3188            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3189   case PPC::BI__builtin_tbegin:
3190   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3191   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3192   case PPC::BI__builtin_tabortwc:
3193   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3194   case PPC::BI__builtin_tabortwci:
3195   case PPC::BI__builtin_tabortdci:
3196     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3197            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3198   case PPC::BI__builtin_vsx_xxpermdi:
3199   case PPC::BI__builtin_vsx_xxsldwi:
3200     return SemaBuiltinVSX(TheCall);
3201   case PPC::BI__builtin_unpack_vector_int128:
3202     return SemaVSXCheck(TheCall) ||
3203            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3204   case PPC::BI__builtin_pack_vector_int128:
3205     return SemaVSXCheck(TheCall);
3206   }
3207   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3208 }
3209 
3210 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3211                                            CallExpr *TheCall) {
3212   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3213     Expr *Arg = TheCall->getArg(0);
3214     llvm::APSInt AbortCode(32);
3215     if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
3216         AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
3217       return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3218              << Arg->getSourceRange();
3219   }
3220 
3221   // For intrinsics which take an immediate value as part of the instruction,
3222   // range check them here.
3223   unsigned i = 0, l = 0, u = 0;
3224   switch (BuiltinID) {
3225   default: return false;
3226   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3227   case SystemZ::BI__builtin_s390_verimb:
3228   case SystemZ::BI__builtin_s390_verimh:
3229   case SystemZ::BI__builtin_s390_verimf:
3230   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3231   case SystemZ::BI__builtin_s390_vfaeb:
3232   case SystemZ::BI__builtin_s390_vfaeh:
3233   case SystemZ::BI__builtin_s390_vfaef:
3234   case SystemZ::BI__builtin_s390_vfaebs:
3235   case SystemZ::BI__builtin_s390_vfaehs:
3236   case SystemZ::BI__builtin_s390_vfaefs:
3237   case SystemZ::BI__builtin_s390_vfaezb:
3238   case SystemZ::BI__builtin_s390_vfaezh:
3239   case SystemZ::BI__builtin_s390_vfaezf:
3240   case SystemZ::BI__builtin_s390_vfaezbs:
3241   case SystemZ::BI__builtin_s390_vfaezhs:
3242   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3243   case SystemZ::BI__builtin_s390_vfisb:
3244   case SystemZ::BI__builtin_s390_vfidb:
3245     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3246            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3247   case SystemZ::BI__builtin_s390_vftcisb:
3248   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3249   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3250   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3251   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3252   case SystemZ::BI__builtin_s390_vstrcb:
3253   case SystemZ::BI__builtin_s390_vstrch:
3254   case SystemZ::BI__builtin_s390_vstrcf:
3255   case SystemZ::BI__builtin_s390_vstrczb:
3256   case SystemZ::BI__builtin_s390_vstrczh:
3257   case SystemZ::BI__builtin_s390_vstrczf:
3258   case SystemZ::BI__builtin_s390_vstrcbs:
3259   case SystemZ::BI__builtin_s390_vstrchs:
3260   case SystemZ::BI__builtin_s390_vstrcfs:
3261   case SystemZ::BI__builtin_s390_vstrczbs:
3262   case SystemZ::BI__builtin_s390_vstrczhs:
3263   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3264   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3265   case SystemZ::BI__builtin_s390_vfminsb:
3266   case SystemZ::BI__builtin_s390_vfmaxsb:
3267   case SystemZ::BI__builtin_s390_vfmindb:
3268   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3269   }
3270   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3271 }
3272 
3273 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3274 /// This checks that the target supports __builtin_cpu_supports and
3275 /// that the string argument is constant and valid.
3276 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
3277   Expr *Arg = TheCall->getArg(0);
3278 
3279   // Check if the argument is a string literal.
3280   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3281     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3282            << Arg->getSourceRange();
3283 
3284   // Check the contents of the string.
3285   StringRef Feature =
3286       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3287   if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
3288     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3289            << Arg->getSourceRange();
3290   return false;
3291 }
3292 
3293 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3294 /// This checks that the target supports __builtin_cpu_is and
3295 /// that the string argument is constant and valid.
3296 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
3297   Expr *Arg = TheCall->getArg(0);
3298 
3299   // Check if the argument is a string literal.
3300   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3301     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3302            << Arg->getSourceRange();
3303 
3304   // Check the contents of the string.
3305   StringRef Feature =
3306       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3307   if (!S.Context.getTargetInfo().validateCpuIs(Feature))
3308     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3309            << Arg->getSourceRange();
3310   return false;
3311 }
3312 
3313 // Check if the rounding mode is legal.
3314 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3315   // Indicates if this instruction has rounding control or just SAE.
3316   bool HasRC = false;
3317 
3318   unsigned ArgNum = 0;
3319   switch (BuiltinID) {
3320   default:
3321     return false;
3322   case X86::BI__builtin_ia32_vcvttsd2si32:
3323   case X86::BI__builtin_ia32_vcvttsd2si64:
3324   case X86::BI__builtin_ia32_vcvttsd2usi32:
3325   case X86::BI__builtin_ia32_vcvttsd2usi64:
3326   case X86::BI__builtin_ia32_vcvttss2si32:
3327   case X86::BI__builtin_ia32_vcvttss2si64:
3328   case X86::BI__builtin_ia32_vcvttss2usi32:
3329   case X86::BI__builtin_ia32_vcvttss2usi64:
3330     ArgNum = 1;
3331     break;
3332   case X86::BI__builtin_ia32_maxpd512:
3333   case X86::BI__builtin_ia32_maxps512:
3334   case X86::BI__builtin_ia32_minpd512:
3335   case X86::BI__builtin_ia32_minps512:
3336     ArgNum = 2;
3337     break;
3338   case X86::BI__builtin_ia32_cvtps2pd512_mask:
3339   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3340   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3341   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3342   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3343   case X86::BI__builtin_ia32_cvttps2dq512_mask:
3344   case X86::BI__builtin_ia32_cvttps2qq512_mask:
3345   case X86::BI__builtin_ia32_cvttps2udq512_mask:
3346   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3347   case X86::BI__builtin_ia32_exp2pd_mask:
3348   case X86::BI__builtin_ia32_exp2ps_mask:
3349   case X86::BI__builtin_ia32_getexppd512_mask:
3350   case X86::BI__builtin_ia32_getexpps512_mask:
3351   case X86::BI__builtin_ia32_rcp28pd_mask:
3352   case X86::BI__builtin_ia32_rcp28ps_mask:
3353   case X86::BI__builtin_ia32_rsqrt28pd_mask:
3354   case X86::BI__builtin_ia32_rsqrt28ps_mask:
3355   case X86::BI__builtin_ia32_vcomisd:
3356   case X86::BI__builtin_ia32_vcomiss:
3357   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3358     ArgNum = 3;
3359     break;
3360   case X86::BI__builtin_ia32_cmppd512_mask:
3361   case X86::BI__builtin_ia32_cmpps512_mask:
3362   case X86::BI__builtin_ia32_cmpsd_mask:
3363   case X86::BI__builtin_ia32_cmpss_mask:
3364   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3365   case X86::BI__builtin_ia32_getexpsd128_round_mask:
3366   case X86::BI__builtin_ia32_getexpss128_round_mask:
3367   case X86::BI__builtin_ia32_maxsd_round_mask:
3368   case X86::BI__builtin_ia32_maxss_round_mask:
3369   case X86::BI__builtin_ia32_minsd_round_mask:
3370   case X86::BI__builtin_ia32_minss_round_mask:
3371   case X86::BI__builtin_ia32_rcp28sd_round_mask:
3372   case X86::BI__builtin_ia32_rcp28ss_round_mask:
3373   case X86::BI__builtin_ia32_reducepd512_mask:
3374   case X86::BI__builtin_ia32_reduceps512_mask:
3375   case X86::BI__builtin_ia32_rndscalepd_mask:
3376   case X86::BI__builtin_ia32_rndscaleps_mask:
3377   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3378   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3379     ArgNum = 4;
3380     break;
3381   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3382   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3383   case X86::BI__builtin_ia32_fixupimmps512_mask:
3384   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3385   case X86::BI__builtin_ia32_fixupimmsd_mask:
3386   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3387   case X86::BI__builtin_ia32_fixupimmss_mask:
3388   case X86::BI__builtin_ia32_fixupimmss_maskz:
3389   case X86::BI__builtin_ia32_rangepd512_mask:
3390   case X86::BI__builtin_ia32_rangeps512_mask:
3391   case X86::BI__builtin_ia32_rangesd128_round_mask:
3392   case X86::BI__builtin_ia32_rangess128_round_mask:
3393   case X86::BI__builtin_ia32_reducesd_mask:
3394   case X86::BI__builtin_ia32_reducess_mask:
3395   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3396   case X86::BI__builtin_ia32_rndscaless_round_mask:
3397     ArgNum = 5;
3398     break;
3399   case X86::BI__builtin_ia32_vcvtsd2si64:
3400   case X86::BI__builtin_ia32_vcvtsd2si32:
3401   case X86::BI__builtin_ia32_vcvtsd2usi32:
3402   case X86::BI__builtin_ia32_vcvtsd2usi64:
3403   case X86::BI__builtin_ia32_vcvtss2si32:
3404   case X86::BI__builtin_ia32_vcvtss2si64:
3405   case X86::BI__builtin_ia32_vcvtss2usi32:
3406   case X86::BI__builtin_ia32_vcvtss2usi64:
3407   case X86::BI__builtin_ia32_sqrtpd512:
3408   case X86::BI__builtin_ia32_sqrtps512:
3409     ArgNum = 1;
3410     HasRC = true;
3411     break;
3412   case X86::BI__builtin_ia32_addpd512:
3413   case X86::BI__builtin_ia32_addps512:
3414   case X86::BI__builtin_ia32_divpd512:
3415   case X86::BI__builtin_ia32_divps512:
3416   case X86::BI__builtin_ia32_mulpd512:
3417   case X86::BI__builtin_ia32_mulps512:
3418   case X86::BI__builtin_ia32_subpd512:
3419   case X86::BI__builtin_ia32_subps512:
3420   case X86::BI__builtin_ia32_cvtsi2sd64:
3421   case X86::BI__builtin_ia32_cvtsi2ss32:
3422   case X86::BI__builtin_ia32_cvtsi2ss64:
3423   case X86::BI__builtin_ia32_cvtusi2sd64:
3424   case X86::BI__builtin_ia32_cvtusi2ss32:
3425   case X86::BI__builtin_ia32_cvtusi2ss64:
3426     ArgNum = 2;
3427     HasRC = true;
3428     break;
3429   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3430   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3431   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
3432   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3433   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3434   case X86::BI__builtin_ia32_cvtps2qq512_mask:
3435   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3436   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3437   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3438   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3439   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3440     ArgNum = 3;
3441     HasRC = true;
3442     break;
3443   case X86::BI__builtin_ia32_addss_round_mask:
3444   case X86::BI__builtin_ia32_addsd_round_mask:
3445   case X86::BI__builtin_ia32_divss_round_mask:
3446   case X86::BI__builtin_ia32_divsd_round_mask:
3447   case X86::BI__builtin_ia32_mulss_round_mask:
3448   case X86::BI__builtin_ia32_mulsd_round_mask:
3449   case X86::BI__builtin_ia32_subss_round_mask:
3450   case X86::BI__builtin_ia32_subsd_round_mask:
3451   case X86::BI__builtin_ia32_scalefpd512_mask:
3452   case X86::BI__builtin_ia32_scalefps512_mask:
3453   case X86::BI__builtin_ia32_scalefsd_round_mask:
3454   case X86::BI__builtin_ia32_scalefss_round_mask:
3455   case X86::BI__builtin_ia32_getmantpd512_mask:
3456   case X86::BI__builtin_ia32_getmantps512_mask:
3457   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3458   case X86::BI__builtin_ia32_sqrtsd_round_mask:
3459   case X86::BI__builtin_ia32_sqrtss_round_mask:
3460   case X86::BI__builtin_ia32_vfmaddsd3_mask:
3461   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3462   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
3463   case X86::BI__builtin_ia32_vfmaddss3_mask:
3464   case X86::BI__builtin_ia32_vfmaddss3_maskz:
3465   case X86::BI__builtin_ia32_vfmaddss3_mask3:
3466   case X86::BI__builtin_ia32_vfmaddpd512_mask:
3467   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
3468   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
3469   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
3470   case X86::BI__builtin_ia32_vfmaddps512_mask:
3471   case X86::BI__builtin_ia32_vfmaddps512_maskz:
3472   case X86::BI__builtin_ia32_vfmaddps512_mask3:
3473   case X86::BI__builtin_ia32_vfmsubps512_mask3:
3474   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
3475   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
3476   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
3477   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
3478   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
3479   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
3480   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
3481   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
3482     ArgNum = 4;
3483     HasRC = true;
3484     break;
3485   case X86::BI__builtin_ia32_getmantsd_round_mask:
3486   case X86::BI__builtin_ia32_getmantss_round_mask:
3487     ArgNum = 5;
3488     HasRC = true;
3489     break;
3490   }
3491 
3492   llvm::APSInt Result;
3493 
3494   // We can't check the value of a dependent argument.
3495   Expr *Arg = TheCall->getArg(ArgNum);
3496   if (Arg->isTypeDependent() || Arg->isValueDependent())
3497     return false;
3498 
3499   // Check constant-ness first.
3500   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3501     return true;
3502 
3503   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
3504   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
3505   // combined with ROUND_NO_EXC.
3506   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
3507       Result == 8/*ROUND_NO_EXC*/ ||
3508       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
3509     return false;
3510 
3511   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
3512          << Arg->getSourceRange();
3513 }
3514 
3515 // Check if the gather/scatter scale is legal.
3516 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
3517                                              CallExpr *TheCall) {
3518   unsigned ArgNum = 0;
3519   switch (BuiltinID) {
3520   default:
3521     return false;
3522   case X86::BI__builtin_ia32_gatherpfdpd:
3523   case X86::BI__builtin_ia32_gatherpfdps:
3524   case X86::BI__builtin_ia32_gatherpfqpd:
3525   case X86::BI__builtin_ia32_gatherpfqps:
3526   case X86::BI__builtin_ia32_scatterpfdpd:
3527   case X86::BI__builtin_ia32_scatterpfdps:
3528   case X86::BI__builtin_ia32_scatterpfqpd:
3529   case X86::BI__builtin_ia32_scatterpfqps:
3530     ArgNum = 3;
3531     break;
3532   case X86::BI__builtin_ia32_gatherd_pd:
3533   case X86::BI__builtin_ia32_gatherd_pd256:
3534   case X86::BI__builtin_ia32_gatherq_pd:
3535   case X86::BI__builtin_ia32_gatherq_pd256:
3536   case X86::BI__builtin_ia32_gatherd_ps:
3537   case X86::BI__builtin_ia32_gatherd_ps256:
3538   case X86::BI__builtin_ia32_gatherq_ps:
3539   case X86::BI__builtin_ia32_gatherq_ps256:
3540   case X86::BI__builtin_ia32_gatherd_q:
3541   case X86::BI__builtin_ia32_gatherd_q256:
3542   case X86::BI__builtin_ia32_gatherq_q:
3543   case X86::BI__builtin_ia32_gatherq_q256:
3544   case X86::BI__builtin_ia32_gatherd_d:
3545   case X86::BI__builtin_ia32_gatherd_d256:
3546   case X86::BI__builtin_ia32_gatherq_d:
3547   case X86::BI__builtin_ia32_gatherq_d256:
3548   case X86::BI__builtin_ia32_gather3div2df:
3549   case X86::BI__builtin_ia32_gather3div2di:
3550   case X86::BI__builtin_ia32_gather3div4df:
3551   case X86::BI__builtin_ia32_gather3div4di:
3552   case X86::BI__builtin_ia32_gather3div4sf:
3553   case X86::BI__builtin_ia32_gather3div4si:
3554   case X86::BI__builtin_ia32_gather3div8sf:
3555   case X86::BI__builtin_ia32_gather3div8si:
3556   case X86::BI__builtin_ia32_gather3siv2df:
3557   case X86::BI__builtin_ia32_gather3siv2di:
3558   case X86::BI__builtin_ia32_gather3siv4df:
3559   case X86::BI__builtin_ia32_gather3siv4di:
3560   case X86::BI__builtin_ia32_gather3siv4sf:
3561   case X86::BI__builtin_ia32_gather3siv4si:
3562   case X86::BI__builtin_ia32_gather3siv8sf:
3563   case X86::BI__builtin_ia32_gather3siv8si:
3564   case X86::BI__builtin_ia32_gathersiv8df:
3565   case X86::BI__builtin_ia32_gathersiv16sf:
3566   case X86::BI__builtin_ia32_gatherdiv8df:
3567   case X86::BI__builtin_ia32_gatherdiv16sf:
3568   case X86::BI__builtin_ia32_gathersiv8di:
3569   case X86::BI__builtin_ia32_gathersiv16si:
3570   case X86::BI__builtin_ia32_gatherdiv8di:
3571   case X86::BI__builtin_ia32_gatherdiv16si:
3572   case X86::BI__builtin_ia32_scatterdiv2df:
3573   case X86::BI__builtin_ia32_scatterdiv2di:
3574   case X86::BI__builtin_ia32_scatterdiv4df:
3575   case X86::BI__builtin_ia32_scatterdiv4di:
3576   case X86::BI__builtin_ia32_scatterdiv4sf:
3577   case X86::BI__builtin_ia32_scatterdiv4si:
3578   case X86::BI__builtin_ia32_scatterdiv8sf:
3579   case X86::BI__builtin_ia32_scatterdiv8si:
3580   case X86::BI__builtin_ia32_scattersiv2df:
3581   case X86::BI__builtin_ia32_scattersiv2di:
3582   case X86::BI__builtin_ia32_scattersiv4df:
3583   case X86::BI__builtin_ia32_scattersiv4di:
3584   case X86::BI__builtin_ia32_scattersiv4sf:
3585   case X86::BI__builtin_ia32_scattersiv4si:
3586   case X86::BI__builtin_ia32_scattersiv8sf:
3587   case X86::BI__builtin_ia32_scattersiv8si:
3588   case X86::BI__builtin_ia32_scattersiv8df:
3589   case X86::BI__builtin_ia32_scattersiv16sf:
3590   case X86::BI__builtin_ia32_scatterdiv8df:
3591   case X86::BI__builtin_ia32_scatterdiv16sf:
3592   case X86::BI__builtin_ia32_scattersiv8di:
3593   case X86::BI__builtin_ia32_scattersiv16si:
3594   case X86::BI__builtin_ia32_scatterdiv8di:
3595   case X86::BI__builtin_ia32_scatterdiv16si:
3596     ArgNum = 4;
3597     break;
3598   }
3599 
3600   llvm::APSInt Result;
3601 
3602   // We can't check the value of a dependent argument.
3603   Expr *Arg = TheCall->getArg(ArgNum);
3604   if (Arg->isTypeDependent() || Arg->isValueDependent())
3605     return false;
3606 
3607   // Check constant-ness first.
3608   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3609     return true;
3610 
3611   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
3612     return false;
3613 
3614   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
3615          << Arg->getSourceRange();
3616 }
3617 
3618 static bool isX86_32Builtin(unsigned BuiltinID) {
3619   // These builtins only work on x86-32 targets.
3620   switch (BuiltinID) {
3621   case X86::BI__builtin_ia32_readeflags_u32:
3622   case X86::BI__builtin_ia32_writeeflags_u32:
3623     return true;
3624   }
3625 
3626   return false;
3627 }
3628 
3629 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3630   if (BuiltinID == X86::BI__builtin_cpu_supports)
3631     return SemaBuiltinCpuSupports(*this, TheCall);
3632 
3633   if (BuiltinID == X86::BI__builtin_cpu_is)
3634     return SemaBuiltinCpuIs(*this, TheCall);
3635 
3636   // Check for 32-bit only builtins on a 64-bit target.
3637   const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3638   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
3639     return Diag(TheCall->getCallee()->getBeginLoc(),
3640                 diag::err_32_bit_builtin_64_bit_tgt);
3641 
3642   // If the intrinsic has rounding or SAE make sure its valid.
3643   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
3644     return true;
3645 
3646   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
3647   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
3648     return true;
3649 
3650   // For intrinsics which take an immediate value as part of the instruction,
3651   // range check them here.
3652   int i = 0, l = 0, u = 0;
3653   switch (BuiltinID) {
3654   default:
3655     return false;
3656   case X86::BI__builtin_ia32_vec_ext_v2si:
3657   case X86::BI__builtin_ia32_vec_ext_v2di:
3658   case X86::BI__builtin_ia32_vextractf128_pd256:
3659   case X86::BI__builtin_ia32_vextractf128_ps256:
3660   case X86::BI__builtin_ia32_vextractf128_si256:
3661   case X86::BI__builtin_ia32_extract128i256:
3662   case X86::BI__builtin_ia32_extractf64x4_mask:
3663   case X86::BI__builtin_ia32_extracti64x4_mask:
3664   case X86::BI__builtin_ia32_extractf32x8_mask:
3665   case X86::BI__builtin_ia32_extracti32x8_mask:
3666   case X86::BI__builtin_ia32_extractf64x2_256_mask:
3667   case X86::BI__builtin_ia32_extracti64x2_256_mask:
3668   case X86::BI__builtin_ia32_extractf32x4_256_mask:
3669   case X86::BI__builtin_ia32_extracti32x4_256_mask:
3670     i = 1; l = 0; u = 1;
3671     break;
3672   case X86::BI__builtin_ia32_vec_set_v2di:
3673   case X86::BI__builtin_ia32_vinsertf128_pd256:
3674   case X86::BI__builtin_ia32_vinsertf128_ps256:
3675   case X86::BI__builtin_ia32_vinsertf128_si256:
3676   case X86::BI__builtin_ia32_insert128i256:
3677   case X86::BI__builtin_ia32_insertf32x8:
3678   case X86::BI__builtin_ia32_inserti32x8:
3679   case X86::BI__builtin_ia32_insertf64x4:
3680   case X86::BI__builtin_ia32_inserti64x4:
3681   case X86::BI__builtin_ia32_insertf64x2_256:
3682   case X86::BI__builtin_ia32_inserti64x2_256:
3683   case X86::BI__builtin_ia32_insertf32x4_256:
3684   case X86::BI__builtin_ia32_inserti32x4_256:
3685     i = 2; l = 0; u = 1;
3686     break;
3687   case X86::BI__builtin_ia32_vpermilpd:
3688   case X86::BI__builtin_ia32_vec_ext_v4hi:
3689   case X86::BI__builtin_ia32_vec_ext_v4si:
3690   case X86::BI__builtin_ia32_vec_ext_v4sf:
3691   case X86::BI__builtin_ia32_vec_ext_v4di:
3692   case X86::BI__builtin_ia32_extractf32x4_mask:
3693   case X86::BI__builtin_ia32_extracti32x4_mask:
3694   case X86::BI__builtin_ia32_extractf64x2_512_mask:
3695   case X86::BI__builtin_ia32_extracti64x2_512_mask:
3696     i = 1; l = 0; u = 3;
3697     break;
3698   case X86::BI_mm_prefetch:
3699   case X86::BI__builtin_ia32_vec_ext_v8hi:
3700   case X86::BI__builtin_ia32_vec_ext_v8si:
3701     i = 1; l = 0; u = 7;
3702     break;
3703   case X86::BI__builtin_ia32_sha1rnds4:
3704   case X86::BI__builtin_ia32_blendpd:
3705   case X86::BI__builtin_ia32_shufpd:
3706   case X86::BI__builtin_ia32_vec_set_v4hi:
3707   case X86::BI__builtin_ia32_vec_set_v4si:
3708   case X86::BI__builtin_ia32_vec_set_v4di:
3709   case X86::BI__builtin_ia32_shuf_f32x4_256:
3710   case X86::BI__builtin_ia32_shuf_f64x2_256:
3711   case X86::BI__builtin_ia32_shuf_i32x4_256:
3712   case X86::BI__builtin_ia32_shuf_i64x2_256:
3713   case X86::BI__builtin_ia32_insertf64x2_512:
3714   case X86::BI__builtin_ia32_inserti64x2_512:
3715   case X86::BI__builtin_ia32_insertf32x4:
3716   case X86::BI__builtin_ia32_inserti32x4:
3717     i = 2; l = 0; u = 3;
3718     break;
3719   case X86::BI__builtin_ia32_vpermil2pd:
3720   case X86::BI__builtin_ia32_vpermil2pd256:
3721   case X86::BI__builtin_ia32_vpermil2ps:
3722   case X86::BI__builtin_ia32_vpermil2ps256:
3723     i = 3; l = 0; u = 3;
3724     break;
3725   case X86::BI__builtin_ia32_cmpb128_mask:
3726   case X86::BI__builtin_ia32_cmpw128_mask:
3727   case X86::BI__builtin_ia32_cmpd128_mask:
3728   case X86::BI__builtin_ia32_cmpq128_mask:
3729   case X86::BI__builtin_ia32_cmpb256_mask:
3730   case X86::BI__builtin_ia32_cmpw256_mask:
3731   case X86::BI__builtin_ia32_cmpd256_mask:
3732   case X86::BI__builtin_ia32_cmpq256_mask:
3733   case X86::BI__builtin_ia32_cmpb512_mask:
3734   case X86::BI__builtin_ia32_cmpw512_mask:
3735   case X86::BI__builtin_ia32_cmpd512_mask:
3736   case X86::BI__builtin_ia32_cmpq512_mask:
3737   case X86::BI__builtin_ia32_ucmpb128_mask:
3738   case X86::BI__builtin_ia32_ucmpw128_mask:
3739   case X86::BI__builtin_ia32_ucmpd128_mask:
3740   case X86::BI__builtin_ia32_ucmpq128_mask:
3741   case X86::BI__builtin_ia32_ucmpb256_mask:
3742   case X86::BI__builtin_ia32_ucmpw256_mask:
3743   case X86::BI__builtin_ia32_ucmpd256_mask:
3744   case X86::BI__builtin_ia32_ucmpq256_mask:
3745   case X86::BI__builtin_ia32_ucmpb512_mask:
3746   case X86::BI__builtin_ia32_ucmpw512_mask:
3747   case X86::BI__builtin_ia32_ucmpd512_mask:
3748   case X86::BI__builtin_ia32_ucmpq512_mask:
3749   case X86::BI__builtin_ia32_vpcomub:
3750   case X86::BI__builtin_ia32_vpcomuw:
3751   case X86::BI__builtin_ia32_vpcomud:
3752   case X86::BI__builtin_ia32_vpcomuq:
3753   case X86::BI__builtin_ia32_vpcomb:
3754   case X86::BI__builtin_ia32_vpcomw:
3755   case X86::BI__builtin_ia32_vpcomd:
3756   case X86::BI__builtin_ia32_vpcomq:
3757   case X86::BI__builtin_ia32_vec_set_v8hi:
3758   case X86::BI__builtin_ia32_vec_set_v8si:
3759     i = 2; l = 0; u = 7;
3760     break;
3761   case X86::BI__builtin_ia32_vpermilpd256:
3762   case X86::BI__builtin_ia32_roundps:
3763   case X86::BI__builtin_ia32_roundpd:
3764   case X86::BI__builtin_ia32_roundps256:
3765   case X86::BI__builtin_ia32_roundpd256:
3766   case X86::BI__builtin_ia32_getmantpd128_mask:
3767   case X86::BI__builtin_ia32_getmantpd256_mask:
3768   case X86::BI__builtin_ia32_getmantps128_mask:
3769   case X86::BI__builtin_ia32_getmantps256_mask:
3770   case X86::BI__builtin_ia32_getmantpd512_mask:
3771   case X86::BI__builtin_ia32_getmantps512_mask:
3772   case X86::BI__builtin_ia32_vec_ext_v16qi:
3773   case X86::BI__builtin_ia32_vec_ext_v16hi:
3774     i = 1; l = 0; u = 15;
3775     break;
3776   case X86::BI__builtin_ia32_pblendd128:
3777   case X86::BI__builtin_ia32_blendps:
3778   case X86::BI__builtin_ia32_blendpd256:
3779   case X86::BI__builtin_ia32_shufpd256:
3780   case X86::BI__builtin_ia32_roundss:
3781   case X86::BI__builtin_ia32_roundsd:
3782   case X86::BI__builtin_ia32_rangepd128_mask:
3783   case X86::BI__builtin_ia32_rangepd256_mask:
3784   case X86::BI__builtin_ia32_rangepd512_mask:
3785   case X86::BI__builtin_ia32_rangeps128_mask:
3786   case X86::BI__builtin_ia32_rangeps256_mask:
3787   case X86::BI__builtin_ia32_rangeps512_mask:
3788   case X86::BI__builtin_ia32_getmantsd_round_mask:
3789   case X86::BI__builtin_ia32_getmantss_round_mask:
3790   case X86::BI__builtin_ia32_vec_set_v16qi:
3791   case X86::BI__builtin_ia32_vec_set_v16hi:
3792     i = 2; l = 0; u = 15;
3793     break;
3794   case X86::BI__builtin_ia32_vec_ext_v32qi:
3795     i = 1; l = 0; u = 31;
3796     break;
3797   case X86::BI__builtin_ia32_cmpps:
3798   case X86::BI__builtin_ia32_cmpss:
3799   case X86::BI__builtin_ia32_cmppd:
3800   case X86::BI__builtin_ia32_cmpsd:
3801   case X86::BI__builtin_ia32_cmpps256:
3802   case X86::BI__builtin_ia32_cmppd256:
3803   case X86::BI__builtin_ia32_cmpps128_mask:
3804   case X86::BI__builtin_ia32_cmppd128_mask:
3805   case X86::BI__builtin_ia32_cmpps256_mask:
3806   case X86::BI__builtin_ia32_cmppd256_mask:
3807   case X86::BI__builtin_ia32_cmpps512_mask:
3808   case X86::BI__builtin_ia32_cmppd512_mask:
3809   case X86::BI__builtin_ia32_cmpsd_mask:
3810   case X86::BI__builtin_ia32_cmpss_mask:
3811   case X86::BI__builtin_ia32_vec_set_v32qi:
3812     i = 2; l = 0; u = 31;
3813     break;
3814   case X86::BI__builtin_ia32_permdf256:
3815   case X86::BI__builtin_ia32_permdi256:
3816   case X86::BI__builtin_ia32_permdf512:
3817   case X86::BI__builtin_ia32_permdi512:
3818   case X86::BI__builtin_ia32_vpermilps:
3819   case X86::BI__builtin_ia32_vpermilps256:
3820   case X86::BI__builtin_ia32_vpermilpd512:
3821   case X86::BI__builtin_ia32_vpermilps512:
3822   case X86::BI__builtin_ia32_pshufd:
3823   case X86::BI__builtin_ia32_pshufd256:
3824   case X86::BI__builtin_ia32_pshufd512:
3825   case X86::BI__builtin_ia32_pshufhw:
3826   case X86::BI__builtin_ia32_pshufhw256:
3827   case X86::BI__builtin_ia32_pshufhw512:
3828   case X86::BI__builtin_ia32_pshuflw:
3829   case X86::BI__builtin_ia32_pshuflw256:
3830   case X86::BI__builtin_ia32_pshuflw512:
3831   case X86::BI__builtin_ia32_vcvtps2ph:
3832   case X86::BI__builtin_ia32_vcvtps2ph_mask:
3833   case X86::BI__builtin_ia32_vcvtps2ph256:
3834   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
3835   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
3836   case X86::BI__builtin_ia32_rndscaleps_128_mask:
3837   case X86::BI__builtin_ia32_rndscalepd_128_mask:
3838   case X86::BI__builtin_ia32_rndscaleps_256_mask:
3839   case X86::BI__builtin_ia32_rndscalepd_256_mask:
3840   case X86::BI__builtin_ia32_rndscaleps_mask:
3841   case X86::BI__builtin_ia32_rndscalepd_mask:
3842   case X86::BI__builtin_ia32_reducepd128_mask:
3843   case X86::BI__builtin_ia32_reducepd256_mask:
3844   case X86::BI__builtin_ia32_reducepd512_mask:
3845   case X86::BI__builtin_ia32_reduceps128_mask:
3846   case X86::BI__builtin_ia32_reduceps256_mask:
3847   case X86::BI__builtin_ia32_reduceps512_mask:
3848   case X86::BI__builtin_ia32_prold512:
3849   case X86::BI__builtin_ia32_prolq512:
3850   case X86::BI__builtin_ia32_prold128:
3851   case X86::BI__builtin_ia32_prold256:
3852   case X86::BI__builtin_ia32_prolq128:
3853   case X86::BI__builtin_ia32_prolq256:
3854   case X86::BI__builtin_ia32_prord512:
3855   case X86::BI__builtin_ia32_prorq512:
3856   case X86::BI__builtin_ia32_prord128:
3857   case X86::BI__builtin_ia32_prord256:
3858   case X86::BI__builtin_ia32_prorq128:
3859   case X86::BI__builtin_ia32_prorq256:
3860   case X86::BI__builtin_ia32_fpclasspd128_mask:
3861   case X86::BI__builtin_ia32_fpclasspd256_mask:
3862   case X86::BI__builtin_ia32_fpclassps128_mask:
3863   case X86::BI__builtin_ia32_fpclassps256_mask:
3864   case X86::BI__builtin_ia32_fpclassps512_mask:
3865   case X86::BI__builtin_ia32_fpclasspd512_mask:
3866   case X86::BI__builtin_ia32_fpclasssd_mask:
3867   case X86::BI__builtin_ia32_fpclassss_mask:
3868   case X86::BI__builtin_ia32_pslldqi128_byteshift:
3869   case X86::BI__builtin_ia32_pslldqi256_byteshift:
3870   case X86::BI__builtin_ia32_pslldqi512_byteshift:
3871   case X86::BI__builtin_ia32_psrldqi128_byteshift:
3872   case X86::BI__builtin_ia32_psrldqi256_byteshift:
3873   case X86::BI__builtin_ia32_psrldqi512_byteshift:
3874   case X86::BI__builtin_ia32_kshiftliqi:
3875   case X86::BI__builtin_ia32_kshiftlihi:
3876   case X86::BI__builtin_ia32_kshiftlisi:
3877   case X86::BI__builtin_ia32_kshiftlidi:
3878   case X86::BI__builtin_ia32_kshiftriqi:
3879   case X86::BI__builtin_ia32_kshiftrihi:
3880   case X86::BI__builtin_ia32_kshiftrisi:
3881   case X86::BI__builtin_ia32_kshiftridi:
3882     i = 1; l = 0; u = 255;
3883     break;
3884   case X86::BI__builtin_ia32_vperm2f128_pd256:
3885   case X86::BI__builtin_ia32_vperm2f128_ps256:
3886   case X86::BI__builtin_ia32_vperm2f128_si256:
3887   case X86::BI__builtin_ia32_permti256:
3888   case X86::BI__builtin_ia32_pblendw128:
3889   case X86::BI__builtin_ia32_pblendw256:
3890   case X86::BI__builtin_ia32_blendps256:
3891   case X86::BI__builtin_ia32_pblendd256:
3892   case X86::BI__builtin_ia32_palignr128:
3893   case X86::BI__builtin_ia32_palignr256:
3894   case X86::BI__builtin_ia32_palignr512:
3895   case X86::BI__builtin_ia32_alignq512:
3896   case X86::BI__builtin_ia32_alignd512:
3897   case X86::BI__builtin_ia32_alignd128:
3898   case X86::BI__builtin_ia32_alignd256:
3899   case X86::BI__builtin_ia32_alignq128:
3900   case X86::BI__builtin_ia32_alignq256:
3901   case X86::BI__builtin_ia32_vcomisd:
3902   case X86::BI__builtin_ia32_vcomiss:
3903   case X86::BI__builtin_ia32_shuf_f32x4:
3904   case X86::BI__builtin_ia32_shuf_f64x2:
3905   case X86::BI__builtin_ia32_shuf_i32x4:
3906   case X86::BI__builtin_ia32_shuf_i64x2:
3907   case X86::BI__builtin_ia32_shufpd512:
3908   case X86::BI__builtin_ia32_shufps:
3909   case X86::BI__builtin_ia32_shufps256:
3910   case X86::BI__builtin_ia32_shufps512:
3911   case X86::BI__builtin_ia32_dbpsadbw128:
3912   case X86::BI__builtin_ia32_dbpsadbw256:
3913   case X86::BI__builtin_ia32_dbpsadbw512:
3914   case X86::BI__builtin_ia32_vpshldd128:
3915   case X86::BI__builtin_ia32_vpshldd256:
3916   case X86::BI__builtin_ia32_vpshldd512:
3917   case X86::BI__builtin_ia32_vpshldq128:
3918   case X86::BI__builtin_ia32_vpshldq256:
3919   case X86::BI__builtin_ia32_vpshldq512:
3920   case X86::BI__builtin_ia32_vpshldw128:
3921   case X86::BI__builtin_ia32_vpshldw256:
3922   case X86::BI__builtin_ia32_vpshldw512:
3923   case X86::BI__builtin_ia32_vpshrdd128:
3924   case X86::BI__builtin_ia32_vpshrdd256:
3925   case X86::BI__builtin_ia32_vpshrdd512:
3926   case X86::BI__builtin_ia32_vpshrdq128:
3927   case X86::BI__builtin_ia32_vpshrdq256:
3928   case X86::BI__builtin_ia32_vpshrdq512:
3929   case X86::BI__builtin_ia32_vpshrdw128:
3930   case X86::BI__builtin_ia32_vpshrdw256:
3931   case X86::BI__builtin_ia32_vpshrdw512:
3932     i = 2; l = 0; u = 255;
3933     break;
3934   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3935   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3936   case X86::BI__builtin_ia32_fixupimmps512_mask:
3937   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3938   case X86::BI__builtin_ia32_fixupimmsd_mask:
3939   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3940   case X86::BI__builtin_ia32_fixupimmss_mask:
3941   case X86::BI__builtin_ia32_fixupimmss_maskz:
3942   case X86::BI__builtin_ia32_fixupimmpd128_mask:
3943   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
3944   case X86::BI__builtin_ia32_fixupimmpd256_mask:
3945   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
3946   case X86::BI__builtin_ia32_fixupimmps128_mask:
3947   case X86::BI__builtin_ia32_fixupimmps128_maskz:
3948   case X86::BI__builtin_ia32_fixupimmps256_mask:
3949   case X86::BI__builtin_ia32_fixupimmps256_maskz:
3950   case X86::BI__builtin_ia32_pternlogd512_mask:
3951   case X86::BI__builtin_ia32_pternlogd512_maskz:
3952   case X86::BI__builtin_ia32_pternlogq512_mask:
3953   case X86::BI__builtin_ia32_pternlogq512_maskz:
3954   case X86::BI__builtin_ia32_pternlogd128_mask:
3955   case X86::BI__builtin_ia32_pternlogd128_maskz:
3956   case X86::BI__builtin_ia32_pternlogd256_mask:
3957   case X86::BI__builtin_ia32_pternlogd256_maskz:
3958   case X86::BI__builtin_ia32_pternlogq128_mask:
3959   case X86::BI__builtin_ia32_pternlogq128_maskz:
3960   case X86::BI__builtin_ia32_pternlogq256_mask:
3961   case X86::BI__builtin_ia32_pternlogq256_maskz:
3962     i = 3; l = 0; u = 255;
3963     break;
3964   case X86::BI__builtin_ia32_gatherpfdpd:
3965   case X86::BI__builtin_ia32_gatherpfdps:
3966   case X86::BI__builtin_ia32_gatherpfqpd:
3967   case X86::BI__builtin_ia32_gatherpfqps:
3968   case X86::BI__builtin_ia32_scatterpfdpd:
3969   case X86::BI__builtin_ia32_scatterpfdps:
3970   case X86::BI__builtin_ia32_scatterpfqpd:
3971   case X86::BI__builtin_ia32_scatterpfqps:
3972     i = 4; l = 2; u = 3;
3973     break;
3974   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3975   case X86::BI__builtin_ia32_rndscaless_round_mask:
3976     i = 4; l = 0; u = 255;
3977     break;
3978   }
3979 
3980   // Note that we don't force a hard error on the range check here, allowing
3981   // template-generated or macro-generated dead code to potentially have out-of-
3982   // range values. These need to code generate, but don't need to necessarily
3983   // make any sense. We use a warning that defaults to an error.
3984   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
3985 }
3986 
3987 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
3988 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
3989 /// Returns true when the format fits the function and the FormatStringInfo has
3990 /// been populated.
3991 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
3992                                FormatStringInfo *FSI) {
3993   FSI->HasVAListArg = Format->getFirstArg() == 0;
3994   FSI->FormatIdx = Format->getFormatIdx() - 1;
3995   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
3996 
3997   // The way the format attribute works in GCC, the implicit this argument
3998   // of member functions is counted. However, it doesn't appear in our own
3999   // lists, so decrement format_idx in that case.
4000   if (IsCXXMember) {
4001     if(FSI->FormatIdx == 0)
4002       return false;
4003     --FSI->FormatIdx;
4004     if (FSI->FirstDataArg != 0)
4005       --FSI->FirstDataArg;
4006   }
4007   return true;
4008 }
4009 
4010 /// Checks if a the given expression evaluates to null.
4011 ///
4012 /// Returns true if the value evaluates to null.
4013 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4014   // If the expression has non-null type, it doesn't evaluate to null.
4015   if (auto nullability
4016         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
4017     if (*nullability == NullabilityKind::NonNull)
4018       return false;
4019   }
4020 
4021   // As a special case, transparent unions initialized with zero are
4022   // considered null for the purposes of the nonnull attribute.
4023   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
4024     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
4025       if (const CompoundLiteralExpr *CLE =
4026           dyn_cast<CompoundLiteralExpr>(Expr))
4027         if (const InitListExpr *ILE =
4028             dyn_cast<InitListExpr>(CLE->getInitializer()))
4029           Expr = ILE->getInit(0);
4030   }
4031 
4032   bool Result;
4033   return (!Expr->isValueDependent() &&
4034           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
4035           !Result);
4036 }
4037 
4038 static void CheckNonNullArgument(Sema &S,
4039                                  const Expr *ArgExpr,
4040                                  SourceLocation CallSiteLoc) {
4041   if (CheckNonNullExpr(S, ArgExpr))
4042     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4043            S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
4044 }
4045 
4046 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
4047   FormatStringInfo FSI;
4048   if ((GetFormatStringType(Format) == FST_NSString) &&
4049       getFormatStringInfo(Format, false, &FSI)) {
4050     Idx = FSI.FormatIdx;
4051     return true;
4052   }
4053   return false;
4054 }
4055 
4056 /// Diagnose use of %s directive in an NSString which is being passed
4057 /// as formatting string to formatting method.
4058 static void
4059 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
4060                                         const NamedDecl *FDecl,
4061                                         Expr **Args,
4062                                         unsigned NumArgs) {
4063   unsigned Idx = 0;
4064   bool Format = false;
4065   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
4066   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
4067     Idx = 2;
4068     Format = true;
4069   }
4070   else
4071     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4072       if (S.GetFormatNSStringIdx(I, Idx)) {
4073         Format = true;
4074         break;
4075       }
4076     }
4077   if (!Format || NumArgs <= Idx)
4078     return;
4079   const Expr *FormatExpr = Args[Idx];
4080   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4081     FormatExpr = CSCE->getSubExpr();
4082   const StringLiteral *FormatString;
4083   if (const ObjCStringLiteral *OSL =
4084       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4085     FormatString = OSL->getString();
4086   else
4087     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4088   if (!FormatString)
4089     return;
4090   if (S.FormatStringHasSArg(FormatString)) {
4091     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4092       << "%s" << 1 << 1;
4093     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4094       << FDecl->getDeclName();
4095   }
4096 }
4097 
4098 /// Determine whether the given type has a non-null nullability annotation.
4099 static bool isNonNullType(ASTContext &ctx, QualType type) {
4100   if (auto nullability = type->getNullability(ctx))
4101     return *nullability == NullabilityKind::NonNull;
4102 
4103   return false;
4104 }
4105 
4106 static void CheckNonNullArguments(Sema &S,
4107                                   const NamedDecl *FDecl,
4108                                   const FunctionProtoType *Proto,
4109                                   ArrayRef<const Expr *> Args,
4110                                   SourceLocation CallSiteLoc) {
4111   assert((FDecl || Proto) && "Need a function declaration or prototype");
4112 
4113   // Check the attributes attached to the method/function itself.
4114   llvm::SmallBitVector NonNullArgs;
4115   if (FDecl) {
4116     // Handle the nonnull attribute on the function/method declaration itself.
4117     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4118       if (!NonNull->args_size()) {
4119         // Easy case: all pointer arguments are nonnull.
4120         for (const auto *Arg : Args)
4121           if (S.isValidPointerAttrType(Arg->getType()))
4122             CheckNonNullArgument(S, Arg, CallSiteLoc);
4123         return;
4124       }
4125 
4126       for (const ParamIdx &Idx : NonNull->args()) {
4127         unsigned IdxAST = Idx.getASTIndex();
4128         if (IdxAST >= Args.size())
4129           continue;
4130         if (NonNullArgs.empty())
4131           NonNullArgs.resize(Args.size());
4132         NonNullArgs.set(IdxAST);
4133       }
4134     }
4135   }
4136 
4137   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4138     // Handle the nonnull attribute on the parameters of the
4139     // function/method.
4140     ArrayRef<ParmVarDecl*> parms;
4141     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4142       parms = FD->parameters();
4143     else
4144       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4145 
4146     unsigned ParamIndex = 0;
4147     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4148          I != E; ++I, ++ParamIndex) {
4149       const ParmVarDecl *PVD = *I;
4150       if (PVD->hasAttr<NonNullAttr>() ||
4151           isNonNullType(S.Context, PVD->getType())) {
4152         if (NonNullArgs.empty())
4153           NonNullArgs.resize(Args.size());
4154 
4155         NonNullArgs.set(ParamIndex);
4156       }
4157     }
4158   } else {
4159     // If we have a non-function, non-method declaration but no
4160     // function prototype, try to dig out the function prototype.
4161     if (!Proto) {
4162       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4163         QualType type = VD->getType().getNonReferenceType();
4164         if (auto pointerType = type->getAs<PointerType>())
4165           type = pointerType->getPointeeType();
4166         else if (auto blockType = type->getAs<BlockPointerType>())
4167           type = blockType->getPointeeType();
4168         // FIXME: data member pointers?
4169 
4170         // Dig out the function prototype, if there is one.
4171         Proto = type->getAs<FunctionProtoType>();
4172       }
4173     }
4174 
4175     // Fill in non-null argument information from the nullability
4176     // information on the parameter types (if we have them).
4177     if (Proto) {
4178       unsigned Index = 0;
4179       for (auto paramType : Proto->getParamTypes()) {
4180         if (isNonNullType(S.Context, paramType)) {
4181           if (NonNullArgs.empty())
4182             NonNullArgs.resize(Args.size());
4183 
4184           NonNullArgs.set(Index);
4185         }
4186 
4187         ++Index;
4188       }
4189     }
4190   }
4191 
4192   // Check for non-null arguments.
4193   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4194        ArgIndex != ArgIndexEnd; ++ArgIndex) {
4195     if (NonNullArgs[ArgIndex])
4196       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4197   }
4198 }
4199 
4200 /// Handles the checks for format strings, non-POD arguments to vararg
4201 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4202 /// attributes.
4203 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4204                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
4205                      bool IsMemberFunction, SourceLocation Loc,
4206                      SourceRange Range, VariadicCallType CallType) {
4207   // FIXME: We should check as much as we can in the template definition.
4208   if (CurContext->isDependentContext())
4209     return;
4210 
4211   // Printf and scanf checking.
4212   llvm::SmallBitVector CheckedVarArgs;
4213   if (FDecl) {
4214     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4215       // Only create vector if there are format attributes.
4216       CheckedVarArgs.resize(Args.size());
4217 
4218       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4219                            CheckedVarArgs);
4220     }
4221   }
4222 
4223   // Refuse POD arguments that weren't caught by the format string
4224   // checks above.
4225   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4226   if (CallType != VariadicDoesNotApply &&
4227       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4228     unsigned NumParams = Proto ? Proto->getNumParams()
4229                        : FDecl && isa<FunctionDecl>(FDecl)
4230                            ? cast<FunctionDecl>(FDecl)->getNumParams()
4231                        : FDecl && isa<ObjCMethodDecl>(FDecl)
4232                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
4233                        : 0;
4234 
4235     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4236       // Args[ArgIdx] can be null in malformed code.
4237       if (const Expr *Arg = Args[ArgIdx]) {
4238         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4239           checkVariadicArgument(Arg, CallType);
4240       }
4241     }
4242   }
4243 
4244   if (FDecl || Proto) {
4245     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4246 
4247     // Type safety checking.
4248     if (FDecl) {
4249       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4250         CheckArgumentWithTypeTag(I, Args, Loc);
4251     }
4252   }
4253 
4254   if (FD)
4255     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4256 }
4257 
4258 /// CheckConstructorCall - Check a constructor call for correctness and safety
4259 /// properties not enforced by the C type system.
4260 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
4261                                 ArrayRef<const Expr *> Args,
4262                                 const FunctionProtoType *Proto,
4263                                 SourceLocation Loc) {
4264   VariadicCallType CallType =
4265     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4266   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4267             Loc, SourceRange(), CallType);
4268 }
4269 
4270 /// CheckFunctionCall - Check a direct function call for various correctness
4271 /// and safety properties not strictly enforced by the C type system.
4272 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4273                              const FunctionProtoType *Proto) {
4274   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4275                               isa<CXXMethodDecl>(FDecl);
4276   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4277                           IsMemberOperatorCall;
4278   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4279                                                   TheCall->getCallee());
4280   Expr** Args = TheCall->getArgs();
4281   unsigned NumArgs = TheCall->getNumArgs();
4282 
4283   Expr *ImplicitThis = nullptr;
4284   if (IsMemberOperatorCall) {
4285     // If this is a call to a member operator, hide the first argument
4286     // from checkCall.
4287     // FIXME: Our choice of AST representation here is less than ideal.
4288     ImplicitThis = Args[0];
4289     ++Args;
4290     --NumArgs;
4291   } else if (IsMemberFunction)
4292     ImplicitThis =
4293         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4294 
4295   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
4296             IsMemberFunction, TheCall->getRParenLoc(),
4297             TheCall->getCallee()->getSourceRange(), CallType);
4298 
4299   IdentifierInfo *FnInfo = FDecl->getIdentifier();
4300   // None of the checks below are needed for functions that don't have
4301   // simple names (e.g., C++ conversion functions).
4302   if (!FnInfo)
4303     return false;
4304 
4305   CheckAbsoluteValueFunction(TheCall, FDecl);
4306   CheckMaxUnsignedZero(TheCall, FDecl);
4307 
4308   if (getLangOpts().ObjC)
4309     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
4310 
4311   unsigned CMId = FDecl->getMemoryFunctionKind();
4312   if (CMId == 0)
4313     return false;
4314 
4315   // Handle memory setting and copying functions.
4316   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
4317     CheckStrlcpycatArguments(TheCall, FnInfo);
4318   else if (CMId == Builtin::BIstrncat)
4319     CheckStrncatArguments(TheCall, FnInfo);
4320   else
4321     CheckMemaccessArguments(TheCall, CMId, FnInfo);
4322 
4323   return false;
4324 }
4325 
4326 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
4327                                ArrayRef<const Expr *> Args) {
4328   VariadicCallType CallType =
4329       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
4330 
4331   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
4332             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
4333             CallType);
4334 
4335   return false;
4336 }
4337 
4338 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4339                             const FunctionProtoType *Proto) {
4340   QualType Ty;
4341   if (const auto *V = dyn_cast<VarDecl>(NDecl))
4342     Ty = V->getType().getNonReferenceType();
4343   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4344     Ty = F->getType().getNonReferenceType();
4345   else
4346     return false;
4347 
4348   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4349       !Ty->isFunctionProtoType())
4350     return false;
4351 
4352   VariadicCallType CallType;
4353   if (!Proto || !Proto->isVariadic()) {
4354     CallType = VariadicDoesNotApply;
4355   } else if (Ty->isBlockPointerType()) {
4356     CallType = VariadicBlock;
4357   } else { // Ty->isFunctionPointerType()
4358     CallType = VariadicFunction;
4359   }
4360 
4361   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4362             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4363             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4364             TheCall->getCallee()->getSourceRange(), CallType);
4365 
4366   return false;
4367 }
4368 
4369 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
4370 /// such as function pointers returned from functions.
4371 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4372   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4373                                                   TheCall->getCallee());
4374   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4375             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4376             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4377             TheCall->getCallee()->getSourceRange(), CallType);
4378 
4379   return false;
4380 }
4381 
4382 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4383   if (!llvm::isValidAtomicOrderingCABI(Ordering))
4384     return false;
4385 
4386   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4387   switch (Op) {
4388   case AtomicExpr::AO__c11_atomic_init:
4389   case AtomicExpr::AO__opencl_atomic_init:
4390     llvm_unreachable("There is no ordering argument for an init");
4391 
4392   case AtomicExpr::AO__c11_atomic_load:
4393   case AtomicExpr::AO__opencl_atomic_load:
4394   case AtomicExpr::AO__atomic_load_n:
4395   case AtomicExpr::AO__atomic_load:
4396     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4397            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4398 
4399   case AtomicExpr::AO__c11_atomic_store:
4400   case AtomicExpr::AO__opencl_atomic_store:
4401   case AtomicExpr::AO__atomic_store:
4402   case AtomicExpr::AO__atomic_store_n:
4403     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4404            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4405            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4406 
4407   default:
4408     return true;
4409   }
4410 }
4411 
4412 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
4413                                          AtomicExpr::AtomicOp Op) {
4414   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4415   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4416 
4417   // All the non-OpenCL operations take one of the following forms.
4418   // The OpenCL operations take the __c11 forms with one extra argument for
4419   // synchronization scope.
4420   enum {
4421     // C    __c11_atomic_init(A *, C)
4422     Init,
4423 
4424     // C    __c11_atomic_load(A *, int)
4425     Load,
4426 
4427     // void __atomic_load(A *, CP, int)
4428     LoadCopy,
4429 
4430     // void __atomic_store(A *, CP, int)
4431     Copy,
4432 
4433     // C    __c11_atomic_add(A *, M, int)
4434     Arithmetic,
4435 
4436     // C    __atomic_exchange_n(A *, CP, int)
4437     Xchg,
4438 
4439     // void __atomic_exchange(A *, C *, CP, int)
4440     GNUXchg,
4441 
4442     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4443     C11CmpXchg,
4444 
4445     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4446     GNUCmpXchg
4447   } Form = Init;
4448 
4449   const unsigned NumForm = GNUCmpXchg + 1;
4450   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
4451   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
4452   // where:
4453   //   C is an appropriate type,
4454   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4455   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4456   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4457   //   the int parameters are for orderings.
4458 
4459   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4460       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4461       "need to update code for modified forms");
4462   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
4463                     AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
4464                         AtomicExpr::AO__atomic_load,
4465                 "need to update code for modified C11 atomics");
4466   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
4467                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
4468   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
4469                Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
4470                IsOpenCL;
4471   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4472              Op == AtomicExpr::AO__atomic_store_n ||
4473              Op == AtomicExpr::AO__atomic_exchange_n ||
4474              Op == AtomicExpr::AO__atomic_compare_exchange_n;
4475   bool IsAddSub = false;
4476   bool IsMinMax = false;
4477 
4478   switch (Op) {
4479   case AtomicExpr::AO__c11_atomic_init:
4480   case AtomicExpr::AO__opencl_atomic_init:
4481     Form = Init;
4482     break;
4483 
4484   case AtomicExpr::AO__c11_atomic_load:
4485   case AtomicExpr::AO__opencl_atomic_load:
4486   case AtomicExpr::AO__atomic_load_n:
4487     Form = Load;
4488     break;
4489 
4490   case AtomicExpr::AO__atomic_load:
4491     Form = LoadCopy;
4492     break;
4493 
4494   case AtomicExpr::AO__c11_atomic_store:
4495   case AtomicExpr::AO__opencl_atomic_store:
4496   case AtomicExpr::AO__atomic_store:
4497   case AtomicExpr::AO__atomic_store_n:
4498     Form = Copy;
4499     break;
4500 
4501   case AtomicExpr::AO__c11_atomic_fetch_add:
4502   case AtomicExpr::AO__c11_atomic_fetch_sub:
4503   case AtomicExpr::AO__opencl_atomic_fetch_add:
4504   case AtomicExpr::AO__opencl_atomic_fetch_sub:
4505   case AtomicExpr::AO__opencl_atomic_fetch_min:
4506   case AtomicExpr::AO__opencl_atomic_fetch_max:
4507   case AtomicExpr::AO__atomic_fetch_add:
4508   case AtomicExpr::AO__atomic_fetch_sub:
4509   case AtomicExpr::AO__atomic_add_fetch:
4510   case AtomicExpr::AO__atomic_sub_fetch:
4511     IsAddSub = true;
4512     LLVM_FALLTHROUGH;
4513   case AtomicExpr::AO__c11_atomic_fetch_and:
4514   case AtomicExpr::AO__c11_atomic_fetch_or:
4515   case AtomicExpr::AO__c11_atomic_fetch_xor:
4516   case AtomicExpr::AO__opencl_atomic_fetch_and:
4517   case AtomicExpr::AO__opencl_atomic_fetch_or:
4518   case AtomicExpr::AO__opencl_atomic_fetch_xor:
4519   case AtomicExpr::AO__atomic_fetch_and:
4520   case AtomicExpr::AO__atomic_fetch_or:
4521   case AtomicExpr::AO__atomic_fetch_xor:
4522   case AtomicExpr::AO__atomic_fetch_nand:
4523   case AtomicExpr::AO__atomic_and_fetch:
4524   case AtomicExpr::AO__atomic_or_fetch:
4525   case AtomicExpr::AO__atomic_xor_fetch:
4526   case AtomicExpr::AO__atomic_nand_fetch:
4527     Form = Arithmetic;
4528     break;
4529 
4530   case AtomicExpr::AO__atomic_fetch_min:
4531   case AtomicExpr::AO__atomic_fetch_max:
4532     IsMinMax = true;
4533     Form = Arithmetic;
4534     break;
4535 
4536   case AtomicExpr::AO__c11_atomic_exchange:
4537   case AtomicExpr::AO__opencl_atomic_exchange:
4538   case AtomicExpr::AO__atomic_exchange_n:
4539     Form = Xchg;
4540     break;
4541 
4542   case AtomicExpr::AO__atomic_exchange:
4543     Form = GNUXchg;
4544     break;
4545 
4546   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4547   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4548   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4549   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4550     Form = C11CmpXchg;
4551     break;
4552 
4553   case AtomicExpr::AO__atomic_compare_exchange:
4554   case AtomicExpr::AO__atomic_compare_exchange_n:
4555     Form = GNUCmpXchg;
4556     break;
4557   }
4558 
4559   unsigned AdjustedNumArgs = NumArgs[Form];
4560   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
4561     ++AdjustedNumArgs;
4562   // Check we have the right number of arguments.
4563   if (TheCall->getNumArgs() < AdjustedNumArgs) {
4564     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
4565         << 0 << AdjustedNumArgs << TheCall->getNumArgs()
4566         << TheCall->getCallee()->getSourceRange();
4567     return ExprError();
4568   } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
4569     Diag(TheCall->getArg(AdjustedNumArgs)->getBeginLoc(),
4570          diag::err_typecheck_call_too_many_args)
4571         << 0 << AdjustedNumArgs << TheCall->getNumArgs()
4572         << TheCall->getCallee()->getSourceRange();
4573     return ExprError();
4574   }
4575 
4576   // Inspect the first argument of the atomic operation.
4577   Expr *Ptr = TheCall->getArg(0);
4578   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
4579   if (ConvertedPtr.isInvalid())
4580     return ExprError();
4581 
4582   Ptr = ConvertedPtr.get();
4583   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4584   if (!pointerType) {
4585     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
4586         << Ptr->getType() << Ptr->getSourceRange();
4587     return ExprError();
4588   }
4589 
4590   // For a __c11 builtin, this should be a pointer to an _Atomic type.
4591   QualType AtomTy = pointerType->getPointeeType(); // 'A'
4592   QualType ValType = AtomTy; // 'C'
4593   if (IsC11) {
4594     if (!AtomTy->isAtomicType()) {
4595       Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic)
4596           << Ptr->getType() << Ptr->getSourceRange();
4597       return ExprError();
4598     }
4599     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
4600         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
4601       Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_atomic)
4602           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4603           << Ptr->getSourceRange();
4604       return ExprError();
4605     }
4606     ValType = AtomTy->getAs<AtomicType>()->getValueType();
4607   } else if (Form != Load && Form != LoadCopy) {
4608     if (ValType.isConstQualified()) {
4609       Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_pointer)
4610           << Ptr->getType() << Ptr->getSourceRange();
4611       return ExprError();
4612     }
4613   }
4614 
4615   // For an arithmetic operation, the implied arithmetic must be well-formed.
4616   if (Form == Arithmetic) {
4617     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
4618     if (IsAddSub && !ValType->isIntegerType()
4619         && !ValType->isPointerType()) {
4620       Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4621           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4622       return ExprError();
4623     }
4624     if (IsMinMax) {
4625       const BuiltinType *BT = ValType->getAs<BuiltinType>();
4626       if (!BT || (BT->getKind() != BuiltinType::Int &&
4627                   BT->getKind() != BuiltinType::UInt)) {
4628         Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_int32_or_ptr);
4629         return ExprError();
4630       }
4631     }
4632     if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) {
4633       Diag(DRE->getBeginLoc(), diag::err_atomic_op_bitwise_needs_atomic_int)
4634           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4635       return ExprError();
4636     }
4637     if (IsC11 && ValType->isPointerType() &&
4638         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
4639                             diag::err_incomplete_type)) {
4640       return ExprError();
4641     }
4642   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
4643     // For __atomic_*_n operations, the value type must be a scalar integral or
4644     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
4645     Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4646         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4647     return ExprError();
4648   }
4649 
4650   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4651       !AtomTy->isScalarType()) {
4652     // For GNU atomics, require a trivially-copyable type. This is not part of
4653     // the GNU atomics specification, but we enforce it for sanity.
4654     Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_trivial_copy)
4655         << Ptr->getType() << Ptr->getSourceRange();
4656     return ExprError();
4657   }
4658 
4659   switch (ValType.getObjCLifetime()) {
4660   case Qualifiers::OCL_None:
4661   case Qualifiers::OCL_ExplicitNone:
4662     // okay
4663     break;
4664 
4665   case Qualifiers::OCL_Weak:
4666   case Qualifiers::OCL_Strong:
4667   case Qualifiers::OCL_Autoreleasing:
4668     // FIXME: Can this happen? By this point, ValType should be known
4669     // to be trivially copyable.
4670     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
4671         << ValType << Ptr->getSourceRange();
4672     return ExprError();
4673   }
4674 
4675   // All atomic operations have an overload which takes a pointer to a volatile
4676   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
4677   // into the result or the other operands. Similarly atomic_load takes a
4678   // pointer to a const 'A'.
4679   ValType.removeLocalVolatile();
4680   ValType.removeLocalConst();
4681   QualType ResultType = ValType;
4682   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
4683       Form == Init)
4684     ResultType = Context.VoidTy;
4685   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
4686     ResultType = Context.BoolTy;
4687 
4688   // The type of a parameter passed 'by value'. In the GNU atomics, such
4689   // arguments are actually passed as pointers.
4690   QualType ByValType = ValType; // 'CP'
4691   bool IsPassedByAddress = false;
4692   if (!IsC11 && !IsN) {
4693     ByValType = Ptr->getType();
4694     IsPassedByAddress = true;
4695   }
4696 
4697   // The first argument's non-CV pointer type is used to deduce the type of
4698   // subsequent arguments, except for:
4699   //  - weak flag (always converted to bool)
4700   //  - memory order (always converted to int)
4701   //  - scope  (always converted to int)
4702   for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
4703     QualType Ty;
4704     if (i < NumVals[Form] + 1) {
4705       switch (i) {
4706       case 0:
4707         // The first argument is always a pointer. It has a fixed type.
4708         // It is always dereferenced, a nullptr is undefined.
4709         CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
4710         // Nothing else to do: we already know all we want about this pointer.
4711         continue;
4712       case 1:
4713         // The second argument is the non-atomic operand. For arithmetic, this
4714         // is always passed by value, and for a compare_exchange it is always
4715         // passed by address. For the rest, GNU uses by-address and C11 uses
4716         // by-value.
4717         assert(Form != Load);
4718         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
4719           Ty = ValType;
4720         else if (Form == Copy || Form == Xchg) {
4721           if (IsPassedByAddress)
4722             // The value pointer is always dereferenced, a nullptr is undefined.
4723             CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
4724           Ty = ByValType;
4725         } else if (Form == Arithmetic)
4726           Ty = Context.getPointerDiffType();
4727         else {
4728           Expr *ValArg = TheCall->getArg(i);
4729           // The value pointer is always dereferenced, a nullptr is undefined.
4730           CheckNonNullArgument(*this, ValArg, DRE->getBeginLoc());
4731           LangAS AS = LangAS::Default;
4732           // Keep address space of non-atomic pointer type.
4733           if (const PointerType *PtrTy =
4734                   ValArg->getType()->getAs<PointerType>()) {
4735             AS = PtrTy->getPointeeType().getAddressSpace();
4736           }
4737           Ty = Context.getPointerType(
4738               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
4739         }
4740         break;
4741       case 2:
4742         // The third argument to compare_exchange / GNU exchange is the desired
4743         // value, either by-value (for the C11 and *_n variant) or as a pointer.
4744         if (IsPassedByAddress)
4745           CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
4746         Ty = ByValType;
4747         break;
4748       case 3:
4749         // The fourth argument to GNU compare_exchange is a 'weak' flag.
4750         Ty = Context.BoolTy;
4751         break;
4752       }
4753     } else {
4754       // The order(s) and scope are always converted to int.
4755       Ty = Context.IntTy;
4756     }
4757 
4758     InitializedEntity Entity =
4759         InitializedEntity::InitializeParameter(Context, Ty, false);
4760     ExprResult Arg = TheCall->getArg(i);
4761     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4762     if (Arg.isInvalid())
4763       return true;
4764     TheCall->setArg(i, Arg.get());
4765   }
4766 
4767   // Permute the arguments into a 'consistent' order.
4768   SmallVector<Expr*, 5> SubExprs;
4769   SubExprs.push_back(Ptr);
4770   switch (Form) {
4771   case Init:
4772     // Note, AtomicExpr::getVal1() has a special case for this atomic.
4773     SubExprs.push_back(TheCall->getArg(1)); // Val1
4774     break;
4775   case Load:
4776     SubExprs.push_back(TheCall->getArg(1)); // Order
4777     break;
4778   case LoadCopy:
4779   case Copy:
4780   case Arithmetic:
4781   case Xchg:
4782     SubExprs.push_back(TheCall->getArg(2)); // Order
4783     SubExprs.push_back(TheCall->getArg(1)); // Val1
4784     break;
4785   case GNUXchg:
4786     // Note, AtomicExpr::getVal2() has a special case for this atomic.
4787     SubExprs.push_back(TheCall->getArg(3)); // Order
4788     SubExprs.push_back(TheCall->getArg(1)); // Val1
4789     SubExprs.push_back(TheCall->getArg(2)); // Val2
4790     break;
4791   case C11CmpXchg:
4792     SubExprs.push_back(TheCall->getArg(3)); // Order
4793     SubExprs.push_back(TheCall->getArg(1)); // Val1
4794     SubExprs.push_back(TheCall->getArg(4)); // OrderFail
4795     SubExprs.push_back(TheCall->getArg(2)); // Val2
4796     break;
4797   case GNUCmpXchg:
4798     SubExprs.push_back(TheCall->getArg(4)); // Order
4799     SubExprs.push_back(TheCall->getArg(1)); // Val1
4800     SubExprs.push_back(TheCall->getArg(5)); // OrderFail
4801     SubExprs.push_back(TheCall->getArg(2)); // Val2
4802     SubExprs.push_back(TheCall->getArg(3)); // Weak
4803     break;
4804   }
4805 
4806   if (SubExprs.size() >= 2 && Form != Init) {
4807     llvm::APSInt Result(32);
4808     if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
4809         !isValidOrderingForOp(Result.getSExtValue(), Op))
4810       Diag(SubExprs[1]->getBeginLoc(),
4811            diag::warn_atomic_op_has_invalid_memory_order)
4812           << SubExprs[1]->getSourceRange();
4813   }
4814 
4815   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
4816     auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
4817     llvm::APSInt Result(32);
4818     if (Scope->isIntegerConstantExpr(Result, Context) &&
4819         !ScopeModel->isValid(Result.getZExtValue())) {
4820       Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
4821           << Scope->getSourceRange();
4822     }
4823     SubExprs.push_back(Scope);
4824   }
4825 
4826   AtomicExpr *AE =
4827       new (Context) AtomicExpr(TheCall->getCallee()->getBeginLoc(), SubExprs,
4828                                ResultType, Op, TheCall->getRParenLoc());
4829 
4830   if ((Op == AtomicExpr::AO__c11_atomic_load ||
4831        Op == AtomicExpr::AO__c11_atomic_store ||
4832        Op == AtomicExpr::AO__opencl_atomic_load ||
4833        Op == AtomicExpr::AO__opencl_atomic_store ) &&
4834       Context.AtomicUsesUnsupportedLibcall(AE))
4835     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
4836         << ((Op == AtomicExpr::AO__c11_atomic_load ||
4837              Op == AtomicExpr::AO__opencl_atomic_load)
4838                 ? 0
4839                 : 1);
4840 
4841   return AE;
4842 }
4843 
4844 /// checkBuiltinArgument - Given a call to a builtin function, perform
4845 /// normal type-checking on the given argument, updating the call in
4846 /// place.  This is useful when a builtin function requires custom
4847 /// type-checking for some of its arguments but not necessarily all of
4848 /// them.
4849 ///
4850 /// Returns true on error.
4851 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
4852   FunctionDecl *Fn = E->getDirectCallee();
4853   assert(Fn && "builtin call without direct callee!");
4854 
4855   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
4856   InitializedEntity Entity =
4857     InitializedEntity::InitializeParameter(S.Context, Param);
4858 
4859   ExprResult Arg = E->getArg(0);
4860   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
4861   if (Arg.isInvalid())
4862     return true;
4863 
4864   E->setArg(ArgIndex, Arg.get());
4865   return false;
4866 }
4867 
4868 /// We have a call to a function like __sync_fetch_and_add, which is an
4869 /// overloaded function based on the pointer type of its first argument.
4870 /// The main ActOnCallExpr routines have already promoted the types of
4871 /// arguments because all of these calls are prototyped as void(...).
4872 ///
4873 /// This function goes through and does final semantic checking for these
4874 /// builtins, as well as generating any warnings.
4875 ExprResult
4876 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
4877   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
4878   Expr *Callee = TheCall->getCallee();
4879   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
4880   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4881 
4882   // Ensure that we have at least one argument to do type inference from.
4883   if (TheCall->getNumArgs() < 1) {
4884     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
4885         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
4886     return ExprError();
4887   }
4888 
4889   // Inspect the first argument of the atomic builtin.  This should always be
4890   // a pointer type, whose element is an integral scalar or pointer type.
4891   // Because it is a pointer type, we don't have to worry about any implicit
4892   // casts here.
4893   // FIXME: We don't allow floating point scalars as input.
4894   Expr *FirstArg = TheCall->getArg(0);
4895   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
4896   if (FirstArgResult.isInvalid())
4897     return ExprError();
4898   FirstArg = FirstArgResult.get();
4899   TheCall->setArg(0, FirstArg);
4900 
4901   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
4902   if (!pointerType) {
4903     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
4904         << FirstArg->getType() << FirstArg->getSourceRange();
4905     return ExprError();
4906   }
4907 
4908   QualType ValType = pointerType->getPointeeType();
4909   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
4910       !ValType->isBlockPointerType()) {
4911     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
4912         << FirstArg->getType() << FirstArg->getSourceRange();
4913     return ExprError();
4914   }
4915 
4916   if (ValType.isConstQualified()) {
4917     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
4918         << FirstArg->getType() << FirstArg->getSourceRange();
4919     return ExprError();
4920   }
4921 
4922   switch (ValType.getObjCLifetime()) {
4923   case Qualifiers::OCL_None:
4924   case Qualifiers::OCL_ExplicitNone:
4925     // okay
4926     break;
4927 
4928   case Qualifiers::OCL_Weak:
4929   case Qualifiers::OCL_Strong:
4930   case Qualifiers::OCL_Autoreleasing:
4931     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
4932         << ValType << FirstArg->getSourceRange();
4933     return ExprError();
4934   }
4935 
4936   // Strip any qualifiers off ValType.
4937   ValType = ValType.getUnqualifiedType();
4938 
4939   // The majority of builtins return a value, but a few have special return
4940   // types, so allow them to override appropriately below.
4941   QualType ResultType = ValType;
4942 
4943   // We need to figure out which concrete builtin this maps onto.  For example,
4944   // __sync_fetch_and_add with a 2 byte object turns into
4945   // __sync_fetch_and_add_2.
4946 #define BUILTIN_ROW(x) \
4947   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
4948     Builtin::BI##x##_8, Builtin::BI##x##_16 }
4949 
4950   static const unsigned BuiltinIndices[][5] = {
4951     BUILTIN_ROW(__sync_fetch_and_add),
4952     BUILTIN_ROW(__sync_fetch_and_sub),
4953     BUILTIN_ROW(__sync_fetch_and_or),
4954     BUILTIN_ROW(__sync_fetch_and_and),
4955     BUILTIN_ROW(__sync_fetch_and_xor),
4956     BUILTIN_ROW(__sync_fetch_and_nand),
4957 
4958     BUILTIN_ROW(__sync_add_and_fetch),
4959     BUILTIN_ROW(__sync_sub_and_fetch),
4960     BUILTIN_ROW(__sync_and_and_fetch),
4961     BUILTIN_ROW(__sync_or_and_fetch),
4962     BUILTIN_ROW(__sync_xor_and_fetch),
4963     BUILTIN_ROW(__sync_nand_and_fetch),
4964 
4965     BUILTIN_ROW(__sync_val_compare_and_swap),
4966     BUILTIN_ROW(__sync_bool_compare_and_swap),
4967     BUILTIN_ROW(__sync_lock_test_and_set),
4968     BUILTIN_ROW(__sync_lock_release),
4969     BUILTIN_ROW(__sync_swap)
4970   };
4971 #undef BUILTIN_ROW
4972 
4973   // Determine the index of the size.
4974   unsigned SizeIndex;
4975   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
4976   case 1: SizeIndex = 0; break;
4977   case 2: SizeIndex = 1; break;
4978   case 4: SizeIndex = 2; break;
4979   case 8: SizeIndex = 3; break;
4980   case 16: SizeIndex = 4; break;
4981   default:
4982     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
4983         << FirstArg->getType() << FirstArg->getSourceRange();
4984     return ExprError();
4985   }
4986 
4987   // Each of these builtins has one pointer argument, followed by some number of
4988   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
4989   // that we ignore.  Find out which row of BuiltinIndices to read from as well
4990   // as the number of fixed args.
4991   unsigned BuiltinID = FDecl->getBuiltinID();
4992   unsigned BuiltinIndex, NumFixed = 1;
4993   bool WarnAboutSemanticsChange = false;
4994   switch (BuiltinID) {
4995   default: llvm_unreachable("Unknown overloaded atomic builtin!");
4996   case Builtin::BI__sync_fetch_and_add:
4997   case Builtin::BI__sync_fetch_and_add_1:
4998   case Builtin::BI__sync_fetch_and_add_2:
4999   case Builtin::BI__sync_fetch_and_add_4:
5000   case Builtin::BI__sync_fetch_and_add_8:
5001   case Builtin::BI__sync_fetch_and_add_16:
5002     BuiltinIndex = 0;
5003     break;
5004 
5005   case Builtin::BI__sync_fetch_and_sub:
5006   case Builtin::BI__sync_fetch_and_sub_1:
5007   case Builtin::BI__sync_fetch_and_sub_2:
5008   case Builtin::BI__sync_fetch_and_sub_4:
5009   case Builtin::BI__sync_fetch_and_sub_8:
5010   case Builtin::BI__sync_fetch_and_sub_16:
5011     BuiltinIndex = 1;
5012     break;
5013 
5014   case Builtin::BI__sync_fetch_and_or:
5015   case Builtin::BI__sync_fetch_and_or_1:
5016   case Builtin::BI__sync_fetch_and_or_2:
5017   case Builtin::BI__sync_fetch_and_or_4:
5018   case Builtin::BI__sync_fetch_and_or_8:
5019   case Builtin::BI__sync_fetch_and_or_16:
5020     BuiltinIndex = 2;
5021     break;
5022 
5023   case Builtin::BI__sync_fetch_and_and:
5024   case Builtin::BI__sync_fetch_and_and_1:
5025   case Builtin::BI__sync_fetch_and_and_2:
5026   case Builtin::BI__sync_fetch_and_and_4:
5027   case Builtin::BI__sync_fetch_and_and_8:
5028   case Builtin::BI__sync_fetch_and_and_16:
5029     BuiltinIndex = 3;
5030     break;
5031 
5032   case Builtin::BI__sync_fetch_and_xor:
5033   case Builtin::BI__sync_fetch_and_xor_1:
5034   case Builtin::BI__sync_fetch_and_xor_2:
5035   case Builtin::BI__sync_fetch_and_xor_4:
5036   case Builtin::BI__sync_fetch_and_xor_8:
5037   case Builtin::BI__sync_fetch_and_xor_16:
5038     BuiltinIndex = 4;
5039     break;
5040 
5041   case Builtin::BI__sync_fetch_and_nand:
5042   case Builtin::BI__sync_fetch_and_nand_1:
5043   case Builtin::BI__sync_fetch_and_nand_2:
5044   case Builtin::BI__sync_fetch_and_nand_4:
5045   case Builtin::BI__sync_fetch_and_nand_8:
5046   case Builtin::BI__sync_fetch_and_nand_16:
5047     BuiltinIndex = 5;
5048     WarnAboutSemanticsChange = true;
5049     break;
5050 
5051   case Builtin::BI__sync_add_and_fetch:
5052   case Builtin::BI__sync_add_and_fetch_1:
5053   case Builtin::BI__sync_add_and_fetch_2:
5054   case Builtin::BI__sync_add_and_fetch_4:
5055   case Builtin::BI__sync_add_and_fetch_8:
5056   case Builtin::BI__sync_add_and_fetch_16:
5057     BuiltinIndex = 6;
5058     break;
5059 
5060   case Builtin::BI__sync_sub_and_fetch:
5061   case Builtin::BI__sync_sub_and_fetch_1:
5062   case Builtin::BI__sync_sub_and_fetch_2:
5063   case Builtin::BI__sync_sub_and_fetch_4:
5064   case Builtin::BI__sync_sub_and_fetch_8:
5065   case Builtin::BI__sync_sub_and_fetch_16:
5066     BuiltinIndex = 7;
5067     break;
5068 
5069   case Builtin::BI__sync_and_and_fetch:
5070   case Builtin::BI__sync_and_and_fetch_1:
5071   case Builtin::BI__sync_and_and_fetch_2:
5072   case Builtin::BI__sync_and_and_fetch_4:
5073   case Builtin::BI__sync_and_and_fetch_8:
5074   case Builtin::BI__sync_and_and_fetch_16:
5075     BuiltinIndex = 8;
5076     break;
5077 
5078   case Builtin::BI__sync_or_and_fetch:
5079   case Builtin::BI__sync_or_and_fetch_1:
5080   case Builtin::BI__sync_or_and_fetch_2:
5081   case Builtin::BI__sync_or_and_fetch_4:
5082   case Builtin::BI__sync_or_and_fetch_8:
5083   case Builtin::BI__sync_or_and_fetch_16:
5084     BuiltinIndex = 9;
5085     break;
5086 
5087   case Builtin::BI__sync_xor_and_fetch:
5088   case Builtin::BI__sync_xor_and_fetch_1:
5089   case Builtin::BI__sync_xor_and_fetch_2:
5090   case Builtin::BI__sync_xor_and_fetch_4:
5091   case Builtin::BI__sync_xor_and_fetch_8:
5092   case Builtin::BI__sync_xor_and_fetch_16:
5093     BuiltinIndex = 10;
5094     break;
5095 
5096   case Builtin::BI__sync_nand_and_fetch:
5097   case Builtin::BI__sync_nand_and_fetch_1:
5098   case Builtin::BI__sync_nand_and_fetch_2:
5099   case Builtin::BI__sync_nand_and_fetch_4:
5100   case Builtin::BI__sync_nand_and_fetch_8:
5101   case Builtin::BI__sync_nand_and_fetch_16:
5102     BuiltinIndex = 11;
5103     WarnAboutSemanticsChange = true;
5104     break;
5105 
5106   case Builtin::BI__sync_val_compare_and_swap:
5107   case Builtin::BI__sync_val_compare_and_swap_1:
5108   case Builtin::BI__sync_val_compare_and_swap_2:
5109   case Builtin::BI__sync_val_compare_and_swap_4:
5110   case Builtin::BI__sync_val_compare_and_swap_8:
5111   case Builtin::BI__sync_val_compare_and_swap_16:
5112     BuiltinIndex = 12;
5113     NumFixed = 2;
5114     break;
5115 
5116   case Builtin::BI__sync_bool_compare_and_swap:
5117   case Builtin::BI__sync_bool_compare_and_swap_1:
5118   case Builtin::BI__sync_bool_compare_and_swap_2:
5119   case Builtin::BI__sync_bool_compare_and_swap_4:
5120   case Builtin::BI__sync_bool_compare_and_swap_8:
5121   case Builtin::BI__sync_bool_compare_and_swap_16:
5122     BuiltinIndex = 13;
5123     NumFixed = 2;
5124     ResultType = Context.BoolTy;
5125     break;
5126 
5127   case Builtin::BI__sync_lock_test_and_set:
5128   case Builtin::BI__sync_lock_test_and_set_1:
5129   case Builtin::BI__sync_lock_test_and_set_2:
5130   case Builtin::BI__sync_lock_test_and_set_4:
5131   case Builtin::BI__sync_lock_test_and_set_8:
5132   case Builtin::BI__sync_lock_test_and_set_16:
5133     BuiltinIndex = 14;
5134     break;
5135 
5136   case Builtin::BI__sync_lock_release:
5137   case Builtin::BI__sync_lock_release_1:
5138   case Builtin::BI__sync_lock_release_2:
5139   case Builtin::BI__sync_lock_release_4:
5140   case Builtin::BI__sync_lock_release_8:
5141   case Builtin::BI__sync_lock_release_16:
5142     BuiltinIndex = 15;
5143     NumFixed = 0;
5144     ResultType = Context.VoidTy;
5145     break;
5146 
5147   case Builtin::BI__sync_swap:
5148   case Builtin::BI__sync_swap_1:
5149   case Builtin::BI__sync_swap_2:
5150   case Builtin::BI__sync_swap_4:
5151   case Builtin::BI__sync_swap_8:
5152   case Builtin::BI__sync_swap_16:
5153     BuiltinIndex = 16;
5154     break;
5155   }
5156 
5157   // Now that we know how many fixed arguments we expect, first check that we
5158   // have at least that many.
5159   if (TheCall->getNumArgs() < 1+NumFixed) {
5160     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5161         << 0 << 1 + NumFixed << TheCall->getNumArgs()
5162         << Callee->getSourceRange();
5163     return ExprError();
5164   }
5165 
5166   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5167       << Callee->getSourceRange();
5168 
5169   if (WarnAboutSemanticsChange) {
5170     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5171         << Callee->getSourceRange();
5172   }
5173 
5174   // Get the decl for the concrete builtin from this, we can tell what the
5175   // concrete integer type we should convert to is.
5176   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5177   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5178   FunctionDecl *NewBuiltinDecl;
5179   if (NewBuiltinID == BuiltinID)
5180     NewBuiltinDecl = FDecl;
5181   else {
5182     // Perform builtin lookup to avoid redeclaring it.
5183     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5184     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5185     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5186     assert(Res.getFoundDecl());
5187     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5188     if (!NewBuiltinDecl)
5189       return ExprError();
5190   }
5191 
5192   // The first argument --- the pointer --- has a fixed type; we
5193   // deduce the types of the rest of the arguments accordingly.  Walk
5194   // the remaining arguments, converting them to the deduced value type.
5195   for (unsigned i = 0; i != NumFixed; ++i) {
5196     ExprResult Arg = TheCall->getArg(i+1);
5197 
5198     // GCC does an implicit conversion to the pointer or integer ValType.  This
5199     // can fail in some cases (1i -> int**), check for this error case now.
5200     // Initialize the argument.
5201     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5202                                                    ValType, /*consume*/ false);
5203     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5204     if (Arg.isInvalid())
5205       return ExprError();
5206 
5207     // Okay, we have something that *can* be converted to the right type.  Check
5208     // to see if there is a potentially weird extension going on here.  This can
5209     // happen when you do an atomic operation on something like an char* and
5210     // pass in 42.  The 42 gets converted to char.  This is even more strange
5211     // for things like 45.123 -> char, etc.
5212     // FIXME: Do this check.
5213     TheCall->setArg(i+1, Arg.get());
5214   }
5215 
5216   // Create a new DeclRefExpr to refer to the new decl.
5217   DeclRefExpr* NewDRE = DeclRefExpr::Create(
5218       Context,
5219       DRE->getQualifierLoc(),
5220       SourceLocation(),
5221       NewBuiltinDecl,
5222       /*enclosing*/ false,
5223       DRE->getLocation(),
5224       Context.BuiltinFnTy,
5225       DRE->getValueKind());
5226 
5227   // Set the callee in the CallExpr.
5228   // FIXME: This loses syntactic information.
5229   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5230   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5231                                               CK_BuiltinFnToFnPtr);
5232   TheCall->setCallee(PromotedCall.get());
5233 
5234   // Change the result type of the call to match the original value type. This
5235   // is arbitrary, but the codegen for these builtins ins design to handle it
5236   // gracefully.
5237   TheCall->setType(ResultType);
5238 
5239   return TheCallResult;
5240 }
5241 
5242 /// SemaBuiltinNontemporalOverloaded - We have a call to
5243 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
5244 /// overloaded function based on the pointer type of its last argument.
5245 ///
5246 /// This function goes through and does final semantic checking for these
5247 /// builtins.
5248 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5249   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5250   DeclRefExpr *DRE =
5251       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5252   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5253   unsigned BuiltinID = FDecl->getBuiltinID();
5254   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5255           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5256          "Unexpected nontemporal load/store builtin!");
5257   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5258   unsigned numArgs = isStore ? 2 : 1;
5259 
5260   // Ensure that we have the proper number of arguments.
5261   if (checkArgCount(*this, TheCall, numArgs))
5262     return ExprError();
5263 
5264   // Inspect the last argument of the nontemporal builtin.  This should always
5265   // be a pointer type, from which we imply the type of the memory access.
5266   // Because it is a pointer type, we don't have to worry about any implicit
5267   // casts here.
5268   Expr *PointerArg = TheCall->getArg(numArgs - 1);
5269   ExprResult PointerArgResult =
5270       DefaultFunctionArrayLvalueConversion(PointerArg);
5271 
5272   if (PointerArgResult.isInvalid())
5273     return ExprError();
5274   PointerArg = PointerArgResult.get();
5275   TheCall->setArg(numArgs - 1, PointerArg);
5276 
5277   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5278   if (!pointerType) {
5279     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5280         << PointerArg->getType() << PointerArg->getSourceRange();
5281     return ExprError();
5282   }
5283 
5284   QualType ValType = pointerType->getPointeeType();
5285 
5286   // Strip any qualifiers off ValType.
5287   ValType = ValType.getUnqualifiedType();
5288   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5289       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5290       !ValType->isVectorType()) {
5291     Diag(DRE->getBeginLoc(),
5292          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5293         << PointerArg->getType() << PointerArg->getSourceRange();
5294     return ExprError();
5295   }
5296 
5297   if (!isStore) {
5298     TheCall->setType(ValType);
5299     return TheCallResult;
5300   }
5301 
5302   ExprResult ValArg = TheCall->getArg(0);
5303   InitializedEntity Entity = InitializedEntity::InitializeParameter(
5304       Context, ValType, /*consume*/ false);
5305   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5306   if (ValArg.isInvalid())
5307     return ExprError();
5308 
5309   TheCall->setArg(0, ValArg.get());
5310   TheCall->setType(Context.VoidTy);
5311   return TheCallResult;
5312 }
5313 
5314 /// CheckObjCString - Checks that the argument to the builtin
5315 /// CFString constructor is correct
5316 /// Note: It might also make sense to do the UTF-16 conversion here (would
5317 /// simplify the backend).
5318 bool Sema::CheckObjCString(Expr *Arg) {
5319   Arg = Arg->IgnoreParenCasts();
5320   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
5321 
5322   if (!Literal || !Literal->isAscii()) {
5323     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
5324         << Arg->getSourceRange();
5325     return true;
5326   }
5327 
5328   if (Literal->containsNonAsciiOrNull()) {
5329     StringRef String = Literal->getString();
5330     unsigned NumBytes = String.size();
5331     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
5332     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5333     llvm::UTF16 *ToPtr = &ToBuf[0];
5334 
5335     llvm::ConversionResult Result =
5336         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5337                                  ToPtr + NumBytes, llvm::strictConversion);
5338     // Check for conversion failure.
5339     if (Result != llvm::conversionOK)
5340       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
5341           << Arg->getSourceRange();
5342   }
5343   return false;
5344 }
5345 
5346 /// CheckObjCString - Checks that the format string argument to the os_log()
5347 /// and os_trace() functions is correct, and converts it to const char *.
5348 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5349   Arg = Arg->IgnoreParenCasts();
5350   auto *Literal = dyn_cast<StringLiteral>(Arg);
5351   if (!Literal) {
5352     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5353       Literal = ObjcLiteral->getString();
5354     }
5355   }
5356 
5357   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
5358     return ExprError(
5359         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5360         << Arg->getSourceRange());
5361   }
5362 
5363   ExprResult Result(Literal);
5364   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5365   InitializedEntity Entity =
5366       InitializedEntity::InitializeParameter(Context, ResultTy, false);
5367   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5368   return Result;
5369 }
5370 
5371 /// Check that the user is calling the appropriate va_start builtin for the
5372 /// target and calling convention.
5373 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5374   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5375   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5376   bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
5377   bool IsWindows = TT.isOSWindows();
5378   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5379   if (IsX64 || IsAArch64) {
5380     CallingConv CC = CC_C;
5381     if (const FunctionDecl *FD = S.getCurFunctionDecl())
5382       CC = FD->getType()->getAs<FunctionType>()->getCallConv();
5383     if (IsMSVAStart) {
5384       // Don't allow this in System V ABI functions.
5385       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
5386         return S.Diag(Fn->getBeginLoc(),
5387                       diag::err_ms_va_start_used_in_sysv_function);
5388     } else {
5389       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5390       // On x64 Windows, don't allow this in System V ABI functions.
5391       // (Yes, that means there's no corresponding way to support variadic
5392       // System V ABI functions on Windows.)
5393       if ((IsWindows && CC == CC_X86_64SysV) ||
5394           (!IsWindows && CC == CC_Win64))
5395         return S.Diag(Fn->getBeginLoc(),
5396                       diag::err_va_start_used_in_wrong_abi_function)
5397                << !IsWindows;
5398     }
5399     return false;
5400   }
5401 
5402   if (IsMSVAStart)
5403     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5404   return false;
5405 }
5406 
5407 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
5408                                              ParmVarDecl **LastParam = nullptr) {
5409   // Determine whether the current function, block, or obj-c method is variadic
5410   // and get its parameter list.
5411   bool IsVariadic = false;
5412   ArrayRef<ParmVarDecl *> Params;
5413   DeclContext *Caller = S.CurContext;
5414   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5415     IsVariadic = Block->isVariadic();
5416     Params = Block->parameters();
5417   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5418     IsVariadic = FD->isVariadic();
5419     Params = FD->parameters();
5420   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5421     IsVariadic = MD->isVariadic();
5422     // FIXME: This isn't correct for methods (results in bogus warning).
5423     Params = MD->parameters();
5424   } else if (isa<CapturedDecl>(Caller)) {
5425     // We don't support va_start in a CapturedDecl.
5426     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5427     return true;
5428   } else {
5429     // This must be some other declcontext that parses exprs.
5430     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5431     return true;
5432   }
5433 
5434   if (!IsVariadic) {
5435     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
5436     return true;
5437   }
5438 
5439   if (LastParam)
5440     *LastParam = Params.empty() ? nullptr : Params.back();
5441 
5442   return false;
5443 }
5444 
5445 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
5446 /// for validity.  Emit an error and return true on failure; return false
5447 /// on success.
5448 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5449   Expr *Fn = TheCall->getCallee();
5450 
5451   if (checkVAStartABI(*this, BuiltinID, Fn))
5452     return true;
5453 
5454   if (TheCall->getNumArgs() > 2) {
5455     Diag(TheCall->getArg(2)->getBeginLoc(),
5456          diag::err_typecheck_call_too_many_args)
5457         << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5458         << Fn->getSourceRange()
5459         << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5460                        (*(TheCall->arg_end() - 1))->getEndLoc());
5461     return true;
5462   }
5463 
5464   if (TheCall->getNumArgs() < 2) {
5465     return Diag(TheCall->getEndLoc(),
5466                 diag::err_typecheck_call_too_few_args_at_least)
5467            << 0 /*function call*/ << 2 << TheCall->getNumArgs();
5468   }
5469 
5470   // Type-check the first argument normally.
5471   if (checkBuiltinArgument(*this, TheCall, 0))
5472     return true;
5473 
5474   // Check that the current function is variadic, and get its last parameter.
5475   ParmVarDecl *LastParam;
5476   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5477     return true;
5478 
5479   // Verify that the second argument to the builtin is the last argument of the
5480   // current function or method.
5481   bool SecondArgIsLastNamedArgument = false;
5482   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5483 
5484   // These are valid if SecondArgIsLastNamedArgument is false after the next
5485   // block.
5486   QualType Type;
5487   SourceLocation ParamLoc;
5488   bool IsCRegister = false;
5489 
5490   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5491     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5492       SecondArgIsLastNamedArgument = PV == LastParam;
5493 
5494       Type = PV->getType();
5495       ParamLoc = PV->getLocation();
5496       IsCRegister =
5497           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5498     }
5499   }
5500 
5501   if (!SecondArgIsLastNamedArgument)
5502     Diag(TheCall->getArg(1)->getBeginLoc(),
5503          diag::warn_second_arg_of_va_start_not_last_named_param);
5504   else if (IsCRegister || Type->isReferenceType() ||
5505            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5506              // Promotable integers are UB, but enumerations need a bit of
5507              // extra checking to see what their promotable type actually is.
5508              if (!Type->isPromotableIntegerType())
5509                return false;
5510              if (!Type->isEnumeralType())
5511                return true;
5512              const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
5513              return !(ED &&
5514                       Context.typesAreCompatible(ED->getPromotionType(), Type));
5515            }()) {
5516     unsigned Reason = 0;
5517     if (Type->isReferenceType())  Reason = 1;
5518     else if (IsCRegister)         Reason = 2;
5519     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
5520     Diag(ParamLoc, diag::note_parameter_type) << Type;
5521   }
5522 
5523   TheCall->setType(Context.VoidTy);
5524   return false;
5525 }
5526 
5527 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
5528   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5529   //                 const char *named_addr);
5530 
5531   Expr *Func = Call->getCallee();
5532 
5533   if (Call->getNumArgs() < 3)
5534     return Diag(Call->getEndLoc(),
5535                 diag::err_typecheck_call_too_few_args_at_least)
5536            << 0 /*function call*/ << 3 << Call->getNumArgs();
5537 
5538   // Type-check the first argument normally.
5539   if (checkBuiltinArgument(*this, Call, 0))
5540     return true;
5541 
5542   // Check that the current function is variadic.
5543   if (checkVAStartIsInVariadicFunction(*this, Func))
5544     return true;
5545 
5546   // __va_start on Windows does not validate the parameter qualifiers
5547 
5548   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5549   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5550 
5551   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5552   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5553 
5554   const QualType &ConstCharPtrTy =
5555       Context.getPointerType(Context.CharTy.withConst());
5556   if (!Arg1Ty->isPointerType() ||
5557       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
5558     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5559         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5560         << 0                                      /* qualifier difference */
5561         << 3                                      /* parameter mismatch */
5562         << 2 << Arg1->getType() << ConstCharPtrTy;
5563 
5564   const QualType SizeTy = Context.getSizeType();
5565   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
5566     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5567         << Arg2->getType() << SizeTy << 1 /* different class */
5568         << 0                              /* qualifier difference */
5569         << 3                              /* parameter mismatch */
5570         << 3 << Arg2->getType() << SizeTy;
5571 
5572   return false;
5573 }
5574 
5575 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
5576 /// friends.  This is declared to take (...), so we have to check everything.
5577 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
5578   if (TheCall->getNumArgs() < 2)
5579     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5580            << 0 << 2 << TheCall->getNumArgs() /*function call*/;
5581   if (TheCall->getNumArgs() > 2)
5582     return Diag(TheCall->getArg(2)->getBeginLoc(),
5583                 diag::err_typecheck_call_too_many_args)
5584            << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5585            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5586                           (*(TheCall->arg_end() - 1))->getEndLoc());
5587 
5588   ExprResult OrigArg0 = TheCall->getArg(0);
5589   ExprResult OrigArg1 = TheCall->getArg(1);
5590 
5591   // Do standard promotions between the two arguments, returning their common
5592   // type.
5593   QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
5594   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5595     return true;
5596 
5597   // Make sure any conversions are pushed back into the call; this is
5598   // type safe since unordered compare builtins are declared as "_Bool
5599   // foo(...)".
5600   TheCall->setArg(0, OrigArg0.get());
5601   TheCall->setArg(1, OrigArg1.get());
5602 
5603   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5604     return false;
5605 
5606   // If the common type isn't a real floating type, then the arguments were
5607   // invalid for this operation.
5608   if (Res.isNull() || !Res->isRealFloatingType())
5609     return Diag(OrigArg0.get()->getBeginLoc(),
5610                 diag::err_typecheck_call_invalid_ordered_compare)
5611            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5612            << SourceRange(OrigArg0.get()->getBeginLoc(),
5613                           OrigArg1.get()->getEndLoc());
5614 
5615   return false;
5616 }
5617 
5618 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
5619 /// __builtin_isnan and friends.  This is declared to take (...), so we have
5620 /// to check everything. We expect the last argument to be a floating point
5621 /// value.
5622 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
5623   if (TheCall->getNumArgs() < NumArgs)
5624     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5625            << 0 << NumArgs << TheCall->getNumArgs() /*function call*/;
5626   if (TheCall->getNumArgs() > NumArgs)
5627     return Diag(TheCall->getArg(NumArgs)->getBeginLoc(),
5628                 diag::err_typecheck_call_too_many_args)
5629            << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
5630            << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(),
5631                           (*(TheCall->arg_end() - 1))->getEndLoc());
5632 
5633   Expr *OrigArg = TheCall->getArg(NumArgs-1);
5634 
5635   if (OrigArg->isTypeDependent())
5636     return false;
5637 
5638   // This operation requires a non-_Complex floating-point number.
5639   if (!OrigArg->getType()->isRealFloatingType())
5640     return Diag(OrigArg->getBeginLoc(),
5641                 diag::err_typecheck_call_invalid_unary_fp)
5642            << OrigArg->getType() << OrigArg->getSourceRange();
5643 
5644   // If this is an implicit conversion from float -> float, double, or
5645   // long double, remove it.
5646   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
5647     // Only remove standard FloatCasts, leaving other casts inplace
5648     if (Cast->getCastKind() == CK_FloatingCast) {
5649       Expr *CastArg = Cast->getSubExpr();
5650       if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
5651         assert(
5652             (Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
5653              Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) ||
5654              Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) &&
5655             "promotion from float to either float, double, or long double is "
5656             "the only expected cast here");
5657         Cast->setSubExpr(nullptr);
5658         TheCall->setArg(NumArgs-1, CastArg);
5659       }
5660     }
5661   }
5662 
5663   return false;
5664 }
5665 
5666 // Customized Sema Checking for VSX builtins that have the following signature:
5667 // vector [...] builtinName(vector [...], vector [...], const int);
5668 // Which takes the same type of vectors (any legal vector type) for the first
5669 // two arguments and takes compile time constant for the third argument.
5670 // Example builtins are :
5671 // vector double vec_xxpermdi(vector double, vector double, int);
5672 // vector short vec_xxsldwi(vector short, vector short, int);
5673 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
5674   unsigned ExpectedNumArgs = 3;
5675   if (TheCall->getNumArgs() < ExpectedNumArgs)
5676     return Diag(TheCall->getEndLoc(),
5677                 diag::err_typecheck_call_too_few_args_at_least)
5678            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5679            << TheCall->getSourceRange();
5680 
5681   if (TheCall->getNumArgs() > ExpectedNumArgs)
5682     return Diag(TheCall->getEndLoc(),
5683                 diag::err_typecheck_call_too_many_args_at_most)
5684            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5685            << TheCall->getSourceRange();
5686 
5687   // Check the third argument is a compile time constant
5688   llvm::APSInt Value;
5689   if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
5690     return Diag(TheCall->getBeginLoc(),
5691                 diag::err_vsx_builtin_nonconstant_argument)
5692            << 3 /* argument index */ << TheCall->getDirectCallee()
5693            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5694                           TheCall->getArg(2)->getEndLoc());
5695 
5696   QualType Arg1Ty = TheCall->getArg(0)->getType();
5697   QualType Arg2Ty = TheCall->getArg(1)->getType();
5698 
5699   // Check the type of argument 1 and argument 2 are vectors.
5700   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
5701   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
5702       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
5703     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
5704            << TheCall->getDirectCallee()
5705            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5706                           TheCall->getArg(1)->getEndLoc());
5707   }
5708 
5709   // Check the first two arguments are the same type.
5710   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
5711     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
5712            << TheCall->getDirectCallee()
5713            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5714                           TheCall->getArg(1)->getEndLoc());
5715   }
5716 
5717   // When default clang type checking is turned off and the customized type
5718   // checking is used, the returning type of the function must be explicitly
5719   // set. Otherwise it is _Bool by default.
5720   TheCall->setType(Arg1Ty);
5721 
5722   return false;
5723 }
5724 
5725 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
5726 // This is declared to take (...), so we have to check everything.
5727 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
5728   if (TheCall->getNumArgs() < 2)
5729     return ExprError(Diag(TheCall->getEndLoc(),
5730                           diag::err_typecheck_call_too_few_args_at_least)
5731                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5732                      << TheCall->getSourceRange());
5733 
5734   // Determine which of the following types of shufflevector we're checking:
5735   // 1) unary, vector mask: (lhs, mask)
5736   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
5737   QualType resType = TheCall->getArg(0)->getType();
5738   unsigned numElements = 0;
5739 
5740   if (!TheCall->getArg(0)->isTypeDependent() &&
5741       !TheCall->getArg(1)->isTypeDependent()) {
5742     QualType LHSType = TheCall->getArg(0)->getType();
5743     QualType RHSType = TheCall->getArg(1)->getType();
5744 
5745     if (!LHSType->isVectorType() || !RHSType->isVectorType())
5746       return ExprError(
5747           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
5748           << TheCall->getDirectCallee()
5749           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5750                          TheCall->getArg(1)->getEndLoc()));
5751 
5752     numElements = LHSType->getAs<VectorType>()->getNumElements();
5753     unsigned numResElements = TheCall->getNumArgs() - 2;
5754 
5755     // Check to see if we have a call with 2 vector arguments, the unary shuffle
5756     // with mask.  If so, verify that RHS is an integer vector type with the
5757     // same number of elts as lhs.
5758     if (TheCall->getNumArgs() == 2) {
5759       if (!RHSType->hasIntegerRepresentation() ||
5760           RHSType->getAs<VectorType>()->getNumElements() != numElements)
5761         return ExprError(Diag(TheCall->getBeginLoc(),
5762                               diag::err_vec_builtin_incompatible_vector)
5763                          << TheCall->getDirectCallee()
5764                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
5765                                         TheCall->getArg(1)->getEndLoc()));
5766     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
5767       return ExprError(Diag(TheCall->getBeginLoc(),
5768                             diag::err_vec_builtin_incompatible_vector)
5769                        << TheCall->getDirectCallee()
5770                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5771                                       TheCall->getArg(1)->getEndLoc()));
5772     } else if (numElements != numResElements) {
5773       QualType eltType = LHSType->getAs<VectorType>()->getElementType();
5774       resType = Context.getVectorType(eltType, numResElements,
5775                                       VectorType::GenericVector);
5776     }
5777   }
5778 
5779   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
5780     if (TheCall->getArg(i)->isTypeDependent() ||
5781         TheCall->getArg(i)->isValueDependent())
5782       continue;
5783 
5784     llvm::APSInt Result(32);
5785     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
5786       return ExprError(Diag(TheCall->getBeginLoc(),
5787                             diag::err_shufflevector_nonconstant_argument)
5788                        << TheCall->getArg(i)->getSourceRange());
5789 
5790     // Allow -1 which will be translated to undef in the IR.
5791     if (Result.isSigned() && Result.isAllOnesValue())
5792       continue;
5793 
5794     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
5795       return ExprError(Diag(TheCall->getBeginLoc(),
5796                             diag::err_shufflevector_argument_too_large)
5797                        << TheCall->getArg(i)->getSourceRange());
5798   }
5799 
5800   SmallVector<Expr*, 32> exprs;
5801 
5802   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
5803     exprs.push_back(TheCall->getArg(i));
5804     TheCall->setArg(i, nullptr);
5805   }
5806 
5807   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
5808                                          TheCall->getCallee()->getBeginLoc(),
5809                                          TheCall->getRParenLoc());
5810 }
5811 
5812 /// SemaConvertVectorExpr - Handle __builtin_convertvector
5813 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
5814                                        SourceLocation BuiltinLoc,
5815                                        SourceLocation RParenLoc) {
5816   ExprValueKind VK = VK_RValue;
5817   ExprObjectKind OK = OK_Ordinary;
5818   QualType DstTy = TInfo->getType();
5819   QualType SrcTy = E->getType();
5820 
5821   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
5822     return ExprError(Diag(BuiltinLoc,
5823                           diag::err_convertvector_non_vector)
5824                      << E->getSourceRange());
5825   if (!DstTy->isVectorType() && !DstTy->isDependentType())
5826     return ExprError(Diag(BuiltinLoc,
5827                           diag::err_convertvector_non_vector_type));
5828 
5829   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
5830     unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
5831     unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
5832     if (SrcElts != DstElts)
5833       return ExprError(Diag(BuiltinLoc,
5834                             diag::err_convertvector_incompatible_vector)
5835                        << E->getSourceRange());
5836   }
5837 
5838   return new (Context)
5839       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5840 }
5841 
5842 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
5843 // This is declared to take (const void*, ...) and can take two
5844 // optional constant int args.
5845 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
5846   unsigned NumArgs = TheCall->getNumArgs();
5847 
5848   if (NumArgs > 3)
5849     return Diag(TheCall->getEndLoc(),
5850                 diag::err_typecheck_call_too_many_args_at_most)
5851            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
5852 
5853   // Argument 0 is checked for us and the remaining arguments must be
5854   // constant integers.
5855   for (unsigned i = 1; i != NumArgs; ++i)
5856     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
5857       return true;
5858 
5859   return false;
5860 }
5861 
5862 /// SemaBuiltinAssume - Handle __assume (MS Extension).
5863 // __assume does not evaluate its arguments, and should warn if its argument
5864 // has side effects.
5865 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
5866   Expr *Arg = TheCall->getArg(0);
5867   if (Arg->isInstantiationDependent()) return false;
5868 
5869   if (Arg->HasSideEffects(Context))
5870     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
5871         << Arg->getSourceRange()
5872         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
5873 
5874   return false;
5875 }
5876 
5877 /// Handle __builtin_alloca_with_align. This is declared
5878 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
5879 /// than 8.
5880 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
5881   // The alignment must be a constant integer.
5882   Expr *Arg = TheCall->getArg(1);
5883 
5884   // We can't check the value of a dependent argument.
5885   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5886     if (const auto *UE =
5887             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
5888       if (UE->getKind() == UETT_AlignOf ||
5889           UE->getKind() == UETT_PreferredAlignOf)
5890         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
5891             << Arg->getSourceRange();
5892 
5893     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
5894 
5895     if (!Result.isPowerOf2())
5896       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5897              << Arg->getSourceRange();
5898 
5899     if (Result < Context.getCharWidth())
5900       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
5901              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
5902 
5903     if (Result > std::numeric_limits<int32_t>::max())
5904       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
5905              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
5906   }
5907 
5908   return false;
5909 }
5910 
5911 /// Handle __builtin_assume_aligned. This is declared
5912 /// as (const void*, size_t, ...) and can take one optional constant int arg.
5913 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
5914   unsigned NumArgs = TheCall->getNumArgs();
5915 
5916   if (NumArgs > 3)
5917     return Diag(TheCall->getEndLoc(),
5918                 diag::err_typecheck_call_too_many_args_at_most)
5919            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
5920 
5921   // The alignment must be a constant integer.
5922   Expr *Arg = TheCall->getArg(1);
5923 
5924   // We can't check the value of a dependent argument.
5925   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5926     llvm::APSInt Result;
5927     if (SemaBuiltinConstantArg(TheCall, 1, Result))
5928       return true;
5929 
5930     if (!Result.isPowerOf2())
5931       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5932              << Arg->getSourceRange();
5933   }
5934 
5935   if (NumArgs > 2) {
5936     ExprResult Arg(TheCall->getArg(2));
5937     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5938       Context.getSizeType(), false);
5939     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5940     if (Arg.isInvalid()) return true;
5941     TheCall->setArg(2, Arg.get());
5942   }
5943 
5944   return false;
5945 }
5946 
5947 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
5948   unsigned BuiltinID =
5949       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
5950   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
5951 
5952   unsigned NumArgs = TheCall->getNumArgs();
5953   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
5954   if (NumArgs < NumRequiredArgs) {
5955     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5956            << 0 /* function call */ << NumRequiredArgs << NumArgs
5957            << TheCall->getSourceRange();
5958   }
5959   if (NumArgs >= NumRequiredArgs + 0x100) {
5960     return Diag(TheCall->getEndLoc(),
5961                 diag::err_typecheck_call_too_many_args_at_most)
5962            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
5963            << TheCall->getSourceRange();
5964   }
5965   unsigned i = 0;
5966 
5967   // For formatting call, check buffer arg.
5968   if (!IsSizeCall) {
5969     ExprResult Arg(TheCall->getArg(i));
5970     InitializedEntity Entity = InitializedEntity::InitializeParameter(
5971         Context, Context.VoidPtrTy, false);
5972     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5973     if (Arg.isInvalid())
5974       return true;
5975     TheCall->setArg(i, Arg.get());
5976     i++;
5977   }
5978 
5979   // Check string literal arg.
5980   unsigned FormatIdx = i;
5981   {
5982     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
5983     if (Arg.isInvalid())
5984       return true;
5985     TheCall->setArg(i, Arg.get());
5986     i++;
5987   }
5988 
5989   // Make sure variadic args are scalar.
5990   unsigned FirstDataArg = i;
5991   while (i < NumArgs) {
5992     ExprResult Arg = DefaultVariadicArgumentPromotion(
5993         TheCall->getArg(i), VariadicFunction, nullptr);
5994     if (Arg.isInvalid())
5995       return true;
5996     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
5997     if (ArgSize.getQuantity() >= 0x100) {
5998       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
5999              << i << (int)ArgSize.getQuantity() << 0xff
6000              << TheCall->getSourceRange();
6001     }
6002     TheCall->setArg(i, Arg.get());
6003     i++;
6004   }
6005 
6006   // Check formatting specifiers. NOTE: We're only doing this for the non-size
6007   // call to avoid duplicate diagnostics.
6008   if (!IsSizeCall) {
6009     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6010     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6011     bool Success = CheckFormatArguments(
6012         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
6013         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
6014         CheckedVarArgs);
6015     if (!Success)
6016       return true;
6017   }
6018 
6019   if (IsSizeCall) {
6020     TheCall->setType(Context.getSizeType());
6021   } else {
6022     TheCall->setType(Context.VoidPtrTy);
6023   }
6024   return false;
6025 }
6026 
6027 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
6028 /// TheCall is a constant expression.
6029 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
6030                                   llvm::APSInt &Result) {
6031   Expr *Arg = TheCall->getArg(ArgNum);
6032   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6033   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6034 
6035   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
6036 
6037   if (!Arg->isIntegerConstantExpr(Result, Context))
6038     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6039            << FDecl->getDeclName() << Arg->getSourceRange();
6040 
6041   return false;
6042 }
6043 
6044 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
6045 /// TheCall is a constant expression in the range [Low, High].
6046 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
6047                                        int Low, int High, bool RangeIsError) {
6048   llvm::APSInt Result;
6049 
6050   // We can't check the value of a dependent argument.
6051   Expr *Arg = TheCall->getArg(ArgNum);
6052   if (Arg->isTypeDependent() || Arg->isValueDependent())
6053     return false;
6054 
6055   // Check constant-ness first.
6056   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6057     return true;
6058 
6059   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6060     if (RangeIsError)
6061       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6062              << Result.toString(10) << Low << High << Arg->getSourceRange();
6063     else
6064       // Defer the warning until we know if the code will be emitted so that
6065       // dead code can ignore this.
6066       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6067                           PDiag(diag::warn_argument_invalid_range)
6068                               << Result.toString(10) << Low << High
6069                               << Arg->getSourceRange());
6070   }
6071 
6072   return false;
6073 }
6074 
6075 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
6076 /// TheCall is a constant expression is a multiple of Num..
6077 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
6078                                           unsigned Num) {
6079   llvm::APSInt Result;
6080 
6081   // We can't check the value of a dependent argument.
6082   Expr *Arg = TheCall->getArg(ArgNum);
6083   if (Arg->isTypeDependent() || Arg->isValueDependent())
6084     return false;
6085 
6086   // Check constant-ness first.
6087   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6088     return true;
6089 
6090   if (Result.getSExtValue() % Num != 0)
6091     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6092            << Num << Arg->getSourceRange();
6093 
6094   return false;
6095 }
6096 
6097 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
6098 /// TheCall is an ARM/AArch64 special register string literal.
6099 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
6100                                     int ArgNum, unsigned ExpectedFieldNum,
6101                                     bool AllowName) {
6102   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
6103                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
6104                       BuiltinID == ARM::BI__builtin_arm_rsr ||
6105                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
6106                       BuiltinID == ARM::BI__builtin_arm_wsr ||
6107                       BuiltinID == ARM::BI__builtin_arm_wsrp;
6108   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
6109                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
6110                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
6111                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
6112                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
6113                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
6114   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
6115 
6116   // We can't check the value of a dependent argument.
6117   Expr *Arg = TheCall->getArg(ArgNum);
6118   if (Arg->isTypeDependent() || Arg->isValueDependent())
6119     return false;
6120 
6121   // Check if the argument is a string literal.
6122   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
6123     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
6124            << Arg->getSourceRange();
6125 
6126   // Check the type of special register given.
6127   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
6128   SmallVector<StringRef, 6> Fields;
6129   Reg.split(Fields, ":");
6130 
6131   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
6132     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6133            << Arg->getSourceRange();
6134 
6135   // If the string is the name of a register then we cannot check that it is
6136   // valid here but if the string is of one the forms described in ACLE then we
6137   // can check that the supplied fields are integers and within the valid
6138   // ranges.
6139   if (Fields.size() > 1) {
6140     bool FiveFields = Fields.size() == 5;
6141 
6142     bool ValidString = true;
6143     if (IsARMBuiltin) {
6144       ValidString &= Fields[0].startswith_lower("cp") ||
6145                      Fields[0].startswith_lower("p");
6146       if (ValidString)
6147         Fields[0] =
6148           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
6149 
6150       ValidString &= Fields[2].startswith_lower("c");
6151       if (ValidString)
6152         Fields[2] = Fields[2].drop_front(1);
6153 
6154       if (FiveFields) {
6155         ValidString &= Fields[3].startswith_lower("c");
6156         if (ValidString)
6157           Fields[3] = Fields[3].drop_front(1);
6158       }
6159     }
6160 
6161     SmallVector<int, 5> Ranges;
6162     if (FiveFields)
6163       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
6164     else
6165       Ranges.append({15, 7, 15});
6166 
6167     for (unsigned i=0; i<Fields.size(); ++i) {
6168       int IntField;
6169       ValidString &= !Fields[i].getAsInteger(10, IntField);
6170       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
6171     }
6172 
6173     if (!ValidString)
6174       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6175              << Arg->getSourceRange();
6176   } else if (IsAArch64Builtin && Fields.size() == 1) {
6177     // If the register name is one of those that appear in the condition below
6178     // and the special register builtin being used is one of the write builtins,
6179     // then we require that the argument provided for writing to the register
6180     // is an integer constant expression. This is because it will be lowered to
6181     // an MSR (immediate) instruction, so we need to know the immediate at
6182     // compile time.
6183     if (TheCall->getNumArgs() != 2)
6184       return false;
6185 
6186     std::string RegLower = Reg.lower();
6187     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
6188         RegLower != "pan" && RegLower != "uao")
6189       return false;
6190 
6191     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6192   }
6193 
6194   return false;
6195 }
6196 
6197 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
6198 /// This checks that the target supports __builtin_longjmp and
6199 /// that val is a constant 1.
6200 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
6201   if (!Context.getTargetInfo().hasSjLjLowering())
6202     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
6203            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6204 
6205   Expr *Arg = TheCall->getArg(1);
6206   llvm::APSInt Result;
6207 
6208   // TODO: This is less than ideal. Overload this to take a value.
6209   if (SemaBuiltinConstantArg(TheCall, 1, Result))
6210     return true;
6211 
6212   if (Result != 1)
6213     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
6214            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6215 
6216   return false;
6217 }
6218 
6219 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
6220 /// This checks that the target supports __builtin_setjmp.
6221 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
6222   if (!Context.getTargetInfo().hasSjLjLowering())
6223     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
6224            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6225   return false;
6226 }
6227 
6228 namespace {
6229 
6230 class UncoveredArgHandler {
6231   enum { Unknown = -1, AllCovered = -2 };
6232 
6233   signed FirstUncoveredArg = Unknown;
6234   SmallVector<const Expr *, 4> DiagnosticExprs;
6235 
6236 public:
6237   UncoveredArgHandler() = default;
6238 
6239   bool hasUncoveredArg() const {
6240     return (FirstUncoveredArg >= 0);
6241   }
6242 
6243   unsigned getUncoveredArg() const {
6244     assert(hasUncoveredArg() && "no uncovered argument");
6245     return FirstUncoveredArg;
6246   }
6247 
6248   void setAllCovered() {
6249     // A string has been found with all arguments covered, so clear out
6250     // the diagnostics.
6251     DiagnosticExprs.clear();
6252     FirstUncoveredArg = AllCovered;
6253   }
6254 
6255   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6256     assert(NewFirstUncoveredArg >= 0 && "Outside range");
6257 
6258     // Don't update if a previous string covers all arguments.
6259     if (FirstUncoveredArg == AllCovered)
6260       return;
6261 
6262     // UncoveredArgHandler tracks the highest uncovered argument index
6263     // and with it all the strings that match this index.
6264     if (NewFirstUncoveredArg == FirstUncoveredArg)
6265       DiagnosticExprs.push_back(StrExpr);
6266     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6267       DiagnosticExprs.clear();
6268       DiagnosticExprs.push_back(StrExpr);
6269       FirstUncoveredArg = NewFirstUncoveredArg;
6270     }
6271   }
6272 
6273   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6274 };
6275 
6276 enum StringLiteralCheckType {
6277   SLCT_NotALiteral,
6278   SLCT_UncheckedLiteral,
6279   SLCT_CheckedLiteral
6280 };
6281 
6282 } // namespace
6283 
6284 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6285                                      BinaryOperatorKind BinOpKind,
6286                                      bool AddendIsRight) {
6287   unsigned BitWidth = Offset.getBitWidth();
6288   unsigned AddendBitWidth = Addend.getBitWidth();
6289   // There might be negative interim results.
6290   if (Addend.isUnsigned()) {
6291     Addend = Addend.zext(++AddendBitWidth);
6292     Addend.setIsSigned(true);
6293   }
6294   // Adjust the bit width of the APSInts.
6295   if (AddendBitWidth > BitWidth) {
6296     Offset = Offset.sext(AddendBitWidth);
6297     BitWidth = AddendBitWidth;
6298   } else if (BitWidth > AddendBitWidth) {
6299     Addend = Addend.sext(BitWidth);
6300   }
6301 
6302   bool Ov = false;
6303   llvm::APSInt ResOffset = Offset;
6304   if (BinOpKind == BO_Add)
6305     ResOffset = Offset.sadd_ov(Addend, Ov);
6306   else {
6307     assert(AddendIsRight && BinOpKind == BO_Sub &&
6308            "operator must be add or sub with addend on the right");
6309     ResOffset = Offset.ssub_ov(Addend, Ov);
6310   }
6311 
6312   // We add an offset to a pointer here so we should support an offset as big as
6313   // possible.
6314   if (Ov) {
6315     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6316            "index (intermediate) result too big");
6317     Offset = Offset.sext(2 * BitWidth);
6318     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6319     return;
6320   }
6321 
6322   Offset = ResOffset;
6323 }
6324 
6325 namespace {
6326 
6327 // This is a wrapper class around StringLiteral to support offsetted string
6328 // literals as format strings. It takes the offset into account when returning
6329 // the string and its length or the source locations to display notes correctly.
6330 class FormatStringLiteral {
6331   const StringLiteral *FExpr;
6332   int64_t Offset;
6333 
6334  public:
6335   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
6336       : FExpr(fexpr), Offset(Offset) {}
6337 
6338   StringRef getString() const {
6339     return FExpr->getString().drop_front(Offset);
6340   }
6341 
6342   unsigned getByteLength() const {
6343     return FExpr->getByteLength() - getCharByteWidth() * Offset;
6344   }
6345 
6346   unsigned getLength() const { return FExpr->getLength() - Offset; }
6347   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
6348 
6349   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
6350 
6351   QualType getType() const { return FExpr->getType(); }
6352 
6353   bool isAscii() const { return FExpr->isAscii(); }
6354   bool isWide() const { return FExpr->isWide(); }
6355   bool isUTF8() const { return FExpr->isUTF8(); }
6356   bool isUTF16() const { return FExpr->isUTF16(); }
6357   bool isUTF32() const { return FExpr->isUTF32(); }
6358   bool isPascal() const { return FExpr->isPascal(); }
6359 
6360   SourceLocation getLocationOfByte(
6361       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
6362       const TargetInfo &Target, unsigned *StartToken = nullptr,
6363       unsigned *StartTokenByteOffset = nullptr) const {
6364     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
6365                                     StartToken, StartTokenByteOffset);
6366   }
6367 
6368   SourceLocation getBeginLoc() const LLVM_READONLY {
6369     return FExpr->getBeginLoc().getLocWithOffset(Offset);
6370   }
6371 
6372   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
6373 };
6374 
6375 }  // namespace
6376 
6377 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
6378                               const Expr *OrigFormatExpr,
6379                               ArrayRef<const Expr *> Args,
6380                               bool HasVAListArg, unsigned format_idx,
6381                               unsigned firstDataArg,
6382                               Sema::FormatStringType Type,
6383                               bool inFunctionCall,
6384                               Sema::VariadicCallType CallType,
6385                               llvm::SmallBitVector &CheckedVarArgs,
6386                               UncoveredArgHandler &UncoveredArg);
6387 
6388 // Determine if an expression is a string literal or constant string.
6389 // If this function returns false on the arguments to a function expecting a
6390 // format string, we will usually need to emit a warning.
6391 // True string literals are then checked by CheckFormatString.
6392 static StringLiteralCheckType
6393 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
6394                       bool HasVAListArg, unsigned format_idx,
6395                       unsigned firstDataArg, Sema::FormatStringType Type,
6396                       Sema::VariadicCallType CallType, bool InFunctionCall,
6397                       llvm::SmallBitVector &CheckedVarArgs,
6398                       UncoveredArgHandler &UncoveredArg,
6399                       llvm::APSInt Offset) {
6400  tryAgain:
6401   assert(Offset.isSigned() && "invalid offset");
6402 
6403   if (E->isTypeDependent() || E->isValueDependent())
6404     return SLCT_NotALiteral;
6405 
6406   E = E->IgnoreParenCasts();
6407 
6408   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
6409     // Technically -Wformat-nonliteral does not warn about this case.
6410     // The behavior of printf and friends in this case is implementation
6411     // dependent.  Ideally if the format string cannot be null then
6412     // it should have a 'nonnull' attribute in the function prototype.
6413     return SLCT_UncheckedLiteral;
6414 
6415   switch (E->getStmtClass()) {
6416   case Stmt::BinaryConditionalOperatorClass:
6417   case Stmt::ConditionalOperatorClass: {
6418     // The expression is a literal if both sub-expressions were, and it was
6419     // completely checked only if both sub-expressions were checked.
6420     const AbstractConditionalOperator *C =
6421         cast<AbstractConditionalOperator>(E);
6422 
6423     // Determine whether it is necessary to check both sub-expressions, for
6424     // example, because the condition expression is a constant that can be
6425     // evaluated at compile time.
6426     bool CheckLeft = true, CheckRight = true;
6427 
6428     bool Cond;
6429     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
6430       if (Cond)
6431         CheckRight = false;
6432       else
6433         CheckLeft = false;
6434     }
6435 
6436     // We need to maintain the offsets for the right and the left hand side
6437     // separately to check if every possible indexed expression is a valid
6438     // string literal. They might have different offsets for different string
6439     // literals in the end.
6440     StringLiteralCheckType Left;
6441     if (!CheckLeft)
6442       Left = SLCT_UncheckedLiteral;
6443     else {
6444       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
6445                                    HasVAListArg, format_idx, firstDataArg,
6446                                    Type, CallType, InFunctionCall,
6447                                    CheckedVarArgs, UncoveredArg, Offset);
6448       if (Left == SLCT_NotALiteral || !CheckRight) {
6449         return Left;
6450       }
6451     }
6452 
6453     StringLiteralCheckType Right =
6454         checkFormatStringExpr(S, C->getFalseExpr(), Args,
6455                               HasVAListArg, format_idx, firstDataArg,
6456                               Type, CallType, InFunctionCall, CheckedVarArgs,
6457                               UncoveredArg, Offset);
6458 
6459     return (CheckLeft && Left < Right) ? Left : Right;
6460   }
6461 
6462   case Stmt::ImplicitCastExprClass:
6463     E = cast<ImplicitCastExpr>(E)->getSubExpr();
6464     goto tryAgain;
6465 
6466   case Stmt::OpaqueValueExprClass:
6467     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
6468       E = src;
6469       goto tryAgain;
6470     }
6471     return SLCT_NotALiteral;
6472 
6473   case Stmt::PredefinedExprClass:
6474     // While __func__, etc., are technically not string literals, they
6475     // cannot contain format specifiers and thus are not a security
6476     // liability.
6477     return SLCT_UncheckedLiteral;
6478 
6479   case Stmt::DeclRefExprClass: {
6480     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6481 
6482     // As an exception, do not flag errors for variables binding to
6483     // const string literals.
6484     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
6485       bool isConstant = false;
6486       QualType T = DR->getType();
6487 
6488       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
6489         isConstant = AT->getElementType().isConstant(S.Context);
6490       } else if (const PointerType *PT = T->getAs<PointerType>()) {
6491         isConstant = T.isConstant(S.Context) &&
6492                      PT->getPointeeType().isConstant(S.Context);
6493       } else if (T->isObjCObjectPointerType()) {
6494         // In ObjC, there is usually no "const ObjectPointer" type,
6495         // so don't check if the pointee type is constant.
6496         isConstant = T.isConstant(S.Context);
6497       }
6498 
6499       if (isConstant) {
6500         if (const Expr *Init = VD->getAnyInitializer()) {
6501           // Look through initializers like const char c[] = { "foo" }
6502           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
6503             if (InitList->isStringLiteralInit())
6504               Init = InitList->getInit(0)->IgnoreParenImpCasts();
6505           }
6506           return checkFormatStringExpr(S, Init, Args,
6507                                        HasVAListArg, format_idx,
6508                                        firstDataArg, Type, CallType,
6509                                        /*InFunctionCall*/ false, CheckedVarArgs,
6510                                        UncoveredArg, Offset);
6511         }
6512       }
6513 
6514       // For vprintf* functions (i.e., HasVAListArg==true), we add a
6515       // special check to see if the format string is a function parameter
6516       // of the function calling the printf function.  If the function
6517       // has an attribute indicating it is a printf-like function, then we
6518       // should suppress warnings concerning non-literals being used in a call
6519       // to a vprintf function.  For example:
6520       //
6521       // void
6522       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
6523       //      va_list ap;
6524       //      va_start(ap, fmt);
6525       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
6526       //      ...
6527       // }
6528       if (HasVAListArg) {
6529         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
6530           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
6531             int PVIndex = PV->getFunctionScopeIndex() + 1;
6532             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
6533               // adjust for implicit parameter
6534               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6535                 if (MD->isInstance())
6536                   ++PVIndex;
6537               // We also check if the formats are compatible.
6538               // We can't pass a 'scanf' string to a 'printf' function.
6539               if (PVIndex == PVFormat->getFormatIdx() &&
6540                   Type == S.GetFormatStringType(PVFormat))
6541                 return SLCT_UncheckedLiteral;
6542             }
6543           }
6544         }
6545       }
6546     }
6547 
6548     return SLCT_NotALiteral;
6549   }
6550 
6551   case Stmt::CallExprClass:
6552   case Stmt::CXXMemberCallExprClass: {
6553     const CallExpr *CE = cast<CallExpr>(E);
6554     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
6555       bool IsFirst = true;
6556       StringLiteralCheckType CommonResult;
6557       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
6558         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
6559         StringLiteralCheckType Result = checkFormatStringExpr(
6560             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6561             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
6562         if (IsFirst) {
6563           CommonResult = Result;
6564           IsFirst = false;
6565         }
6566       }
6567       if (!IsFirst)
6568         return CommonResult;
6569 
6570       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
6571         unsigned BuiltinID = FD->getBuiltinID();
6572         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
6573             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
6574           const Expr *Arg = CE->getArg(0);
6575           return checkFormatStringExpr(S, Arg, Args,
6576                                        HasVAListArg, format_idx,
6577                                        firstDataArg, Type, CallType,
6578                                        InFunctionCall, CheckedVarArgs,
6579                                        UncoveredArg, Offset);
6580         }
6581       }
6582     }
6583 
6584     return SLCT_NotALiteral;
6585   }
6586   case Stmt::ObjCMessageExprClass: {
6587     const auto *ME = cast<ObjCMessageExpr>(E);
6588     if (const auto *ND = ME->getMethodDecl()) {
6589       if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
6590         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
6591         return checkFormatStringExpr(
6592             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6593             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
6594       }
6595     }
6596 
6597     return SLCT_NotALiteral;
6598   }
6599   case Stmt::ObjCStringLiteralClass:
6600   case Stmt::StringLiteralClass: {
6601     const StringLiteral *StrE = nullptr;
6602 
6603     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
6604       StrE = ObjCFExpr->getString();
6605     else
6606       StrE = cast<StringLiteral>(E);
6607 
6608     if (StrE) {
6609       if (Offset.isNegative() || Offset > StrE->getLength()) {
6610         // TODO: It would be better to have an explicit warning for out of
6611         // bounds literals.
6612         return SLCT_NotALiteral;
6613       }
6614       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
6615       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
6616                         firstDataArg, Type, InFunctionCall, CallType,
6617                         CheckedVarArgs, UncoveredArg);
6618       return SLCT_CheckedLiteral;
6619     }
6620 
6621     return SLCT_NotALiteral;
6622   }
6623   case Stmt::BinaryOperatorClass: {
6624     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
6625 
6626     // A string literal + an int offset is still a string literal.
6627     if (BinOp->isAdditiveOp()) {
6628       Expr::EvalResult LResult, RResult;
6629 
6630       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
6631       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
6632 
6633       if (LIsInt != RIsInt) {
6634         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
6635 
6636         if (LIsInt) {
6637           if (BinOpKind == BO_Add) {
6638             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
6639             E = BinOp->getRHS();
6640             goto tryAgain;
6641           }
6642         } else {
6643           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
6644           E = BinOp->getLHS();
6645           goto tryAgain;
6646         }
6647       }
6648     }
6649 
6650     return SLCT_NotALiteral;
6651   }
6652   case Stmt::UnaryOperatorClass: {
6653     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
6654     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
6655     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
6656       Expr::EvalResult IndexResult;
6657       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
6658         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
6659                    /*RHS is int*/ true);
6660         E = ASE->getBase();
6661         goto tryAgain;
6662       }
6663     }
6664 
6665     return SLCT_NotALiteral;
6666   }
6667 
6668   default:
6669     return SLCT_NotALiteral;
6670   }
6671 }
6672 
6673 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
6674   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
6675       .Case("scanf", FST_Scanf)
6676       .Cases("printf", "printf0", FST_Printf)
6677       .Cases("NSString", "CFString", FST_NSString)
6678       .Case("strftime", FST_Strftime)
6679       .Case("strfmon", FST_Strfmon)
6680       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
6681       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
6682       .Case("os_trace", FST_OSLog)
6683       .Case("os_log", FST_OSLog)
6684       .Default(FST_Unknown);
6685 }
6686 
6687 /// CheckFormatArguments - Check calls to printf and scanf (and similar
6688 /// functions) for correct use of format strings.
6689 /// Returns true if a format string has been fully checked.
6690 bool Sema::CheckFormatArguments(const FormatAttr *Format,
6691                                 ArrayRef<const Expr *> Args,
6692                                 bool IsCXXMember,
6693                                 VariadicCallType CallType,
6694                                 SourceLocation Loc, SourceRange Range,
6695                                 llvm::SmallBitVector &CheckedVarArgs) {
6696   FormatStringInfo FSI;
6697   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
6698     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
6699                                 FSI.FirstDataArg, GetFormatStringType(Format),
6700                                 CallType, Loc, Range, CheckedVarArgs);
6701   return false;
6702 }
6703 
6704 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
6705                                 bool HasVAListArg, unsigned format_idx,
6706                                 unsigned firstDataArg, FormatStringType Type,
6707                                 VariadicCallType CallType,
6708                                 SourceLocation Loc, SourceRange Range,
6709                                 llvm::SmallBitVector &CheckedVarArgs) {
6710   // CHECK: printf/scanf-like function is called with no format string.
6711   if (format_idx >= Args.size()) {
6712     Diag(Loc, diag::warn_missing_format_string) << Range;
6713     return false;
6714   }
6715 
6716   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
6717 
6718   // CHECK: format string is not a string literal.
6719   //
6720   // Dynamically generated format strings are difficult to
6721   // automatically vet at compile time.  Requiring that format strings
6722   // are string literals: (1) permits the checking of format strings by
6723   // the compiler and thereby (2) can practically remove the source of
6724   // many format string exploits.
6725 
6726   // Format string can be either ObjC string (e.g. @"%d") or
6727   // C string (e.g. "%d")
6728   // ObjC string uses the same format specifiers as C string, so we can use
6729   // the same format string checking logic for both ObjC and C strings.
6730   UncoveredArgHandler UncoveredArg;
6731   StringLiteralCheckType CT =
6732       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
6733                             format_idx, firstDataArg, Type, CallType,
6734                             /*IsFunctionCall*/ true, CheckedVarArgs,
6735                             UncoveredArg,
6736                             /*no string offset*/ llvm::APSInt(64, false) = 0);
6737 
6738   // Generate a diagnostic where an uncovered argument is detected.
6739   if (UncoveredArg.hasUncoveredArg()) {
6740     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
6741     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
6742     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
6743   }
6744 
6745   if (CT != SLCT_NotALiteral)
6746     // Literal format string found, check done!
6747     return CT == SLCT_CheckedLiteral;
6748 
6749   // Strftime is particular as it always uses a single 'time' argument,
6750   // so it is safe to pass a non-literal string.
6751   if (Type == FST_Strftime)
6752     return false;
6753 
6754   // Do not emit diag when the string param is a macro expansion and the
6755   // format is either NSString or CFString. This is a hack to prevent
6756   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
6757   // which are usually used in place of NS and CF string literals.
6758   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
6759   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
6760     return false;
6761 
6762   // If there are no arguments specified, warn with -Wformat-security, otherwise
6763   // warn only with -Wformat-nonliteral.
6764   if (Args.size() == firstDataArg) {
6765     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
6766       << OrigFormatExpr->getSourceRange();
6767     switch (Type) {
6768     default:
6769       break;
6770     case FST_Kprintf:
6771     case FST_FreeBSDKPrintf:
6772     case FST_Printf:
6773       Diag(FormatLoc, diag::note_format_security_fixit)
6774         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
6775       break;
6776     case FST_NSString:
6777       Diag(FormatLoc, diag::note_format_security_fixit)
6778         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
6779       break;
6780     }
6781   } else {
6782     Diag(FormatLoc, diag::warn_format_nonliteral)
6783       << OrigFormatExpr->getSourceRange();
6784   }
6785   return false;
6786 }
6787 
6788 namespace {
6789 
6790 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
6791 protected:
6792   Sema &S;
6793   const FormatStringLiteral *FExpr;
6794   const Expr *OrigFormatExpr;
6795   const Sema::FormatStringType FSType;
6796   const unsigned FirstDataArg;
6797   const unsigned NumDataArgs;
6798   const char *Beg; // Start of format string.
6799   const bool HasVAListArg;
6800   ArrayRef<const Expr *> Args;
6801   unsigned FormatIdx;
6802   llvm::SmallBitVector CoveredArgs;
6803   bool usesPositionalArgs = false;
6804   bool atFirstArg = true;
6805   bool inFunctionCall;
6806   Sema::VariadicCallType CallType;
6807   llvm::SmallBitVector &CheckedVarArgs;
6808   UncoveredArgHandler &UncoveredArg;
6809 
6810 public:
6811   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
6812                      const Expr *origFormatExpr,
6813                      const Sema::FormatStringType type, unsigned firstDataArg,
6814                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
6815                      ArrayRef<const Expr *> Args, unsigned formatIdx,
6816                      bool inFunctionCall, Sema::VariadicCallType callType,
6817                      llvm::SmallBitVector &CheckedVarArgs,
6818                      UncoveredArgHandler &UncoveredArg)
6819       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
6820         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
6821         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
6822         inFunctionCall(inFunctionCall), CallType(callType),
6823         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
6824     CoveredArgs.resize(numDataArgs);
6825     CoveredArgs.reset();
6826   }
6827 
6828   void DoneProcessing();
6829 
6830   void HandleIncompleteSpecifier(const char *startSpecifier,
6831                                  unsigned specifierLen) override;
6832 
6833   void HandleInvalidLengthModifier(
6834                            const analyze_format_string::FormatSpecifier &FS,
6835                            const analyze_format_string::ConversionSpecifier &CS,
6836                            const char *startSpecifier, unsigned specifierLen,
6837                            unsigned DiagID);
6838 
6839   void HandleNonStandardLengthModifier(
6840                     const analyze_format_string::FormatSpecifier &FS,
6841                     const char *startSpecifier, unsigned specifierLen);
6842 
6843   void HandleNonStandardConversionSpecifier(
6844                     const analyze_format_string::ConversionSpecifier &CS,
6845                     const char *startSpecifier, unsigned specifierLen);
6846 
6847   void HandlePosition(const char *startPos, unsigned posLen) override;
6848 
6849   void HandleInvalidPosition(const char *startSpecifier,
6850                              unsigned specifierLen,
6851                              analyze_format_string::PositionContext p) override;
6852 
6853   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
6854 
6855   void HandleNullChar(const char *nullCharacter) override;
6856 
6857   template <typename Range>
6858   static void
6859   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
6860                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
6861                        bool IsStringLocation, Range StringRange,
6862                        ArrayRef<FixItHint> Fixit = None);
6863 
6864 protected:
6865   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
6866                                         const char *startSpec,
6867                                         unsigned specifierLen,
6868                                         const char *csStart, unsigned csLen);
6869 
6870   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
6871                                          const char *startSpec,
6872                                          unsigned specifierLen);
6873 
6874   SourceRange getFormatStringRange();
6875   CharSourceRange getSpecifierRange(const char *startSpecifier,
6876                                     unsigned specifierLen);
6877   SourceLocation getLocationOfByte(const char *x);
6878 
6879   const Expr *getDataArg(unsigned i) const;
6880 
6881   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
6882                     const analyze_format_string::ConversionSpecifier &CS,
6883                     const char *startSpecifier, unsigned specifierLen,
6884                     unsigned argIndex);
6885 
6886   template <typename Range>
6887   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
6888                             bool IsStringLocation, Range StringRange,
6889                             ArrayRef<FixItHint> Fixit = None);
6890 };
6891 
6892 } // namespace
6893 
6894 SourceRange CheckFormatHandler::getFormatStringRange() {
6895   return OrigFormatExpr->getSourceRange();
6896 }
6897 
6898 CharSourceRange CheckFormatHandler::
6899 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
6900   SourceLocation Start = getLocationOfByte(startSpecifier);
6901   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
6902 
6903   // Advance the end SourceLocation by one due to half-open ranges.
6904   End = End.getLocWithOffset(1);
6905 
6906   return CharSourceRange::getCharRange(Start, End);
6907 }
6908 
6909 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
6910   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
6911                                   S.getLangOpts(), S.Context.getTargetInfo());
6912 }
6913 
6914 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
6915                                                    unsigned specifierLen){
6916   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
6917                        getLocationOfByte(startSpecifier),
6918                        /*IsStringLocation*/true,
6919                        getSpecifierRange(startSpecifier, specifierLen));
6920 }
6921 
6922 void CheckFormatHandler::HandleInvalidLengthModifier(
6923     const analyze_format_string::FormatSpecifier &FS,
6924     const analyze_format_string::ConversionSpecifier &CS,
6925     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
6926   using namespace analyze_format_string;
6927 
6928   const LengthModifier &LM = FS.getLengthModifier();
6929   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
6930 
6931   // See if we know how to fix this length modifier.
6932   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
6933   if (FixedLM) {
6934     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
6935                          getLocationOfByte(LM.getStart()),
6936                          /*IsStringLocation*/true,
6937                          getSpecifierRange(startSpecifier, specifierLen));
6938 
6939     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
6940       << FixedLM->toString()
6941       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
6942 
6943   } else {
6944     FixItHint Hint;
6945     if (DiagID == diag::warn_format_nonsensical_length)
6946       Hint = FixItHint::CreateRemoval(LMRange);
6947 
6948     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
6949                          getLocationOfByte(LM.getStart()),
6950                          /*IsStringLocation*/true,
6951                          getSpecifierRange(startSpecifier, specifierLen),
6952                          Hint);
6953   }
6954 }
6955 
6956 void CheckFormatHandler::HandleNonStandardLengthModifier(
6957     const analyze_format_string::FormatSpecifier &FS,
6958     const char *startSpecifier, unsigned specifierLen) {
6959   using namespace analyze_format_string;
6960 
6961   const LengthModifier &LM = FS.getLengthModifier();
6962   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
6963 
6964   // See if we know how to fix this length modifier.
6965   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
6966   if (FixedLM) {
6967     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6968                            << LM.toString() << 0,
6969                          getLocationOfByte(LM.getStart()),
6970                          /*IsStringLocation*/true,
6971                          getSpecifierRange(startSpecifier, specifierLen));
6972 
6973     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
6974       << FixedLM->toString()
6975       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
6976 
6977   } else {
6978     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6979                            << LM.toString() << 0,
6980                          getLocationOfByte(LM.getStart()),
6981                          /*IsStringLocation*/true,
6982                          getSpecifierRange(startSpecifier, specifierLen));
6983   }
6984 }
6985 
6986 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
6987     const analyze_format_string::ConversionSpecifier &CS,
6988     const char *startSpecifier, unsigned specifierLen) {
6989   using namespace analyze_format_string;
6990 
6991   // See if we know how to fix this conversion specifier.
6992   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
6993   if (FixedCS) {
6994     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6995                           << CS.toString() << /*conversion specifier*/1,
6996                          getLocationOfByte(CS.getStart()),
6997                          /*IsStringLocation*/true,
6998                          getSpecifierRange(startSpecifier, specifierLen));
6999 
7000     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
7001     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
7002       << FixedCS->toString()
7003       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
7004   } else {
7005     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7006                           << CS.toString() << /*conversion specifier*/1,
7007                          getLocationOfByte(CS.getStart()),
7008                          /*IsStringLocation*/true,
7009                          getSpecifierRange(startSpecifier, specifierLen));
7010   }
7011 }
7012 
7013 void CheckFormatHandler::HandlePosition(const char *startPos,
7014                                         unsigned posLen) {
7015   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
7016                                getLocationOfByte(startPos),
7017                                /*IsStringLocation*/true,
7018                                getSpecifierRange(startPos, posLen));
7019 }
7020 
7021 void
7022 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
7023                                      analyze_format_string::PositionContext p) {
7024   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
7025                          << (unsigned) p,
7026                        getLocationOfByte(startPos), /*IsStringLocation*/true,
7027                        getSpecifierRange(startPos, posLen));
7028 }
7029 
7030 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
7031                                             unsigned posLen) {
7032   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
7033                                getLocationOfByte(startPos),
7034                                /*IsStringLocation*/true,
7035                                getSpecifierRange(startPos, posLen));
7036 }
7037 
7038 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
7039   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
7040     // The presence of a null character is likely an error.
7041     EmitFormatDiagnostic(
7042       S.PDiag(diag::warn_printf_format_string_contains_null_char),
7043       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
7044       getFormatStringRange());
7045   }
7046 }
7047 
7048 // Note that this may return NULL if there was an error parsing or building
7049 // one of the argument expressions.
7050 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
7051   return Args[FirstDataArg + i];
7052 }
7053 
7054 void CheckFormatHandler::DoneProcessing() {
7055   // Does the number of data arguments exceed the number of
7056   // format conversions in the format string?
7057   if (!HasVAListArg) {
7058       // Find any arguments that weren't covered.
7059     CoveredArgs.flip();
7060     signed notCoveredArg = CoveredArgs.find_first();
7061     if (notCoveredArg >= 0) {
7062       assert((unsigned)notCoveredArg < NumDataArgs);
7063       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
7064     } else {
7065       UncoveredArg.setAllCovered();
7066     }
7067   }
7068 }
7069 
7070 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7071                                    const Expr *ArgExpr) {
7072   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
7073          "Invalid state");
7074 
7075   if (!ArgExpr)
7076     return;
7077 
7078   SourceLocation Loc = ArgExpr->getBeginLoc();
7079 
7080   if (S.getSourceManager().isInSystemMacro(Loc))
7081     return;
7082 
7083   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
7084   for (auto E : DiagnosticExprs)
7085     PDiag << E->getSourceRange();
7086 
7087   CheckFormatHandler::EmitFormatDiagnostic(
7088                                   S, IsFunctionCall, DiagnosticExprs[0],
7089                                   PDiag, Loc, /*IsStringLocation*/false,
7090                                   DiagnosticExprs[0]->getSourceRange());
7091 }
7092 
7093 bool
7094 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7095                                                      SourceLocation Loc,
7096                                                      const char *startSpec,
7097                                                      unsigned specifierLen,
7098                                                      const char *csStart,
7099                                                      unsigned csLen) {
7100   bool keepGoing = true;
7101   if (argIndex < NumDataArgs) {
7102     // Consider the argument coverered, even though the specifier doesn't
7103     // make sense.
7104     CoveredArgs.set(argIndex);
7105   }
7106   else {
7107     // If argIndex exceeds the number of data arguments we
7108     // don't issue a warning because that is just a cascade of warnings (and
7109     // they may have intended '%%' anyway). We don't want to continue processing
7110     // the format string after this point, however, as we will like just get
7111     // gibberish when trying to match arguments.
7112     keepGoing = false;
7113   }
7114 
7115   StringRef Specifier(csStart, csLen);
7116 
7117   // If the specifier in non-printable, it could be the first byte of a UTF-8
7118   // sequence. In that case, print the UTF-8 code point. If not, print the byte
7119   // hex value.
7120   std::string CodePointStr;
7121   if (!llvm::sys::locale::isPrint(*csStart)) {
7122     llvm::UTF32 CodePoint;
7123     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7124     const llvm::UTF8 *E =
7125         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7126     llvm::ConversionResult Result =
7127         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
7128 
7129     if (Result != llvm::conversionOK) {
7130       unsigned char FirstChar = *csStart;
7131       CodePoint = (llvm::UTF32)FirstChar;
7132     }
7133 
7134     llvm::raw_string_ostream OS(CodePointStr);
7135     if (CodePoint < 256)
7136       OS << "\\x" << llvm::format("%02x", CodePoint);
7137     else if (CodePoint <= 0xFFFF)
7138       OS << "\\u" << llvm::format("%04x", CodePoint);
7139     else
7140       OS << "\\U" << llvm::format("%08x", CodePoint);
7141     OS.flush();
7142     Specifier = CodePointStr;
7143   }
7144 
7145   EmitFormatDiagnostic(
7146       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
7147       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
7148 
7149   return keepGoing;
7150 }
7151 
7152 void
7153 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7154                                                       const char *startSpec,
7155                                                       unsigned specifierLen) {
7156   EmitFormatDiagnostic(
7157     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
7158     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
7159 }
7160 
7161 bool
7162 CheckFormatHandler::CheckNumArgs(
7163   const analyze_format_string::FormatSpecifier &FS,
7164   const analyze_format_string::ConversionSpecifier &CS,
7165   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7166 
7167   if (argIndex >= NumDataArgs) {
7168     PartialDiagnostic PDiag = FS.usesPositionalArg()
7169       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
7170            << (argIndex+1) << NumDataArgs)
7171       : S.PDiag(diag::warn_printf_insufficient_data_args);
7172     EmitFormatDiagnostic(
7173       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
7174       getSpecifierRange(startSpecifier, specifierLen));
7175 
7176     // Since more arguments than conversion tokens are given, by extension
7177     // all arguments are covered, so mark this as so.
7178     UncoveredArg.setAllCovered();
7179     return false;
7180   }
7181   return true;
7182 }
7183 
7184 template<typename Range>
7185 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
7186                                               SourceLocation Loc,
7187                                               bool IsStringLocation,
7188                                               Range StringRange,
7189                                               ArrayRef<FixItHint> FixIt) {
7190   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
7191                        Loc, IsStringLocation, StringRange, FixIt);
7192 }
7193 
7194 /// If the format string is not within the function call, emit a note
7195 /// so that the function call and string are in diagnostic messages.
7196 ///
7197 /// \param InFunctionCall if true, the format string is within the function
7198 /// call and only one diagnostic message will be produced.  Otherwise, an
7199 /// extra note will be emitted pointing to location of the format string.
7200 ///
7201 /// \param ArgumentExpr the expression that is passed as the format string
7202 /// argument in the function call.  Used for getting locations when two
7203 /// diagnostics are emitted.
7204 ///
7205 /// \param PDiag the callee should already have provided any strings for the
7206 /// diagnostic message.  This function only adds locations and fixits
7207 /// to diagnostics.
7208 ///
7209 /// \param Loc primary location for diagnostic.  If two diagnostics are
7210 /// required, one will be at Loc and a new SourceLocation will be created for
7211 /// the other one.
7212 ///
7213 /// \param IsStringLocation if true, Loc points to the format string should be
7214 /// used for the note.  Otherwise, Loc points to the argument list and will
7215 /// be used with PDiag.
7216 ///
7217 /// \param StringRange some or all of the string to highlight.  This is
7218 /// templated so it can accept either a CharSourceRange or a SourceRange.
7219 ///
7220 /// \param FixIt optional fix it hint for the format string.
7221 template <typename Range>
7222 void CheckFormatHandler::EmitFormatDiagnostic(
7223     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
7224     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
7225     Range StringRange, ArrayRef<FixItHint> FixIt) {
7226   if (InFunctionCall) {
7227     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
7228     D << StringRange;
7229     D << FixIt;
7230   } else {
7231     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
7232       << ArgumentExpr->getSourceRange();
7233 
7234     const Sema::SemaDiagnosticBuilder &Note =
7235       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
7236              diag::note_format_string_defined);
7237 
7238     Note << StringRange;
7239     Note << FixIt;
7240   }
7241 }
7242 
7243 //===--- CHECK: Printf format string checking ------------------------------===//
7244 
7245 namespace {
7246 
7247 class CheckPrintfHandler : public CheckFormatHandler {
7248 public:
7249   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7250                      const Expr *origFormatExpr,
7251                      const Sema::FormatStringType type, unsigned firstDataArg,
7252                      unsigned numDataArgs, bool isObjC, const char *beg,
7253                      bool hasVAListArg, ArrayRef<const Expr *> Args,
7254                      unsigned formatIdx, bool inFunctionCall,
7255                      Sema::VariadicCallType CallType,
7256                      llvm::SmallBitVector &CheckedVarArgs,
7257                      UncoveredArgHandler &UncoveredArg)
7258       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7259                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
7260                            inFunctionCall, CallType, CheckedVarArgs,
7261                            UncoveredArg) {}
7262 
7263   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
7264 
7265   /// Returns true if '%@' specifiers are allowed in the format string.
7266   bool allowsObjCArg() const {
7267     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
7268            FSType == Sema::FST_OSTrace;
7269   }
7270 
7271   bool HandleInvalidPrintfConversionSpecifier(
7272                                       const analyze_printf::PrintfSpecifier &FS,
7273                                       const char *startSpecifier,
7274                                       unsigned specifierLen) override;
7275 
7276   void handleInvalidMaskType(StringRef MaskType) override;
7277 
7278   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7279                              const char *startSpecifier,
7280                              unsigned specifierLen) override;
7281   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7282                        const char *StartSpecifier,
7283                        unsigned SpecifierLen,
7284                        const Expr *E);
7285 
7286   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
7287                     const char *startSpecifier, unsigned specifierLen);
7288   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
7289                            const analyze_printf::OptionalAmount &Amt,
7290                            unsigned type,
7291                            const char *startSpecifier, unsigned specifierLen);
7292   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7293                   const analyze_printf::OptionalFlag &flag,
7294                   const char *startSpecifier, unsigned specifierLen);
7295   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
7296                          const analyze_printf::OptionalFlag &ignoredFlag,
7297                          const analyze_printf::OptionalFlag &flag,
7298                          const char *startSpecifier, unsigned specifierLen);
7299   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
7300                            const Expr *E);
7301 
7302   void HandleEmptyObjCModifierFlag(const char *startFlag,
7303                                    unsigned flagLen) override;
7304 
7305   void HandleInvalidObjCModifierFlag(const char *startFlag,
7306                                             unsigned flagLen) override;
7307 
7308   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
7309                                            const char *flagsEnd,
7310                                            const char *conversionPosition)
7311                                              override;
7312 };
7313 
7314 } // namespace
7315 
7316 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
7317                                       const analyze_printf::PrintfSpecifier &FS,
7318                                       const char *startSpecifier,
7319                                       unsigned specifierLen) {
7320   const analyze_printf::PrintfConversionSpecifier &CS =
7321     FS.getConversionSpecifier();
7322 
7323   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7324                                           getLocationOfByte(CS.getStart()),
7325                                           startSpecifier, specifierLen,
7326                                           CS.getStart(), CS.getLength());
7327 }
7328 
7329 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
7330   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
7331 }
7332 
7333 bool CheckPrintfHandler::HandleAmount(
7334                                const analyze_format_string::OptionalAmount &Amt,
7335                                unsigned k, const char *startSpecifier,
7336                                unsigned specifierLen) {
7337   if (Amt.hasDataArgument()) {
7338     if (!HasVAListArg) {
7339       unsigned argIndex = Amt.getArgIndex();
7340       if (argIndex >= NumDataArgs) {
7341         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
7342                                << k,
7343                              getLocationOfByte(Amt.getStart()),
7344                              /*IsStringLocation*/true,
7345                              getSpecifierRange(startSpecifier, specifierLen));
7346         // Don't do any more checking.  We will just emit
7347         // spurious errors.
7348         return false;
7349       }
7350 
7351       // Type check the data argument.  It should be an 'int'.
7352       // Although not in conformance with C99, we also allow the argument to be
7353       // an 'unsigned int' as that is a reasonably safe case.  GCC also
7354       // doesn't emit a warning for that case.
7355       CoveredArgs.set(argIndex);
7356       const Expr *Arg = getDataArg(argIndex);
7357       if (!Arg)
7358         return false;
7359 
7360       QualType T = Arg->getType();
7361 
7362       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
7363       assert(AT.isValid());
7364 
7365       if (!AT.matchesType(S.Context, T)) {
7366         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
7367                                << k << AT.getRepresentativeTypeName(S.Context)
7368                                << T << Arg->getSourceRange(),
7369                              getLocationOfByte(Amt.getStart()),
7370                              /*IsStringLocation*/true,
7371                              getSpecifierRange(startSpecifier, specifierLen));
7372         // Don't do any more checking.  We will just emit
7373         // spurious errors.
7374         return false;
7375       }
7376     }
7377   }
7378   return true;
7379 }
7380 
7381 void CheckPrintfHandler::HandleInvalidAmount(
7382                                       const analyze_printf::PrintfSpecifier &FS,
7383                                       const analyze_printf::OptionalAmount &Amt,
7384                                       unsigned type,
7385                                       const char *startSpecifier,
7386                                       unsigned specifierLen) {
7387   const analyze_printf::PrintfConversionSpecifier &CS =
7388     FS.getConversionSpecifier();
7389 
7390   FixItHint fixit =
7391     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
7392       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
7393                                  Amt.getConstantLength()))
7394       : FixItHint();
7395 
7396   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
7397                          << type << CS.toString(),
7398                        getLocationOfByte(Amt.getStart()),
7399                        /*IsStringLocation*/true,
7400                        getSpecifierRange(startSpecifier, specifierLen),
7401                        fixit);
7402 }
7403 
7404 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7405                                     const analyze_printf::OptionalFlag &flag,
7406                                     const char *startSpecifier,
7407                                     unsigned specifierLen) {
7408   // Warn about pointless flag with a fixit removal.
7409   const analyze_printf::PrintfConversionSpecifier &CS =
7410     FS.getConversionSpecifier();
7411   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
7412                          << flag.toString() << CS.toString(),
7413                        getLocationOfByte(flag.getPosition()),
7414                        /*IsStringLocation*/true,
7415                        getSpecifierRange(startSpecifier, specifierLen),
7416                        FixItHint::CreateRemoval(
7417                          getSpecifierRange(flag.getPosition(), 1)));
7418 }
7419 
7420 void CheckPrintfHandler::HandleIgnoredFlag(
7421                                 const analyze_printf::PrintfSpecifier &FS,
7422                                 const analyze_printf::OptionalFlag &ignoredFlag,
7423                                 const analyze_printf::OptionalFlag &flag,
7424                                 const char *startSpecifier,
7425                                 unsigned specifierLen) {
7426   // Warn about ignored flag with a fixit removal.
7427   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
7428                          << ignoredFlag.toString() << flag.toString(),
7429                        getLocationOfByte(ignoredFlag.getPosition()),
7430                        /*IsStringLocation*/true,
7431                        getSpecifierRange(startSpecifier, specifierLen),
7432                        FixItHint::CreateRemoval(
7433                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
7434 }
7435 
7436 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
7437                                                      unsigned flagLen) {
7438   // Warn about an empty flag.
7439   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
7440                        getLocationOfByte(startFlag),
7441                        /*IsStringLocation*/true,
7442                        getSpecifierRange(startFlag, flagLen));
7443 }
7444 
7445 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
7446                                                        unsigned flagLen) {
7447   // Warn about an invalid flag.
7448   auto Range = getSpecifierRange(startFlag, flagLen);
7449   StringRef flag(startFlag, flagLen);
7450   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
7451                       getLocationOfByte(startFlag),
7452                       /*IsStringLocation*/true,
7453                       Range, FixItHint::CreateRemoval(Range));
7454 }
7455 
7456 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
7457     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
7458     // Warn about using '[...]' without a '@' conversion.
7459     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
7460     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
7461     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
7462                          getLocationOfByte(conversionPosition),
7463                          /*IsStringLocation*/true,
7464                          Range, FixItHint::CreateRemoval(Range));
7465 }
7466 
7467 // Determines if the specified is a C++ class or struct containing
7468 // a member with the specified name and kind (e.g. a CXXMethodDecl named
7469 // "c_str()").
7470 template<typename MemberKind>
7471 static llvm::SmallPtrSet<MemberKind*, 1>
7472 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
7473   const RecordType *RT = Ty->getAs<RecordType>();
7474   llvm::SmallPtrSet<MemberKind*, 1> Results;
7475 
7476   if (!RT)
7477     return Results;
7478   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
7479   if (!RD || !RD->getDefinition())
7480     return Results;
7481 
7482   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
7483                  Sema::LookupMemberName);
7484   R.suppressDiagnostics();
7485 
7486   // We just need to include all members of the right kind turned up by the
7487   // filter, at this point.
7488   if (S.LookupQualifiedName(R, RT->getDecl()))
7489     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7490       NamedDecl *decl = (*I)->getUnderlyingDecl();
7491       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
7492         Results.insert(FK);
7493     }
7494   return Results;
7495 }
7496 
7497 /// Check if we could call '.c_str()' on an object.
7498 ///
7499 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
7500 /// allow the call, or if it would be ambiguous).
7501 bool Sema::hasCStrMethod(const Expr *E) {
7502   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7503 
7504   MethodSet Results =
7505       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
7506   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7507        MI != ME; ++MI)
7508     if ((*MI)->getMinRequiredArguments() == 0)
7509       return true;
7510   return false;
7511 }
7512 
7513 // Check if a (w)string was passed when a (w)char* was needed, and offer a
7514 // better diagnostic if so. AT is assumed to be valid.
7515 // Returns true when a c_str() conversion method is found.
7516 bool CheckPrintfHandler::checkForCStrMembers(
7517     const analyze_printf::ArgType &AT, const Expr *E) {
7518   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7519 
7520   MethodSet Results =
7521       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
7522 
7523   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7524        MI != ME; ++MI) {
7525     const CXXMethodDecl *Method = *MI;
7526     if (Method->getMinRequiredArguments() == 0 &&
7527         AT.matchesType(S.Context, Method->getReturnType())) {
7528       // FIXME: Suggest parens if the expression needs them.
7529       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
7530       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
7531           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
7532       return true;
7533     }
7534   }
7535 
7536   return false;
7537 }
7538 
7539 bool
7540 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
7541                                             &FS,
7542                                           const char *startSpecifier,
7543                                           unsigned specifierLen) {
7544   using namespace analyze_format_string;
7545   using namespace analyze_printf;
7546 
7547   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
7548 
7549   if (FS.consumesDataArgument()) {
7550     if (atFirstArg) {
7551         atFirstArg = false;
7552         usesPositionalArgs = FS.usesPositionalArg();
7553     }
7554     else if (usesPositionalArgs != FS.usesPositionalArg()) {
7555       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
7556                                         startSpecifier, specifierLen);
7557       return false;
7558     }
7559   }
7560 
7561   // First check if the field width, precision, and conversion specifier
7562   // have matching data arguments.
7563   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
7564                     startSpecifier, specifierLen)) {
7565     return false;
7566   }
7567 
7568   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
7569                     startSpecifier, specifierLen)) {
7570     return false;
7571   }
7572 
7573   if (!CS.consumesDataArgument()) {
7574     // FIXME: Technically specifying a precision or field width here
7575     // makes no sense.  Worth issuing a warning at some point.
7576     return true;
7577   }
7578 
7579   // Consume the argument.
7580   unsigned argIndex = FS.getArgIndex();
7581   if (argIndex < NumDataArgs) {
7582     // The check to see if the argIndex is valid will come later.
7583     // We set the bit here because we may exit early from this
7584     // function if we encounter some other error.
7585     CoveredArgs.set(argIndex);
7586   }
7587 
7588   // FreeBSD kernel extensions.
7589   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
7590       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
7591     // We need at least two arguments.
7592     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
7593       return false;
7594 
7595     // Claim the second argument.
7596     CoveredArgs.set(argIndex + 1);
7597 
7598     // Type check the first argument (int for %b, pointer for %D)
7599     const Expr *Ex = getDataArg(argIndex);
7600     const analyze_printf::ArgType &AT =
7601       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
7602         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
7603     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
7604       EmitFormatDiagnostic(
7605           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7606               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
7607               << false << Ex->getSourceRange(),
7608           Ex->getBeginLoc(), /*IsStringLocation*/ false,
7609           getSpecifierRange(startSpecifier, specifierLen));
7610 
7611     // Type check the second argument (char * for both %b and %D)
7612     Ex = getDataArg(argIndex + 1);
7613     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
7614     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
7615       EmitFormatDiagnostic(
7616           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7617               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
7618               << false << Ex->getSourceRange(),
7619           Ex->getBeginLoc(), /*IsStringLocation*/ false,
7620           getSpecifierRange(startSpecifier, specifierLen));
7621 
7622      return true;
7623   }
7624 
7625   // Check for using an Objective-C specific conversion specifier
7626   // in a non-ObjC literal.
7627   if (!allowsObjCArg() && CS.isObjCArg()) {
7628     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7629                                                   specifierLen);
7630   }
7631 
7632   // %P can only be used with os_log.
7633   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
7634     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7635                                                   specifierLen);
7636   }
7637 
7638   // %n is not allowed with os_log.
7639   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
7640     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
7641                          getLocationOfByte(CS.getStart()),
7642                          /*IsStringLocation*/ false,
7643                          getSpecifierRange(startSpecifier, specifierLen));
7644 
7645     return true;
7646   }
7647 
7648   // Only scalars are allowed for os_trace.
7649   if (FSType == Sema::FST_OSTrace &&
7650       (CS.getKind() == ConversionSpecifier::PArg ||
7651        CS.getKind() == ConversionSpecifier::sArg ||
7652        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
7653     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7654                                                   specifierLen);
7655   }
7656 
7657   // Check for use of public/private annotation outside of os_log().
7658   if (FSType != Sema::FST_OSLog) {
7659     if (FS.isPublic().isSet()) {
7660       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7661                                << "public",
7662                            getLocationOfByte(FS.isPublic().getPosition()),
7663                            /*IsStringLocation*/ false,
7664                            getSpecifierRange(startSpecifier, specifierLen));
7665     }
7666     if (FS.isPrivate().isSet()) {
7667       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7668                                << "private",
7669                            getLocationOfByte(FS.isPrivate().getPosition()),
7670                            /*IsStringLocation*/ false,
7671                            getSpecifierRange(startSpecifier, specifierLen));
7672     }
7673   }
7674 
7675   // Check for invalid use of field width
7676   if (!FS.hasValidFieldWidth()) {
7677     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
7678         startSpecifier, specifierLen);
7679   }
7680 
7681   // Check for invalid use of precision
7682   if (!FS.hasValidPrecision()) {
7683     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
7684         startSpecifier, specifierLen);
7685   }
7686 
7687   // Precision is mandatory for %P specifier.
7688   if (CS.getKind() == ConversionSpecifier::PArg &&
7689       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
7690     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
7691                          getLocationOfByte(startSpecifier),
7692                          /*IsStringLocation*/ false,
7693                          getSpecifierRange(startSpecifier, specifierLen));
7694   }
7695 
7696   // Check each flag does not conflict with any other component.
7697   if (!FS.hasValidThousandsGroupingPrefix())
7698     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
7699   if (!FS.hasValidLeadingZeros())
7700     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
7701   if (!FS.hasValidPlusPrefix())
7702     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
7703   if (!FS.hasValidSpacePrefix())
7704     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
7705   if (!FS.hasValidAlternativeForm())
7706     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
7707   if (!FS.hasValidLeftJustified())
7708     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
7709 
7710   // Check that flags are not ignored by another flag
7711   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
7712     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
7713         startSpecifier, specifierLen);
7714   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
7715     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
7716             startSpecifier, specifierLen);
7717 
7718   // Check the length modifier is valid with the given conversion specifier.
7719   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
7720                                  S.getLangOpts()))
7721     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7722                                 diag::warn_format_nonsensical_length);
7723   else if (!FS.hasStandardLengthModifier())
7724     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
7725   else if (!FS.hasStandardLengthConversionCombination())
7726     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7727                                 diag::warn_format_non_standard_conversion_spec);
7728 
7729   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
7730     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
7731 
7732   // The remaining checks depend on the data arguments.
7733   if (HasVAListArg)
7734     return true;
7735 
7736   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
7737     return false;
7738 
7739   const Expr *Arg = getDataArg(argIndex);
7740   if (!Arg)
7741     return true;
7742 
7743   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
7744 }
7745 
7746 static bool requiresParensToAddCast(const Expr *E) {
7747   // FIXME: We should have a general way to reason about operator
7748   // precedence and whether parens are actually needed here.
7749   // Take care of a few common cases where they aren't.
7750   const Expr *Inside = E->IgnoreImpCasts();
7751   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
7752     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
7753 
7754   switch (Inside->getStmtClass()) {
7755   case Stmt::ArraySubscriptExprClass:
7756   case Stmt::CallExprClass:
7757   case Stmt::CharacterLiteralClass:
7758   case Stmt::CXXBoolLiteralExprClass:
7759   case Stmt::DeclRefExprClass:
7760   case Stmt::FloatingLiteralClass:
7761   case Stmt::IntegerLiteralClass:
7762   case Stmt::MemberExprClass:
7763   case Stmt::ObjCArrayLiteralClass:
7764   case Stmt::ObjCBoolLiteralExprClass:
7765   case Stmt::ObjCBoxedExprClass:
7766   case Stmt::ObjCDictionaryLiteralClass:
7767   case Stmt::ObjCEncodeExprClass:
7768   case Stmt::ObjCIvarRefExprClass:
7769   case Stmt::ObjCMessageExprClass:
7770   case Stmt::ObjCPropertyRefExprClass:
7771   case Stmt::ObjCStringLiteralClass:
7772   case Stmt::ObjCSubscriptRefExprClass:
7773   case Stmt::ParenExprClass:
7774   case Stmt::StringLiteralClass:
7775   case Stmt::UnaryOperatorClass:
7776     return false;
7777   default:
7778     return true;
7779   }
7780 }
7781 
7782 static std::pair<QualType, StringRef>
7783 shouldNotPrintDirectly(const ASTContext &Context,
7784                        QualType IntendedTy,
7785                        const Expr *E) {
7786   // Use a 'while' to peel off layers of typedefs.
7787   QualType TyTy = IntendedTy;
7788   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
7789     StringRef Name = UserTy->getDecl()->getName();
7790     QualType CastTy = llvm::StringSwitch<QualType>(Name)
7791       .Case("CFIndex", Context.getNSIntegerType())
7792       .Case("NSInteger", Context.getNSIntegerType())
7793       .Case("NSUInteger", Context.getNSUIntegerType())
7794       .Case("SInt32", Context.IntTy)
7795       .Case("UInt32", Context.UnsignedIntTy)
7796       .Default(QualType());
7797 
7798     if (!CastTy.isNull())
7799       return std::make_pair(CastTy, Name);
7800 
7801     TyTy = UserTy->desugar();
7802   }
7803 
7804   // Strip parens if necessary.
7805   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
7806     return shouldNotPrintDirectly(Context,
7807                                   PE->getSubExpr()->getType(),
7808                                   PE->getSubExpr());
7809 
7810   // If this is a conditional expression, then its result type is constructed
7811   // via usual arithmetic conversions and thus there might be no necessary
7812   // typedef sugar there.  Recurse to operands to check for NSInteger &
7813   // Co. usage condition.
7814   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
7815     QualType TrueTy, FalseTy;
7816     StringRef TrueName, FalseName;
7817 
7818     std::tie(TrueTy, TrueName) =
7819       shouldNotPrintDirectly(Context,
7820                              CO->getTrueExpr()->getType(),
7821                              CO->getTrueExpr());
7822     std::tie(FalseTy, FalseName) =
7823       shouldNotPrintDirectly(Context,
7824                              CO->getFalseExpr()->getType(),
7825                              CO->getFalseExpr());
7826 
7827     if (TrueTy == FalseTy)
7828       return std::make_pair(TrueTy, TrueName);
7829     else if (TrueTy.isNull())
7830       return std::make_pair(FalseTy, FalseName);
7831     else if (FalseTy.isNull())
7832       return std::make_pair(TrueTy, TrueName);
7833   }
7834 
7835   return std::make_pair(QualType(), StringRef());
7836 }
7837 
7838 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
7839 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
7840 /// type do not count.
7841 static bool
7842 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
7843   QualType From = ICE->getSubExpr()->getType();
7844   QualType To = ICE->getType();
7845   // It's an integer promotion if the destination type is the promoted
7846   // source type.
7847   if (ICE->getCastKind() == CK_IntegralCast &&
7848       From->isPromotableIntegerType() &&
7849       S.Context.getPromotedIntegerType(From) == To)
7850     return true;
7851   // Look through vector types, since we do default argument promotion for
7852   // those in OpenCL.
7853   if (const auto *VecTy = From->getAs<ExtVectorType>())
7854     From = VecTy->getElementType();
7855   if (const auto *VecTy = To->getAs<ExtVectorType>())
7856     To = VecTy->getElementType();
7857   // It's a floating promotion if the source type is a lower rank.
7858   return ICE->getCastKind() == CK_FloatingCast &&
7859          S.Context.getFloatingTypeOrder(From, To) < 0;
7860 }
7861 
7862 bool
7863 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7864                                     const char *StartSpecifier,
7865                                     unsigned SpecifierLen,
7866                                     const Expr *E) {
7867   using namespace analyze_format_string;
7868   using namespace analyze_printf;
7869 
7870   // Now type check the data expression that matches the
7871   // format specifier.
7872   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
7873   if (!AT.isValid())
7874     return true;
7875 
7876   QualType ExprTy = E->getType();
7877   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
7878     ExprTy = TET->getUnderlyingExpr()->getType();
7879   }
7880 
7881   const analyze_printf::ArgType::MatchKind Match =
7882       AT.matchesType(S.Context, ExprTy);
7883   bool Pedantic = Match == analyze_printf::ArgType::NoMatchPedantic;
7884   if (Match == analyze_printf::ArgType::Match)
7885     return true;
7886 
7887   // Look through argument promotions for our error message's reported type.
7888   // This includes the integral and floating promotions, but excludes array
7889   // and function pointer decay (seeing that an argument intended to be a
7890   // string has type 'char [6]' is probably more confusing than 'char *') and
7891   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
7892   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
7893     if (isArithmeticArgumentPromotion(S, ICE)) {
7894       E = ICE->getSubExpr();
7895       ExprTy = E->getType();
7896 
7897       // Check if we didn't match because of an implicit cast from a 'char'
7898       // or 'short' to an 'int'.  This is done because printf is a varargs
7899       // function.
7900       if (ICE->getType() == S.Context.IntTy ||
7901           ICE->getType() == S.Context.UnsignedIntTy) {
7902         // All further checking is done on the subexpression.
7903         if (AT.matchesType(S.Context, ExprTy))
7904           return true;
7905       }
7906     }
7907   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
7908     // Special case for 'a', which has type 'int' in C.
7909     // Note, however, that we do /not/ want to treat multibyte constants like
7910     // 'MooV' as characters! This form is deprecated but still exists.
7911     if (ExprTy == S.Context.IntTy)
7912       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
7913         ExprTy = S.Context.CharTy;
7914   }
7915 
7916   // Look through enums to their underlying type.
7917   bool IsEnum = false;
7918   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
7919     ExprTy = EnumTy->getDecl()->getIntegerType();
7920     IsEnum = true;
7921   }
7922 
7923   // %C in an Objective-C context prints a unichar, not a wchar_t.
7924   // If the argument is an integer of some kind, believe the %C and suggest
7925   // a cast instead of changing the conversion specifier.
7926   QualType IntendedTy = ExprTy;
7927   if (isObjCContext() &&
7928       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
7929     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
7930         !ExprTy->isCharType()) {
7931       // 'unichar' is defined as a typedef of unsigned short, but we should
7932       // prefer using the typedef if it is visible.
7933       IntendedTy = S.Context.UnsignedShortTy;
7934 
7935       // While we are here, check if the value is an IntegerLiteral that happens
7936       // to be within the valid range.
7937       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
7938         const llvm::APInt &V = IL->getValue();
7939         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
7940           return true;
7941       }
7942 
7943       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
7944                           Sema::LookupOrdinaryName);
7945       if (S.LookupName(Result, S.getCurScope())) {
7946         NamedDecl *ND = Result.getFoundDecl();
7947         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
7948           if (TD->getUnderlyingType() == IntendedTy)
7949             IntendedTy = S.Context.getTypedefType(TD);
7950       }
7951     }
7952   }
7953 
7954   // Special-case some of Darwin's platform-independence types by suggesting
7955   // casts to primitive types that are known to be large enough.
7956   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
7957   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
7958     QualType CastTy;
7959     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
7960     if (!CastTy.isNull()) {
7961       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
7962       // (long in ASTContext). Only complain to pedants.
7963       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
7964           (AT.isSizeT() || AT.isPtrdiffT()) &&
7965           AT.matchesType(S.Context, CastTy))
7966         Pedantic = true;
7967       IntendedTy = CastTy;
7968       ShouldNotPrintDirectly = true;
7969     }
7970   }
7971 
7972   // We may be able to offer a FixItHint if it is a supported type.
7973   PrintfSpecifier fixedFS = FS;
7974   bool Success =
7975       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
7976 
7977   if (Success) {
7978     // Get the fix string from the fixed format specifier
7979     SmallString<16> buf;
7980     llvm::raw_svector_ostream os(buf);
7981     fixedFS.toString(os);
7982 
7983     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
7984 
7985     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
7986       unsigned Diag =
7987           Pedantic
7988               ? diag::warn_format_conversion_argument_type_mismatch_pedantic
7989               : diag::warn_format_conversion_argument_type_mismatch;
7990       // In this case, the specifier is wrong and should be changed to match
7991       // the argument.
7992       EmitFormatDiagnostic(S.PDiag(Diag)
7993                                << AT.getRepresentativeTypeName(S.Context)
7994                                << IntendedTy << IsEnum << E->getSourceRange(),
7995                            E->getBeginLoc(),
7996                            /*IsStringLocation*/ false, SpecRange,
7997                            FixItHint::CreateReplacement(SpecRange, os.str()));
7998     } else {
7999       // The canonical type for formatting this value is different from the
8000       // actual type of the expression. (This occurs, for example, with Darwin's
8001       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
8002       // should be printed as 'long' for 64-bit compatibility.)
8003       // Rather than emitting a normal format/argument mismatch, we want to
8004       // add a cast to the recommended type (and correct the format string
8005       // if necessary).
8006       SmallString<16> CastBuf;
8007       llvm::raw_svector_ostream CastFix(CastBuf);
8008       CastFix << "(";
8009       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
8010       CastFix << ")";
8011 
8012       SmallVector<FixItHint,4> Hints;
8013       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
8014         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
8015 
8016       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
8017         // If there's already a cast present, just replace it.
8018         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
8019         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
8020 
8021       } else if (!requiresParensToAddCast(E)) {
8022         // If the expression has high enough precedence,
8023         // just write the C-style cast.
8024         Hints.push_back(
8025             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8026       } else {
8027         // Otherwise, add parens around the expression as well as the cast.
8028         CastFix << "(";
8029         Hints.push_back(
8030             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8031 
8032         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
8033         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
8034       }
8035 
8036       if (ShouldNotPrintDirectly) {
8037         // The expression has a type that should not be printed directly.
8038         // We extract the name from the typedef because we don't want to show
8039         // the underlying type in the diagnostic.
8040         StringRef Name;
8041         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
8042           Name = TypedefTy->getDecl()->getName();
8043         else
8044           Name = CastTyName;
8045         unsigned Diag = Pedantic
8046                             ? diag::warn_format_argument_needs_cast_pedantic
8047                             : diag::warn_format_argument_needs_cast;
8048         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
8049                                            << E->getSourceRange(),
8050                              E->getBeginLoc(), /*IsStringLocation=*/false,
8051                              SpecRange, Hints);
8052       } else {
8053         // In this case, the expression could be printed using a different
8054         // specifier, but we've decided that the specifier is probably correct
8055         // and we should cast instead. Just use the normal warning message.
8056         EmitFormatDiagnostic(
8057             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8058                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
8059                 << E->getSourceRange(),
8060             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
8061       }
8062     }
8063   } else {
8064     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
8065                                                    SpecifierLen);
8066     // Since the warning for passing non-POD types to variadic functions
8067     // was deferred until now, we emit a warning for non-POD
8068     // arguments here.
8069     switch (S.isValidVarArgType(ExprTy)) {
8070     case Sema::VAK_Valid:
8071     case Sema::VAK_ValidInCXX11: {
8072       unsigned Diag =
8073           Pedantic
8074               ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8075               : diag::warn_format_conversion_argument_type_mismatch;
8076 
8077       EmitFormatDiagnostic(
8078           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
8079                         << IsEnum << CSR << E->getSourceRange(),
8080           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8081       break;
8082     }
8083     case Sema::VAK_Undefined:
8084     case Sema::VAK_MSVCUndefined:
8085       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
8086                                << S.getLangOpts().CPlusPlus11 << ExprTy
8087                                << CallType
8088                                << AT.getRepresentativeTypeName(S.Context) << CSR
8089                                << E->getSourceRange(),
8090                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8091       checkForCStrMembers(AT, E);
8092       break;
8093 
8094     case Sema::VAK_Invalid:
8095       if (ExprTy->isObjCObjectType())
8096         EmitFormatDiagnostic(
8097             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
8098                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
8099                 << AT.getRepresentativeTypeName(S.Context) << CSR
8100                 << E->getSourceRange(),
8101             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8102       else
8103         // FIXME: If this is an initializer list, suggest removing the braces
8104         // or inserting a cast to the target type.
8105         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
8106             << isa<InitListExpr>(E) << ExprTy << CallType
8107             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
8108       break;
8109     }
8110 
8111     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
8112            "format string specifier index out of range");
8113     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
8114   }
8115 
8116   return true;
8117 }
8118 
8119 //===--- CHECK: Scanf format string checking ------------------------------===//
8120 
8121 namespace {
8122 
8123 class CheckScanfHandler : public CheckFormatHandler {
8124 public:
8125   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
8126                     const Expr *origFormatExpr, Sema::FormatStringType type,
8127                     unsigned firstDataArg, unsigned numDataArgs,
8128                     const char *beg, bool hasVAListArg,
8129                     ArrayRef<const Expr *> Args, unsigned formatIdx,
8130                     bool inFunctionCall, Sema::VariadicCallType CallType,
8131                     llvm::SmallBitVector &CheckedVarArgs,
8132                     UncoveredArgHandler &UncoveredArg)
8133       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8134                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8135                            inFunctionCall, CallType, CheckedVarArgs,
8136                            UncoveredArg) {}
8137 
8138   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
8139                             const char *startSpecifier,
8140                             unsigned specifierLen) override;
8141 
8142   bool HandleInvalidScanfConversionSpecifier(
8143           const analyze_scanf::ScanfSpecifier &FS,
8144           const char *startSpecifier,
8145           unsigned specifierLen) override;
8146 
8147   void HandleIncompleteScanList(const char *start, const char *end) override;
8148 };
8149 
8150 } // namespace
8151 
8152 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
8153                                                  const char *end) {
8154   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
8155                        getLocationOfByte(end), /*IsStringLocation*/true,
8156                        getSpecifierRange(start, end - start));
8157 }
8158 
8159 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
8160                                         const analyze_scanf::ScanfSpecifier &FS,
8161                                         const char *startSpecifier,
8162                                         unsigned specifierLen) {
8163   const analyze_scanf::ScanfConversionSpecifier &CS =
8164     FS.getConversionSpecifier();
8165 
8166   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8167                                           getLocationOfByte(CS.getStart()),
8168                                           startSpecifier, specifierLen,
8169                                           CS.getStart(), CS.getLength());
8170 }
8171 
8172 bool CheckScanfHandler::HandleScanfSpecifier(
8173                                        const analyze_scanf::ScanfSpecifier &FS,
8174                                        const char *startSpecifier,
8175                                        unsigned specifierLen) {
8176   using namespace analyze_scanf;
8177   using namespace analyze_format_string;
8178 
8179   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
8180 
8181   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
8182   // be used to decide if we are using positional arguments consistently.
8183   if (FS.consumesDataArgument()) {
8184     if (atFirstArg) {
8185       atFirstArg = false;
8186       usesPositionalArgs = FS.usesPositionalArg();
8187     }
8188     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8189       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8190                                         startSpecifier, specifierLen);
8191       return false;
8192     }
8193   }
8194 
8195   // Check if the field with is non-zero.
8196   const OptionalAmount &Amt = FS.getFieldWidth();
8197   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
8198     if (Amt.getConstantAmount() == 0) {
8199       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
8200                                                    Amt.getConstantLength());
8201       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
8202                            getLocationOfByte(Amt.getStart()),
8203                            /*IsStringLocation*/true, R,
8204                            FixItHint::CreateRemoval(R));
8205     }
8206   }
8207 
8208   if (!FS.consumesDataArgument()) {
8209     // FIXME: Technically specifying a precision or field width here
8210     // makes no sense.  Worth issuing a warning at some point.
8211     return true;
8212   }
8213 
8214   // Consume the argument.
8215   unsigned argIndex = FS.getArgIndex();
8216   if (argIndex < NumDataArgs) {
8217       // The check to see if the argIndex is valid will come later.
8218       // We set the bit here because we may exit early from this
8219       // function if we encounter some other error.
8220     CoveredArgs.set(argIndex);
8221   }
8222 
8223   // Check the length modifier is valid with the given conversion specifier.
8224   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8225                                  S.getLangOpts()))
8226     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8227                                 diag::warn_format_nonsensical_length);
8228   else if (!FS.hasStandardLengthModifier())
8229     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8230   else if (!FS.hasStandardLengthConversionCombination())
8231     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8232                                 diag::warn_format_non_standard_conversion_spec);
8233 
8234   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8235     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8236 
8237   // The remaining checks depend on the data arguments.
8238   if (HasVAListArg)
8239     return true;
8240 
8241   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8242     return false;
8243 
8244   // Check that the argument type matches the format specifier.
8245   const Expr *Ex = getDataArg(argIndex);
8246   if (!Ex)
8247     return true;
8248 
8249   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
8250 
8251   if (!AT.isValid()) {
8252     return true;
8253   }
8254 
8255   analyze_format_string::ArgType::MatchKind Match =
8256       AT.matchesType(S.Context, Ex->getType());
8257   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
8258   if (Match == analyze_format_string::ArgType::Match)
8259     return true;
8260 
8261   ScanfSpecifier fixedFS = FS;
8262   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
8263                                  S.getLangOpts(), S.Context);
8264 
8265   unsigned Diag =
8266       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8267                : diag::warn_format_conversion_argument_type_mismatch;
8268 
8269   if (Success) {
8270     // Get the fix string from the fixed format specifier.
8271     SmallString<128> buf;
8272     llvm::raw_svector_ostream os(buf);
8273     fixedFS.toString(os);
8274 
8275     EmitFormatDiagnostic(
8276         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
8277                       << Ex->getType() << false << Ex->getSourceRange(),
8278         Ex->getBeginLoc(),
8279         /*IsStringLocation*/ false,
8280         getSpecifierRange(startSpecifier, specifierLen),
8281         FixItHint::CreateReplacement(
8282             getSpecifierRange(startSpecifier, specifierLen), os.str()));
8283   } else {
8284     EmitFormatDiagnostic(S.PDiag(Diag)
8285                              << AT.getRepresentativeTypeName(S.Context)
8286                              << Ex->getType() << false << Ex->getSourceRange(),
8287                          Ex->getBeginLoc(),
8288                          /*IsStringLocation*/ false,
8289                          getSpecifierRange(startSpecifier, specifierLen));
8290   }
8291 
8292   return true;
8293 }
8294 
8295 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
8296                               const Expr *OrigFormatExpr,
8297                               ArrayRef<const Expr *> Args,
8298                               bool HasVAListArg, unsigned format_idx,
8299                               unsigned firstDataArg,
8300                               Sema::FormatStringType Type,
8301                               bool inFunctionCall,
8302                               Sema::VariadicCallType CallType,
8303                               llvm::SmallBitVector &CheckedVarArgs,
8304                               UncoveredArgHandler &UncoveredArg) {
8305   // CHECK: is the format string a wide literal?
8306   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
8307     CheckFormatHandler::EmitFormatDiagnostic(
8308         S, inFunctionCall, Args[format_idx],
8309         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
8310         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8311     return;
8312   }
8313 
8314   // Str - The format string.  NOTE: this is NOT null-terminated!
8315   StringRef StrRef = FExpr->getString();
8316   const char *Str = StrRef.data();
8317   // Account for cases where the string literal is truncated in a declaration.
8318   const ConstantArrayType *T =
8319     S.Context.getAsConstantArrayType(FExpr->getType());
8320   assert(T && "String literal not of constant array type!");
8321   size_t TypeSize = T->getSize().getZExtValue();
8322   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8323   const unsigned numDataArgs = Args.size() - firstDataArg;
8324 
8325   // Emit a warning if the string literal is truncated and does not contain an
8326   // embedded null character.
8327   if (TypeSize <= StrRef.size() &&
8328       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
8329     CheckFormatHandler::EmitFormatDiagnostic(
8330         S, inFunctionCall, Args[format_idx],
8331         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
8332         FExpr->getBeginLoc(),
8333         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
8334     return;
8335   }
8336 
8337   // CHECK: empty format string?
8338   if (StrLen == 0 && numDataArgs > 0) {
8339     CheckFormatHandler::EmitFormatDiagnostic(
8340         S, inFunctionCall, Args[format_idx],
8341         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
8342         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8343     return;
8344   }
8345 
8346   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
8347       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
8348       Type == Sema::FST_OSTrace) {
8349     CheckPrintfHandler H(
8350         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
8351         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
8352         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
8353         CheckedVarArgs, UncoveredArg);
8354 
8355     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
8356                                                   S.getLangOpts(),
8357                                                   S.Context.getTargetInfo(),
8358                                             Type == Sema::FST_FreeBSDKPrintf))
8359       H.DoneProcessing();
8360   } else if (Type == Sema::FST_Scanf) {
8361     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
8362                         numDataArgs, Str, HasVAListArg, Args, format_idx,
8363                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
8364 
8365     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
8366                                                  S.getLangOpts(),
8367                                                  S.Context.getTargetInfo()))
8368       H.DoneProcessing();
8369   } // TODO: handle other formats
8370 }
8371 
8372 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
8373   // Str - The format string.  NOTE: this is NOT null-terminated!
8374   StringRef StrRef = FExpr->getString();
8375   const char *Str = StrRef.data();
8376   // Account for cases where the string literal is truncated in a declaration.
8377   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
8378   assert(T && "String literal not of constant array type!");
8379   size_t TypeSize = T->getSize().getZExtValue();
8380   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8381   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
8382                                                          getLangOpts(),
8383                                                          Context.getTargetInfo());
8384 }
8385 
8386 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
8387 
8388 // Returns the related absolute value function that is larger, of 0 if one
8389 // does not exist.
8390 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
8391   switch (AbsFunction) {
8392   default:
8393     return 0;
8394 
8395   case Builtin::BI__builtin_abs:
8396     return Builtin::BI__builtin_labs;
8397   case Builtin::BI__builtin_labs:
8398     return Builtin::BI__builtin_llabs;
8399   case Builtin::BI__builtin_llabs:
8400     return 0;
8401 
8402   case Builtin::BI__builtin_fabsf:
8403     return Builtin::BI__builtin_fabs;
8404   case Builtin::BI__builtin_fabs:
8405     return Builtin::BI__builtin_fabsl;
8406   case Builtin::BI__builtin_fabsl:
8407     return 0;
8408 
8409   case Builtin::BI__builtin_cabsf:
8410     return Builtin::BI__builtin_cabs;
8411   case Builtin::BI__builtin_cabs:
8412     return Builtin::BI__builtin_cabsl;
8413   case Builtin::BI__builtin_cabsl:
8414     return 0;
8415 
8416   case Builtin::BIabs:
8417     return Builtin::BIlabs;
8418   case Builtin::BIlabs:
8419     return Builtin::BIllabs;
8420   case Builtin::BIllabs:
8421     return 0;
8422 
8423   case Builtin::BIfabsf:
8424     return Builtin::BIfabs;
8425   case Builtin::BIfabs:
8426     return Builtin::BIfabsl;
8427   case Builtin::BIfabsl:
8428     return 0;
8429 
8430   case Builtin::BIcabsf:
8431    return Builtin::BIcabs;
8432   case Builtin::BIcabs:
8433     return Builtin::BIcabsl;
8434   case Builtin::BIcabsl:
8435     return 0;
8436   }
8437 }
8438 
8439 // Returns the argument type of the absolute value function.
8440 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
8441                                              unsigned AbsType) {
8442   if (AbsType == 0)
8443     return QualType();
8444 
8445   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
8446   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
8447   if (Error != ASTContext::GE_None)
8448     return QualType();
8449 
8450   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
8451   if (!FT)
8452     return QualType();
8453 
8454   if (FT->getNumParams() != 1)
8455     return QualType();
8456 
8457   return FT->getParamType(0);
8458 }
8459 
8460 // Returns the best absolute value function, or zero, based on type and
8461 // current absolute value function.
8462 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
8463                                    unsigned AbsFunctionKind) {
8464   unsigned BestKind = 0;
8465   uint64_t ArgSize = Context.getTypeSize(ArgType);
8466   for (unsigned Kind = AbsFunctionKind; Kind != 0;
8467        Kind = getLargerAbsoluteValueFunction(Kind)) {
8468     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
8469     if (Context.getTypeSize(ParamType) >= ArgSize) {
8470       if (BestKind == 0)
8471         BestKind = Kind;
8472       else if (Context.hasSameType(ParamType, ArgType)) {
8473         BestKind = Kind;
8474         break;
8475       }
8476     }
8477   }
8478   return BestKind;
8479 }
8480 
8481 enum AbsoluteValueKind {
8482   AVK_Integer,
8483   AVK_Floating,
8484   AVK_Complex
8485 };
8486 
8487 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
8488   if (T->isIntegralOrEnumerationType())
8489     return AVK_Integer;
8490   if (T->isRealFloatingType())
8491     return AVK_Floating;
8492   if (T->isAnyComplexType())
8493     return AVK_Complex;
8494 
8495   llvm_unreachable("Type not integer, floating, or complex");
8496 }
8497 
8498 // Changes the absolute value function to a different type.  Preserves whether
8499 // the function is a builtin.
8500 static unsigned changeAbsFunction(unsigned AbsKind,
8501                                   AbsoluteValueKind ValueKind) {
8502   switch (ValueKind) {
8503   case AVK_Integer:
8504     switch (AbsKind) {
8505     default:
8506       return 0;
8507     case Builtin::BI__builtin_fabsf:
8508     case Builtin::BI__builtin_fabs:
8509     case Builtin::BI__builtin_fabsl:
8510     case Builtin::BI__builtin_cabsf:
8511     case Builtin::BI__builtin_cabs:
8512     case Builtin::BI__builtin_cabsl:
8513       return Builtin::BI__builtin_abs;
8514     case Builtin::BIfabsf:
8515     case Builtin::BIfabs:
8516     case Builtin::BIfabsl:
8517     case Builtin::BIcabsf:
8518     case Builtin::BIcabs:
8519     case Builtin::BIcabsl:
8520       return Builtin::BIabs;
8521     }
8522   case AVK_Floating:
8523     switch (AbsKind) {
8524     default:
8525       return 0;
8526     case Builtin::BI__builtin_abs:
8527     case Builtin::BI__builtin_labs:
8528     case Builtin::BI__builtin_llabs:
8529     case Builtin::BI__builtin_cabsf:
8530     case Builtin::BI__builtin_cabs:
8531     case Builtin::BI__builtin_cabsl:
8532       return Builtin::BI__builtin_fabsf;
8533     case Builtin::BIabs:
8534     case Builtin::BIlabs:
8535     case Builtin::BIllabs:
8536     case Builtin::BIcabsf:
8537     case Builtin::BIcabs:
8538     case Builtin::BIcabsl:
8539       return Builtin::BIfabsf;
8540     }
8541   case AVK_Complex:
8542     switch (AbsKind) {
8543     default:
8544       return 0;
8545     case Builtin::BI__builtin_abs:
8546     case Builtin::BI__builtin_labs:
8547     case Builtin::BI__builtin_llabs:
8548     case Builtin::BI__builtin_fabsf:
8549     case Builtin::BI__builtin_fabs:
8550     case Builtin::BI__builtin_fabsl:
8551       return Builtin::BI__builtin_cabsf;
8552     case Builtin::BIabs:
8553     case Builtin::BIlabs:
8554     case Builtin::BIllabs:
8555     case Builtin::BIfabsf:
8556     case Builtin::BIfabs:
8557     case Builtin::BIfabsl:
8558       return Builtin::BIcabsf;
8559     }
8560   }
8561   llvm_unreachable("Unable to convert function");
8562 }
8563 
8564 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
8565   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
8566   if (!FnInfo)
8567     return 0;
8568 
8569   switch (FDecl->getBuiltinID()) {
8570   default:
8571     return 0;
8572   case Builtin::BI__builtin_abs:
8573   case Builtin::BI__builtin_fabs:
8574   case Builtin::BI__builtin_fabsf:
8575   case Builtin::BI__builtin_fabsl:
8576   case Builtin::BI__builtin_labs:
8577   case Builtin::BI__builtin_llabs:
8578   case Builtin::BI__builtin_cabs:
8579   case Builtin::BI__builtin_cabsf:
8580   case Builtin::BI__builtin_cabsl:
8581   case Builtin::BIabs:
8582   case Builtin::BIlabs:
8583   case Builtin::BIllabs:
8584   case Builtin::BIfabs:
8585   case Builtin::BIfabsf:
8586   case Builtin::BIfabsl:
8587   case Builtin::BIcabs:
8588   case Builtin::BIcabsf:
8589   case Builtin::BIcabsl:
8590     return FDecl->getBuiltinID();
8591   }
8592   llvm_unreachable("Unknown Builtin type");
8593 }
8594 
8595 // If the replacement is valid, emit a note with replacement function.
8596 // Additionally, suggest including the proper header if not already included.
8597 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
8598                             unsigned AbsKind, QualType ArgType) {
8599   bool EmitHeaderHint = true;
8600   const char *HeaderName = nullptr;
8601   const char *FunctionName = nullptr;
8602   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
8603     FunctionName = "std::abs";
8604     if (ArgType->isIntegralOrEnumerationType()) {
8605       HeaderName = "cstdlib";
8606     } else if (ArgType->isRealFloatingType()) {
8607       HeaderName = "cmath";
8608     } else {
8609       llvm_unreachable("Invalid Type");
8610     }
8611 
8612     // Lookup all std::abs
8613     if (NamespaceDecl *Std = S.getStdNamespace()) {
8614       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
8615       R.suppressDiagnostics();
8616       S.LookupQualifiedName(R, Std);
8617 
8618       for (const auto *I : R) {
8619         const FunctionDecl *FDecl = nullptr;
8620         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
8621           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
8622         } else {
8623           FDecl = dyn_cast<FunctionDecl>(I);
8624         }
8625         if (!FDecl)
8626           continue;
8627 
8628         // Found std::abs(), check that they are the right ones.
8629         if (FDecl->getNumParams() != 1)
8630           continue;
8631 
8632         // Check that the parameter type can handle the argument.
8633         QualType ParamType = FDecl->getParamDecl(0)->getType();
8634         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
8635             S.Context.getTypeSize(ArgType) <=
8636                 S.Context.getTypeSize(ParamType)) {
8637           // Found a function, don't need the header hint.
8638           EmitHeaderHint = false;
8639           break;
8640         }
8641       }
8642     }
8643   } else {
8644     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
8645     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
8646 
8647     if (HeaderName) {
8648       DeclarationName DN(&S.Context.Idents.get(FunctionName));
8649       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
8650       R.suppressDiagnostics();
8651       S.LookupName(R, S.getCurScope());
8652 
8653       if (R.isSingleResult()) {
8654         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
8655         if (FD && FD->getBuiltinID() == AbsKind) {
8656           EmitHeaderHint = false;
8657         } else {
8658           return;
8659         }
8660       } else if (!R.empty()) {
8661         return;
8662       }
8663     }
8664   }
8665 
8666   S.Diag(Loc, diag::note_replace_abs_function)
8667       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
8668 
8669   if (!HeaderName)
8670     return;
8671 
8672   if (!EmitHeaderHint)
8673     return;
8674 
8675   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
8676                                                     << FunctionName;
8677 }
8678 
8679 template <std::size_t StrLen>
8680 static bool IsStdFunction(const FunctionDecl *FDecl,
8681                           const char (&Str)[StrLen]) {
8682   if (!FDecl)
8683     return false;
8684   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
8685     return false;
8686   if (!FDecl->isInStdNamespace())
8687     return false;
8688 
8689   return true;
8690 }
8691 
8692 // Warn when using the wrong abs() function.
8693 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
8694                                       const FunctionDecl *FDecl) {
8695   if (Call->getNumArgs() != 1)
8696     return;
8697 
8698   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
8699   bool IsStdAbs = IsStdFunction(FDecl, "abs");
8700   if (AbsKind == 0 && !IsStdAbs)
8701     return;
8702 
8703   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
8704   QualType ParamType = Call->getArg(0)->getType();
8705 
8706   // Unsigned types cannot be negative.  Suggest removing the absolute value
8707   // function call.
8708   if (ArgType->isUnsignedIntegerType()) {
8709     const char *FunctionName =
8710         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
8711     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
8712     Diag(Call->getExprLoc(), diag::note_remove_abs)
8713         << FunctionName
8714         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
8715     return;
8716   }
8717 
8718   // Taking the absolute value of a pointer is very suspicious, they probably
8719   // wanted to index into an array, dereference a pointer, call a function, etc.
8720   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
8721     unsigned DiagType = 0;
8722     if (ArgType->isFunctionType())
8723       DiagType = 1;
8724     else if (ArgType->isArrayType())
8725       DiagType = 2;
8726 
8727     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
8728     return;
8729   }
8730 
8731   // std::abs has overloads which prevent most of the absolute value problems
8732   // from occurring.
8733   if (IsStdAbs)
8734     return;
8735 
8736   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
8737   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
8738 
8739   // The argument and parameter are the same kind.  Check if they are the right
8740   // size.
8741   if (ArgValueKind == ParamValueKind) {
8742     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
8743       return;
8744 
8745     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
8746     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
8747         << FDecl << ArgType << ParamType;
8748 
8749     if (NewAbsKind == 0)
8750       return;
8751 
8752     emitReplacement(*this, Call->getExprLoc(),
8753                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
8754     return;
8755   }
8756 
8757   // ArgValueKind != ParamValueKind
8758   // The wrong type of absolute value function was used.  Attempt to find the
8759   // proper one.
8760   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
8761   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
8762   if (NewAbsKind == 0)
8763     return;
8764 
8765   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
8766       << FDecl << ParamValueKind << ArgValueKind;
8767 
8768   emitReplacement(*this, Call->getExprLoc(),
8769                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
8770 }
8771 
8772 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
8773 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
8774                                 const FunctionDecl *FDecl) {
8775   if (!Call || !FDecl) return;
8776 
8777   // Ignore template specializations and macros.
8778   if (inTemplateInstantiation()) return;
8779   if (Call->getExprLoc().isMacroID()) return;
8780 
8781   // Only care about the one template argument, two function parameter std::max
8782   if (Call->getNumArgs() != 2) return;
8783   if (!IsStdFunction(FDecl, "max")) return;
8784   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
8785   if (!ArgList) return;
8786   if (ArgList->size() != 1) return;
8787 
8788   // Check that template type argument is unsigned integer.
8789   const auto& TA = ArgList->get(0);
8790   if (TA.getKind() != TemplateArgument::Type) return;
8791   QualType ArgType = TA.getAsType();
8792   if (!ArgType->isUnsignedIntegerType()) return;
8793 
8794   // See if either argument is a literal zero.
8795   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
8796     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
8797     if (!MTE) return false;
8798     const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
8799     if (!Num) return false;
8800     if (Num->getValue() != 0) return false;
8801     return true;
8802   };
8803 
8804   const Expr *FirstArg = Call->getArg(0);
8805   const Expr *SecondArg = Call->getArg(1);
8806   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
8807   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
8808 
8809   // Only warn when exactly one argument is zero.
8810   if (IsFirstArgZero == IsSecondArgZero) return;
8811 
8812   SourceRange FirstRange = FirstArg->getSourceRange();
8813   SourceRange SecondRange = SecondArg->getSourceRange();
8814 
8815   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
8816 
8817   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
8818       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
8819 
8820   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
8821   SourceRange RemovalRange;
8822   if (IsFirstArgZero) {
8823     RemovalRange = SourceRange(FirstRange.getBegin(),
8824                                SecondRange.getBegin().getLocWithOffset(-1));
8825   } else {
8826     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
8827                                SecondRange.getEnd());
8828   }
8829 
8830   Diag(Call->getExprLoc(), diag::note_remove_max_call)
8831         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
8832         << FixItHint::CreateRemoval(RemovalRange);
8833 }
8834 
8835 //===--- CHECK: Standard memory functions ---------------------------------===//
8836 
8837 /// Takes the expression passed to the size_t parameter of functions
8838 /// such as memcmp, strncat, etc and warns if it's a comparison.
8839 ///
8840 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
8841 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
8842                                            IdentifierInfo *FnName,
8843                                            SourceLocation FnLoc,
8844                                            SourceLocation RParenLoc) {
8845   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
8846   if (!Size)
8847     return false;
8848 
8849   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
8850   if (!Size->isComparisonOp() && !Size->isLogicalOp())
8851     return false;
8852 
8853   SourceRange SizeRange = Size->getSourceRange();
8854   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
8855       << SizeRange << FnName;
8856   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
8857       << FnName
8858       << FixItHint::CreateInsertion(
8859              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
8860       << FixItHint::CreateRemoval(RParenLoc);
8861   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
8862       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
8863       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
8864                                     ")");
8865 
8866   return true;
8867 }
8868 
8869 /// Determine whether the given type is or contains a dynamic class type
8870 /// (e.g., whether it has a vtable).
8871 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
8872                                                      bool &IsContained) {
8873   // Look through array types while ignoring qualifiers.
8874   const Type *Ty = T->getBaseElementTypeUnsafe();
8875   IsContained = false;
8876 
8877   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
8878   RD = RD ? RD->getDefinition() : nullptr;
8879   if (!RD || RD->isInvalidDecl())
8880     return nullptr;
8881 
8882   if (RD->isDynamicClass())
8883     return RD;
8884 
8885   // Check all the fields.  If any bases were dynamic, the class is dynamic.
8886   // It's impossible for a class to transitively contain itself by value, so
8887   // infinite recursion is impossible.
8888   for (auto *FD : RD->fields()) {
8889     bool SubContained;
8890     if (const CXXRecordDecl *ContainedRD =
8891             getContainedDynamicClass(FD->getType(), SubContained)) {
8892       IsContained = true;
8893       return ContainedRD;
8894     }
8895   }
8896 
8897   return nullptr;
8898 }
8899 
8900 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
8901   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
8902     if (Unary->getKind() == UETT_SizeOf)
8903       return Unary;
8904   return nullptr;
8905 }
8906 
8907 /// If E is a sizeof expression, returns its argument expression,
8908 /// otherwise returns NULL.
8909 static const Expr *getSizeOfExprArg(const Expr *E) {
8910   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
8911     if (!SizeOf->isArgumentType())
8912       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
8913   return nullptr;
8914 }
8915 
8916 /// If E is a sizeof expression, returns its argument type.
8917 static QualType getSizeOfArgType(const Expr *E) {
8918   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
8919     return SizeOf->getTypeOfArgument();
8920   return QualType();
8921 }
8922 
8923 namespace {
8924 
8925 struct SearchNonTrivialToInitializeField
8926     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
8927   using Super =
8928       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
8929 
8930   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
8931 
8932   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
8933                      SourceLocation SL) {
8934     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
8935       asDerived().visitArray(PDIK, AT, SL);
8936       return;
8937     }
8938 
8939     Super::visitWithKind(PDIK, FT, SL);
8940   }
8941 
8942   void visitARCStrong(QualType FT, SourceLocation SL) {
8943     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
8944   }
8945   void visitARCWeak(QualType FT, SourceLocation SL) {
8946     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
8947   }
8948   void visitStruct(QualType FT, SourceLocation SL) {
8949     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
8950       visit(FD->getType(), FD->getLocation());
8951   }
8952   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
8953                   const ArrayType *AT, SourceLocation SL) {
8954     visit(getContext().getBaseElementType(AT), SL);
8955   }
8956   void visitTrivial(QualType FT, SourceLocation SL) {}
8957 
8958   static void diag(QualType RT, const Expr *E, Sema &S) {
8959     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
8960   }
8961 
8962   ASTContext &getContext() { return S.getASTContext(); }
8963 
8964   const Expr *E;
8965   Sema &S;
8966 };
8967 
8968 struct SearchNonTrivialToCopyField
8969     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
8970   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
8971 
8972   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
8973 
8974   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
8975                      SourceLocation SL) {
8976     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
8977       asDerived().visitArray(PCK, AT, SL);
8978       return;
8979     }
8980 
8981     Super::visitWithKind(PCK, FT, SL);
8982   }
8983 
8984   void visitARCStrong(QualType FT, SourceLocation SL) {
8985     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
8986   }
8987   void visitARCWeak(QualType FT, SourceLocation SL) {
8988     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
8989   }
8990   void visitStruct(QualType FT, SourceLocation SL) {
8991     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
8992       visit(FD->getType(), FD->getLocation());
8993   }
8994   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
8995                   SourceLocation SL) {
8996     visit(getContext().getBaseElementType(AT), SL);
8997   }
8998   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
8999                 SourceLocation SL) {}
9000   void visitTrivial(QualType FT, SourceLocation SL) {}
9001   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
9002 
9003   static void diag(QualType RT, const Expr *E, Sema &S) {
9004     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
9005   }
9006 
9007   ASTContext &getContext() { return S.getASTContext(); }
9008 
9009   const Expr *E;
9010   Sema &S;
9011 };
9012 
9013 }
9014 
9015 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
9016 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
9017   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
9018 
9019   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
9020     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
9021       return false;
9022 
9023     return doesExprLikelyComputeSize(BO->getLHS()) ||
9024            doesExprLikelyComputeSize(BO->getRHS());
9025   }
9026 
9027   return getAsSizeOfExpr(SizeofExpr) != nullptr;
9028 }
9029 
9030 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
9031 ///
9032 /// \code
9033 ///   #define MACRO 0
9034 ///   foo(MACRO);
9035 ///   foo(0);
9036 /// \endcode
9037 ///
9038 /// This should return true for the first call to foo, but not for the second
9039 /// (regardless of whether foo is a macro or function).
9040 static bool isArgumentExpandedFromMacro(SourceManager &SM,
9041                                         SourceLocation CallLoc,
9042                                         SourceLocation ArgLoc) {
9043   if (!CallLoc.isMacroID())
9044     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
9045 
9046   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
9047          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
9048 }
9049 
9050 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
9051 /// last two arguments transposed.
9052 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
9053   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
9054     return;
9055 
9056   const Expr *SizeArg =
9057     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
9058 
9059   auto isLiteralZero = [](const Expr *E) {
9060     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
9061   };
9062 
9063   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
9064   SourceLocation CallLoc = Call->getRParenLoc();
9065   SourceManager &SM = S.getSourceManager();
9066   if (isLiteralZero(SizeArg) &&
9067       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
9068 
9069     SourceLocation DiagLoc = SizeArg->getExprLoc();
9070 
9071     // Some platforms #define bzero to __builtin_memset. See if this is the
9072     // case, and if so, emit a better diagnostic.
9073     if (BId == Builtin::BIbzero ||
9074         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
9075                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
9076       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
9077       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
9078     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
9079       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
9080       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
9081     }
9082     return;
9083   }
9084 
9085   // If the second argument to a memset is a sizeof expression and the third
9086   // isn't, this is also likely an error. This should catch
9087   // 'memset(buf, sizeof(buf), 0xff)'.
9088   if (BId == Builtin::BImemset &&
9089       doesExprLikelyComputeSize(Call->getArg(1)) &&
9090       !doesExprLikelyComputeSize(Call->getArg(2))) {
9091     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
9092     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
9093     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
9094     return;
9095   }
9096 }
9097 
9098 /// Check for dangerous or invalid arguments to memset().
9099 ///
9100 /// This issues warnings on known problematic, dangerous or unspecified
9101 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
9102 /// function calls.
9103 ///
9104 /// \param Call The call expression to diagnose.
9105 void Sema::CheckMemaccessArguments(const CallExpr *Call,
9106                                    unsigned BId,
9107                                    IdentifierInfo *FnName) {
9108   assert(BId != 0);
9109 
9110   // It is possible to have a non-standard definition of memset.  Validate
9111   // we have enough arguments, and if not, abort further checking.
9112   unsigned ExpectedNumArgs =
9113       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
9114   if (Call->getNumArgs() < ExpectedNumArgs)
9115     return;
9116 
9117   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
9118                       BId == Builtin::BIstrndup ? 1 : 2);
9119   unsigned LenArg =
9120       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
9121   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
9122 
9123   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
9124                                      Call->getBeginLoc(), Call->getRParenLoc()))
9125     return;
9126 
9127   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
9128   CheckMemaccessSize(*this, BId, Call);
9129 
9130   // We have special checking when the length is a sizeof expression.
9131   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
9132   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
9133   llvm::FoldingSetNodeID SizeOfArgID;
9134 
9135   // Although widely used, 'bzero' is not a standard function. Be more strict
9136   // with the argument types before allowing diagnostics and only allow the
9137   // form bzero(ptr, sizeof(...)).
9138   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9139   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
9140     return;
9141 
9142   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
9143     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
9144     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
9145 
9146     QualType DestTy = Dest->getType();
9147     QualType PointeeTy;
9148     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
9149       PointeeTy = DestPtrTy->getPointeeType();
9150 
9151       // Never warn about void type pointers. This can be used to suppress
9152       // false positives.
9153       if (PointeeTy->isVoidType())
9154         continue;
9155 
9156       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
9157       // actually comparing the expressions for equality. Because computing the
9158       // expression IDs can be expensive, we only do this if the diagnostic is
9159       // enabled.
9160       if (SizeOfArg &&
9161           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
9162                            SizeOfArg->getExprLoc())) {
9163         // We only compute IDs for expressions if the warning is enabled, and
9164         // cache the sizeof arg's ID.
9165         if (SizeOfArgID == llvm::FoldingSetNodeID())
9166           SizeOfArg->Profile(SizeOfArgID, Context, true);
9167         llvm::FoldingSetNodeID DestID;
9168         Dest->Profile(DestID, Context, true);
9169         if (DestID == SizeOfArgID) {
9170           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
9171           //       over sizeof(src) as well.
9172           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
9173           StringRef ReadableName = FnName->getName();
9174 
9175           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
9176             if (UnaryOp->getOpcode() == UO_AddrOf)
9177               ActionIdx = 1; // If its an address-of operator, just remove it.
9178           if (!PointeeTy->isIncompleteType() &&
9179               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
9180             ActionIdx = 2; // If the pointee's size is sizeof(char),
9181                            // suggest an explicit length.
9182 
9183           // If the function is defined as a builtin macro, do not show macro
9184           // expansion.
9185           SourceLocation SL = SizeOfArg->getExprLoc();
9186           SourceRange DSR = Dest->getSourceRange();
9187           SourceRange SSR = SizeOfArg->getSourceRange();
9188           SourceManager &SM = getSourceManager();
9189 
9190           if (SM.isMacroArgExpansion(SL)) {
9191             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
9192             SL = SM.getSpellingLoc(SL);
9193             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
9194                              SM.getSpellingLoc(DSR.getEnd()));
9195             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
9196                              SM.getSpellingLoc(SSR.getEnd()));
9197           }
9198 
9199           DiagRuntimeBehavior(SL, SizeOfArg,
9200                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
9201                                 << ReadableName
9202                                 << PointeeTy
9203                                 << DestTy
9204                                 << DSR
9205                                 << SSR);
9206           DiagRuntimeBehavior(SL, SizeOfArg,
9207                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
9208                                 << ActionIdx
9209                                 << SSR);
9210 
9211           break;
9212         }
9213       }
9214 
9215       // Also check for cases where the sizeof argument is the exact same
9216       // type as the memory argument, and where it points to a user-defined
9217       // record type.
9218       if (SizeOfArgTy != QualType()) {
9219         if (PointeeTy->isRecordType() &&
9220             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
9221           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
9222                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
9223                                 << FnName << SizeOfArgTy << ArgIdx
9224                                 << PointeeTy << Dest->getSourceRange()
9225                                 << LenExpr->getSourceRange());
9226           break;
9227         }
9228       }
9229     } else if (DestTy->isArrayType()) {
9230       PointeeTy = DestTy;
9231     }
9232 
9233     if (PointeeTy == QualType())
9234       continue;
9235 
9236     // Always complain about dynamic classes.
9237     bool IsContained;
9238     if (const CXXRecordDecl *ContainedRD =
9239             getContainedDynamicClass(PointeeTy, IsContained)) {
9240 
9241       unsigned OperationType = 0;
9242       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
9243       // "overwritten" if we're warning about the destination for any call
9244       // but memcmp; otherwise a verb appropriate to the call.
9245       if (ArgIdx != 0 || IsCmp) {
9246         if (BId == Builtin::BImemcpy)
9247           OperationType = 1;
9248         else if(BId == Builtin::BImemmove)
9249           OperationType = 2;
9250         else if (IsCmp)
9251           OperationType = 3;
9252       }
9253 
9254       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9255                           PDiag(diag::warn_dyn_class_memaccess)
9256                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
9257                               << IsContained << ContainedRD << OperationType
9258                               << Call->getCallee()->getSourceRange());
9259     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
9260              BId != Builtin::BImemset)
9261       DiagRuntimeBehavior(
9262         Dest->getExprLoc(), Dest,
9263         PDiag(diag::warn_arc_object_memaccess)
9264           << ArgIdx << FnName << PointeeTy
9265           << Call->getCallee()->getSourceRange());
9266     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
9267       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
9268           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
9269         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9270                             PDiag(diag::warn_cstruct_memaccess)
9271                                 << ArgIdx << FnName << PointeeTy << 0);
9272         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
9273       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
9274                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
9275         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9276                             PDiag(diag::warn_cstruct_memaccess)
9277                                 << ArgIdx << FnName << PointeeTy << 1);
9278         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
9279       } else {
9280         continue;
9281       }
9282     } else
9283       continue;
9284 
9285     DiagRuntimeBehavior(
9286       Dest->getExprLoc(), Dest,
9287       PDiag(diag::note_bad_memaccess_silence)
9288         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
9289     break;
9290   }
9291 }
9292 
9293 // A little helper routine: ignore addition and subtraction of integer literals.
9294 // This intentionally does not ignore all integer constant expressions because
9295 // we don't want to remove sizeof().
9296 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
9297   Ex = Ex->IgnoreParenCasts();
9298 
9299   while (true) {
9300     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
9301     if (!BO || !BO->isAdditiveOp())
9302       break;
9303 
9304     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
9305     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
9306 
9307     if (isa<IntegerLiteral>(RHS))
9308       Ex = LHS;
9309     else if (isa<IntegerLiteral>(LHS))
9310       Ex = RHS;
9311     else
9312       break;
9313   }
9314 
9315   return Ex;
9316 }
9317 
9318 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
9319                                                       ASTContext &Context) {
9320   // Only handle constant-sized or VLAs, but not flexible members.
9321   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
9322     // Only issue the FIXIT for arrays of size > 1.
9323     if (CAT->getSize().getSExtValue() <= 1)
9324       return false;
9325   } else if (!Ty->isVariableArrayType()) {
9326     return false;
9327   }
9328   return true;
9329 }
9330 
9331 // Warn if the user has made the 'size' argument to strlcpy or strlcat
9332 // be the size of the source, instead of the destination.
9333 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
9334                                     IdentifierInfo *FnName) {
9335 
9336   // Don't crash if the user has the wrong number of arguments
9337   unsigned NumArgs = Call->getNumArgs();
9338   if ((NumArgs != 3) && (NumArgs != 4))
9339     return;
9340 
9341   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
9342   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
9343   const Expr *CompareWithSrc = nullptr;
9344 
9345   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
9346                                      Call->getBeginLoc(), Call->getRParenLoc()))
9347     return;
9348 
9349   // Look for 'strlcpy(dst, x, sizeof(x))'
9350   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
9351     CompareWithSrc = Ex;
9352   else {
9353     // Look for 'strlcpy(dst, x, strlen(x))'
9354     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
9355       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
9356           SizeCall->getNumArgs() == 1)
9357         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
9358     }
9359   }
9360 
9361   if (!CompareWithSrc)
9362     return;
9363 
9364   // Determine if the argument to sizeof/strlen is equal to the source
9365   // argument.  In principle there's all kinds of things you could do
9366   // here, for instance creating an == expression and evaluating it with
9367   // EvaluateAsBooleanCondition, but this uses a more direct technique:
9368   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
9369   if (!SrcArgDRE)
9370     return;
9371 
9372   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
9373   if (!CompareWithSrcDRE ||
9374       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
9375     return;
9376 
9377   const Expr *OriginalSizeArg = Call->getArg(2);
9378   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
9379       << OriginalSizeArg->getSourceRange() << FnName;
9380 
9381   // Output a FIXIT hint if the destination is an array (rather than a
9382   // pointer to an array).  This could be enhanced to handle some
9383   // pointers if we know the actual size, like if DstArg is 'array+2'
9384   // we could say 'sizeof(array)-2'.
9385   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
9386   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
9387     return;
9388 
9389   SmallString<128> sizeString;
9390   llvm::raw_svector_ostream OS(sizeString);
9391   OS << "sizeof(";
9392   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9393   OS << ")";
9394 
9395   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
9396       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
9397                                       OS.str());
9398 }
9399 
9400 /// Check if two expressions refer to the same declaration.
9401 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
9402   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
9403     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
9404       return D1->getDecl() == D2->getDecl();
9405   return false;
9406 }
9407 
9408 static const Expr *getStrlenExprArg(const Expr *E) {
9409   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9410     const FunctionDecl *FD = CE->getDirectCallee();
9411     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
9412       return nullptr;
9413     return CE->getArg(0)->IgnoreParenCasts();
9414   }
9415   return nullptr;
9416 }
9417 
9418 // Warn on anti-patterns as the 'size' argument to strncat.
9419 // The correct size argument should look like following:
9420 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
9421 void Sema::CheckStrncatArguments(const CallExpr *CE,
9422                                  IdentifierInfo *FnName) {
9423   // Don't crash if the user has the wrong number of arguments.
9424   if (CE->getNumArgs() < 3)
9425     return;
9426   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
9427   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
9428   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
9429 
9430   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
9431                                      CE->getRParenLoc()))
9432     return;
9433 
9434   // Identify common expressions, which are wrongly used as the size argument
9435   // to strncat and may lead to buffer overflows.
9436   unsigned PatternType = 0;
9437   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
9438     // - sizeof(dst)
9439     if (referToTheSameDecl(SizeOfArg, DstArg))
9440       PatternType = 1;
9441     // - sizeof(src)
9442     else if (referToTheSameDecl(SizeOfArg, SrcArg))
9443       PatternType = 2;
9444   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
9445     if (BE->getOpcode() == BO_Sub) {
9446       const Expr *L = BE->getLHS()->IgnoreParenCasts();
9447       const Expr *R = BE->getRHS()->IgnoreParenCasts();
9448       // - sizeof(dst) - strlen(dst)
9449       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
9450           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
9451         PatternType = 1;
9452       // - sizeof(src) - (anything)
9453       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
9454         PatternType = 2;
9455     }
9456   }
9457 
9458   if (PatternType == 0)
9459     return;
9460 
9461   // Generate the diagnostic.
9462   SourceLocation SL = LenArg->getBeginLoc();
9463   SourceRange SR = LenArg->getSourceRange();
9464   SourceManager &SM = getSourceManager();
9465 
9466   // If the function is defined as a builtin macro, do not show macro expansion.
9467   if (SM.isMacroArgExpansion(SL)) {
9468     SL = SM.getSpellingLoc(SL);
9469     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
9470                      SM.getSpellingLoc(SR.getEnd()));
9471   }
9472 
9473   // Check if the destination is an array (rather than a pointer to an array).
9474   QualType DstTy = DstArg->getType();
9475   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
9476                                                                     Context);
9477   if (!isKnownSizeArray) {
9478     if (PatternType == 1)
9479       Diag(SL, diag::warn_strncat_wrong_size) << SR;
9480     else
9481       Diag(SL, diag::warn_strncat_src_size) << SR;
9482     return;
9483   }
9484 
9485   if (PatternType == 1)
9486     Diag(SL, diag::warn_strncat_large_size) << SR;
9487   else
9488     Diag(SL, diag::warn_strncat_src_size) << SR;
9489 
9490   SmallString<128> sizeString;
9491   llvm::raw_svector_ostream OS(sizeString);
9492   OS << "sizeof(";
9493   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9494   OS << ") - ";
9495   OS << "strlen(";
9496   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9497   OS << ") - 1";
9498 
9499   Diag(SL, diag::note_strncat_wrong_size)
9500     << FixItHint::CreateReplacement(SR, OS.str());
9501 }
9502 
9503 void
9504 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
9505                          SourceLocation ReturnLoc,
9506                          bool isObjCMethod,
9507                          const AttrVec *Attrs,
9508                          const FunctionDecl *FD) {
9509   // Check if the return value is null but should not be.
9510   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
9511        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
9512       CheckNonNullExpr(*this, RetValExp))
9513     Diag(ReturnLoc, diag::warn_null_ret)
9514       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
9515 
9516   // C++11 [basic.stc.dynamic.allocation]p4:
9517   //   If an allocation function declared with a non-throwing
9518   //   exception-specification fails to allocate storage, it shall return
9519   //   a null pointer. Any other allocation function that fails to allocate
9520   //   storage shall indicate failure only by throwing an exception [...]
9521   if (FD) {
9522     OverloadedOperatorKind Op = FD->getOverloadedOperator();
9523     if (Op == OO_New || Op == OO_Array_New) {
9524       const FunctionProtoType *Proto
9525         = FD->getType()->castAs<FunctionProtoType>();
9526       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
9527           CheckNonNullExpr(*this, RetValExp))
9528         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
9529           << FD << getLangOpts().CPlusPlus11;
9530     }
9531   }
9532 }
9533 
9534 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
9535 
9536 /// Check for comparisons of floating point operands using != and ==.
9537 /// Issue a warning if these are no self-comparisons, as they are not likely
9538 /// to do what the programmer intended.
9539 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
9540   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
9541   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
9542 
9543   // Special case: check for x == x (which is OK).
9544   // Do not emit warnings for such cases.
9545   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
9546     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
9547       if (DRL->getDecl() == DRR->getDecl())
9548         return;
9549 
9550   // Special case: check for comparisons against literals that can be exactly
9551   //  represented by APFloat.  In such cases, do not emit a warning.  This
9552   //  is a heuristic: often comparison against such literals are used to
9553   //  detect if a value in a variable has not changed.  This clearly can
9554   //  lead to false negatives.
9555   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
9556     if (FLL->isExact())
9557       return;
9558   } else
9559     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
9560       if (FLR->isExact())
9561         return;
9562 
9563   // Check for comparisons with builtin types.
9564   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
9565     if (CL->getBuiltinCallee())
9566       return;
9567 
9568   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
9569     if (CR->getBuiltinCallee())
9570       return;
9571 
9572   // Emit the diagnostic.
9573   Diag(Loc, diag::warn_floatingpoint_eq)
9574     << LHS->getSourceRange() << RHS->getSourceRange();
9575 }
9576 
9577 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
9578 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
9579 
9580 namespace {
9581 
9582 /// Structure recording the 'active' range of an integer-valued
9583 /// expression.
9584 struct IntRange {
9585   /// The number of bits active in the int.
9586   unsigned Width;
9587 
9588   /// True if the int is known not to have negative values.
9589   bool NonNegative;
9590 
9591   IntRange(unsigned Width, bool NonNegative)
9592       : Width(Width), NonNegative(NonNegative) {}
9593 
9594   /// Returns the range of the bool type.
9595   static IntRange forBoolType() {
9596     return IntRange(1, true);
9597   }
9598 
9599   /// Returns the range of an opaque value of the given integral type.
9600   static IntRange forValueOfType(ASTContext &C, QualType T) {
9601     return forValueOfCanonicalType(C,
9602                           T->getCanonicalTypeInternal().getTypePtr());
9603   }
9604 
9605   /// Returns the range of an opaque value of a canonical integral type.
9606   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
9607     assert(T->isCanonicalUnqualified());
9608 
9609     if (const VectorType *VT = dyn_cast<VectorType>(T))
9610       T = VT->getElementType().getTypePtr();
9611     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9612       T = CT->getElementType().getTypePtr();
9613     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9614       T = AT->getValueType().getTypePtr();
9615 
9616     if (!C.getLangOpts().CPlusPlus) {
9617       // For enum types in C code, use the underlying datatype.
9618       if (const EnumType *ET = dyn_cast<EnumType>(T))
9619         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
9620     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
9621       // For enum types in C++, use the known bit width of the enumerators.
9622       EnumDecl *Enum = ET->getDecl();
9623       // In C++11, enums can have a fixed underlying type. Use this type to
9624       // compute the range.
9625       if (Enum->isFixed()) {
9626         return IntRange(C.getIntWidth(QualType(T, 0)),
9627                         !ET->isSignedIntegerOrEnumerationType());
9628       }
9629 
9630       unsigned NumPositive = Enum->getNumPositiveBits();
9631       unsigned NumNegative = Enum->getNumNegativeBits();
9632 
9633       if (NumNegative == 0)
9634         return IntRange(NumPositive, true/*NonNegative*/);
9635       else
9636         return IntRange(std::max(NumPositive + 1, NumNegative),
9637                         false/*NonNegative*/);
9638     }
9639 
9640     const BuiltinType *BT = cast<BuiltinType>(T);
9641     assert(BT->isInteger());
9642 
9643     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9644   }
9645 
9646   /// Returns the "target" range of a canonical integral type, i.e.
9647   /// the range of values expressible in the type.
9648   ///
9649   /// This matches forValueOfCanonicalType except that enums have the
9650   /// full range of their type, not the range of their enumerators.
9651   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
9652     assert(T->isCanonicalUnqualified());
9653 
9654     if (const VectorType *VT = dyn_cast<VectorType>(T))
9655       T = VT->getElementType().getTypePtr();
9656     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9657       T = CT->getElementType().getTypePtr();
9658     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9659       T = AT->getValueType().getTypePtr();
9660     if (const EnumType *ET = dyn_cast<EnumType>(T))
9661       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
9662 
9663     const BuiltinType *BT = cast<BuiltinType>(T);
9664     assert(BT->isInteger());
9665 
9666     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9667   }
9668 
9669   /// Returns the supremum of two ranges: i.e. their conservative merge.
9670   static IntRange join(IntRange L, IntRange R) {
9671     return IntRange(std::max(L.Width, R.Width),
9672                     L.NonNegative && R.NonNegative);
9673   }
9674 
9675   /// Returns the infinum of two ranges: i.e. their aggressive merge.
9676   static IntRange meet(IntRange L, IntRange R) {
9677     return IntRange(std::min(L.Width, R.Width),
9678                     L.NonNegative || R.NonNegative);
9679   }
9680 };
9681 
9682 } // namespace
9683 
9684 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
9685                               unsigned MaxWidth) {
9686   if (value.isSigned() && value.isNegative())
9687     return IntRange(value.getMinSignedBits(), false);
9688 
9689   if (value.getBitWidth() > MaxWidth)
9690     value = value.trunc(MaxWidth);
9691 
9692   // isNonNegative() just checks the sign bit without considering
9693   // signedness.
9694   return IntRange(value.getActiveBits(), true);
9695 }
9696 
9697 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
9698                               unsigned MaxWidth) {
9699   if (result.isInt())
9700     return GetValueRange(C, result.getInt(), MaxWidth);
9701 
9702   if (result.isVector()) {
9703     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
9704     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
9705       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
9706       R = IntRange::join(R, El);
9707     }
9708     return R;
9709   }
9710 
9711   if (result.isComplexInt()) {
9712     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
9713     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
9714     return IntRange::join(R, I);
9715   }
9716 
9717   // This can happen with lossless casts to intptr_t of "based" lvalues.
9718   // Assume it might use arbitrary bits.
9719   // FIXME: The only reason we need to pass the type in here is to get
9720   // the sign right on this one case.  It would be nice if APValue
9721   // preserved this.
9722   assert(result.isLValue() || result.isAddrLabelDiff());
9723   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
9724 }
9725 
9726 static QualType GetExprType(const Expr *E) {
9727   QualType Ty = E->getType();
9728   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
9729     Ty = AtomicRHS->getValueType();
9730   return Ty;
9731 }
9732 
9733 /// Pseudo-evaluate the given integer expression, estimating the
9734 /// range of values it might take.
9735 ///
9736 /// \param MaxWidth - the width to which the value will be truncated
9737 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
9738   E = E->IgnoreParens();
9739 
9740   // Try a full evaluation first.
9741   Expr::EvalResult result;
9742   if (E->EvaluateAsRValue(result, C))
9743     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
9744 
9745   // I think we only want to look through implicit casts here; if the
9746   // user has an explicit widening cast, we should treat the value as
9747   // being of the new, wider type.
9748   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
9749     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
9750       return GetExprRange(C, CE->getSubExpr(), MaxWidth);
9751 
9752     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
9753 
9754     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
9755                          CE->getCastKind() == CK_BooleanToSignedIntegral;
9756 
9757     // Assume that non-integer casts can span the full range of the type.
9758     if (!isIntegerCast)
9759       return OutputTypeRange;
9760 
9761     IntRange SubRange
9762       = GetExprRange(C, CE->getSubExpr(),
9763                      std::min(MaxWidth, OutputTypeRange.Width));
9764 
9765     // Bail out if the subexpr's range is as wide as the cast type.
9766     if (SubRange.Width >= OutputTypeRange.Width)
9767       return OutputTypeRange;
9768 
9769     // Otherwise, we take the smaller width, and we're non-negative if
9770     // either the output type or the subexpr is.
9771     return IntRange(SubRange.Width,
9772                     SubRange.NonNegative || OutputTypeRange.NonNegative);
9773   }
9774 
9775   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
9776     // If we can fold the condition, just take that operand.
9777     bool CondResult;
9778     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
9779       return GetExprRange(C, CondResult ? CO->getTrueExpr()
9780                                         : CO->getFalseExpr(),
9781                           MaxWidth);
9782 
9783     // Otherwise, conservatively merge.
9784     IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
9785     IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
9786     return IntRange::join(L, R);
9787   }
9788 
9789   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
9790     switch (BO->getOpcode()) {
9791     case BO_Cmp:
9792       llvm_unreachable("builtin <=> should have class type");
9793 
9794     // Boolean-valued operations are single-bit and positive.
9795     case BO_LAnd:
9796     case BO_LOr:
9797     case BO_LT:
9798     case BO_GT:
9799     case BO_LE:
9800     case BO_GE:
9801     case BO_EQ:
9802     case BO_NE:
9803       return IntRange::forBoolType();
9804 
9805     // The type of the assignments is the type of the LHS, so the RHS
9806     // is not necessarily the same type.
9807     case BO_MulAssign:
9808     case BO_DivAssign:
9809     case BO_RemAssign:
9810     case BO_AddAssign:
9811     case BO_SubAssign:
9812     case BO_XorAssign:
9813     case BO_OrAssign:
9814       // TODO: bitfields?
9815       return IntRange::forValueOfType(C, GetExprType(E));
9816 
9817     // Simple assignments just pass through the RHS, which will have
9818     // been coerced to the LHS type.
9819     case BO_Assign:
9820       // TODO: bitfields?
9821       return GetExprRange(C, BO->getRHS(), MaxWidth);
9822 
9823     // Operations with opaque sources are black-listed.
9824     case BO_PtrMemD:
9825     case BO_PtrMemI:
9826       return IntRange::forValueOfType(C, GetExprType(E));
9827 
9828     // Bitwise-and uses the *infinum* of the two source ranges.
9829     case BO_And:
9830     case BO_AndAssign:
9831       return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
9832                             GetExprRange(C, BO->getRHS(), MaxWidth));
9833 
9834     // Left shift gets black-listed based on a judgement call.
9835     case BO_Shl:
9836       // ...except that we want to treat '1 << (blah)' as logically
9837       // positive.  It's an important idiom.
9838       if (IntegerLiteral *I
9839             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
9840         if (I->getValue() == 1) {
9841           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
9842           return IntRange(R.Width, /*NonNegative*/ true);
9843         }
9844       }
9845       LLVM_FALLTHROUGH;
9846 
9847     case BO_ShlAssign:
9848       return IntRange::forValueOfType(C, GetExprType(E));
9849 
9850     // Right shift by a constant can narrow its left argument.
9851     case BO_Shr:
9852     case BO_ShrAssign: {
9853       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
9854 
9855       // If the shift amount is a positive constant, drop the width by
9856       // that much.
9857       llvm::APSInt shift;
9858       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
9859           shift.isNonNegative()) {
9860         unsigned zext = shift.getZExtValue();
9861         if (zext >= L.Width)
9862           L.Width = (L.NonNegative ? 0 : 1);
9863         else
9864           L.Width -= zext;
9865       }
9866 
9867       return L;
9868     }
9869 
9870     // Comma acts as its right operand.
9871     case BO_Comma:
9872       return GetExprRange(C, BO->getRHS(), MaxWidth);
9873 
9874     // Black-list pointer subtractions.
9875     case BO_Sub:
9876       if (BO->getLHS()->getType()->isPointerType())
9877         return IntRange::forValueOfType(C, GetExprType(E));
9878       break;
9879 
9880     // The width of a division result is mostly determined by the size
9881     // of the LHS.
9882     case BO_Div: {
9883       // Don't 'pre-truncate' the operands.
9884       unsigned opWidth = C.getIntWidth(GetExprType(E));
9885       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
9886 
9887       // If the divisor is constant, use that.
9888       llvm::APSInt divisor;
9889       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
9890         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
9891         if (log2 >= L.Width)
9892           L.Width = (L.NonNegative ? 0 : 1);
9893         else
9894           L.Width = std::min(L.Width - log2, MaxWidth);
9895         return L;
9896       }
9897 
9898       // Otherwise, just use the LHS's width.
9899       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
9900       return IntRange(L.Width, L.NonNegative && R.NonNegative);
9901     }
9902 
9903     // The result of a remainder can't be larger than the result of
9904     // either side.
9905     case BO_Rem: {
9906       // Don't 'pre-truncate' the operands.
9907       unsigned opWidth = C.getIntWidth(GetExprType(E));
9908       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
9909       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
9910 
9911       IntRange meet = IntRange::meet(L, R);
9912       meet.Width = std::min(meet.Width, MaxWidth);
9913       return meet;
9914     }
9915 
9916     // The default behavior is okay for these.
9917     case BO_Mul:
9918     case BO_Add:
9919     case BO_Xor:
9920     case BO_Or:
9921       break;
9922     }
9923 
9924     // The default case is to treat the operation as if it were closed
9925     // on the narrowest type that encompasses both operands.
9926     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
9927     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
9928     return IntRange::join(L, R);
9929   }
9930 
9931   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
9932     switch (UO->getOpcode()) {
9933     // Boolean-valued operations are white-listed.
9934     case UO_LNot:
9935       return IntRange::forBoolType();
9936 
9937     // Operations with opaque sources are black-listed.
9938     case UO_Deref:
9939     case UO_AddrOf: // should be impossible
9940       return IntRange::forValueOfType(C, GetExprType(E));
9941 
9942     default:
9943       return GetExprRange(C, UO->getSubExpr(), MaxWidth);
9944     }
9945   }
9946 
9947   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
9948     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
9949 
9950   if (const auto *BitField = E->getSourceBitField())
9951     return IntRange(BitField->getBitWidthValue(C),
9952                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
9953 
9954   return IntRange::forValueOfType(C, GetExprType(E));
9955 }
9956 
9957 static IntRange GetExprRange(ASTContext &C, const Expr *E) {
9958   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
9959 }
9960 
9961 /// Checks whether the given value, which currently has the given
9962 /// source semantics, has the same value when coerced through the
9963 /// target semantics.
9964 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
9965                                  const llvm::fltSemantics &Src,
9966                                  const llvm::fltSemantics &Tgt) {
9967   llvm::APFloat truncated = value;
9968 
9969   bool ignored;
9970   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
9971   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
9972 
9973   return truncated.bitwiseIsEqual(value);
9974 }
9975 
9976 /// Checks whether the given value, which currently has the given
9977 /// source semantics, has the same value when coerced through the
9978 /// target semantics.
9979 ///
9980 /// The value might be a vector of floats (or a complex number).
9981 static bool IsSameFloatAfterCast(const APValue &value,
9982                                  const llvm::fltSemantics &Src,
9983                                  const llvm::fltSemantics &Tgt) {
9984   if (value.isFloat())
9985     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
9986 
9987   if (value.isVector()) {
9988     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
9989       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
9990         return false;
9991     return true;
9992   }
9993 
9994   assert(value.isComplexFloat());
9995   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
9996           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
9997 }
9998 
9999 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
10000 
10001 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
10002   // Suppress cases where we are comparing against an enum constant.
10003   if (const DeclRefExpr *DR =
10004       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
10005     if (isa<EnumConstantDecl>(DR->getDecl()))
10006       return true;
10007 
10008   // Suppress cases where the '0' value is expanded from a macro.
10009   if (E->getBeginLoc().isMacroID())
10010     return true;
10011 
10012   return false;
10013 }
10014 
10015 static bool isKnownToHaveUnsignedValue(Expr *E) {
10016   return E->getType()->isIntegerType() &&
10017          (!E->getType()->isSignedIntegerType() ||
10018           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
10019 }
10020 
10021 namespace {
10022 /// The promoted range of values of a type. In general this has the
10023 /// following structure:
10024 ///
10025 ///     |-----------| . . . |-----------|
10026 ///     ^           ^       ^           ^
10027 ///    Min       HoleMin  HoleMax      Max
10028 ///
10029 /// ... where there is only a hole if a signed type is promoted to unsigned
10030 /// (in which case Min and Max are the smallest and largest representable
10031 /// values).
10032 struct PromotedRange {
10033   // Min, or HoleMax if there is a hole.
10034   llvm::APSInt PromotedMin;
10035   // Max, or HoleMin if there is a hole.
10036   llvm::APSInt PromotedMax;
10037 
10038   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
10039     if (R.Width == 0)
10040       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
10041     else if (R.Width >= BitWidth && !Unsigned) {
10042       // Promotion made the type *narrower*. This happens when promoting
10043       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
10044       // Treat all values of 'signed int' as being in range for now.
10045       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
10046       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
10047     } else {
10048       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
10049                         .extOrTrunc(BitWidth);
10050       PromotedMin.setIsUnsigned(Unsigned);
10051 
10052       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
10053                         .extOrTrunc(BitWidth);
10054       PromotedMax.setIsUnsigned(Unsigned);
10055     }
10056   }
10057 
10058   // Determine whether this range is contiguous (has no hole).
10059   bool isContiguous() const { return PromotedMin <= PromotedMax; }
10060 
10061   // Where a constant value is within the range.
10062   enum ComparisonResult {
10063     LT = 0x1,
10064     LE = 0x2,
10065     GT = 0x4,
10066     GE = 0x8,
10067     EQ = 0x10,
10068     NE = 0x20,
10069     InRangeFlag = 0x40,
10070 
10071     Less = LE | LT | NE,
10072     Min = LE | InRangeFlag,
10073     InRange = InRangeFlag,
10074     Max = GE | InRangeFlag,
10075     Greater = GE | GT | NE,
10076 
10077     OnlyValue = LE | GE | EQ | InRangeFlag,
10078     InHole = NE
10079   };
10080 
10081   ComparisonResult compare(const llvm::APSInt &Value) const {
10082     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
10083            Value.isUnsigned() == PromotedMin.isUnsigned());
10084     if (!isContiguous()) {
10085       assert(Value.isUnsigned() && "discontiguous range for signed compare");
10086       if (Value.isMinValue()) return Min;
10087       if (Value.isMaxValue()) return Max;
10088       if (Value >= PromotedMin) return InRange;
10089       if (Value <= PromotedMax) return InRange;
10090       return InHole;
10091     }
10092 
10093     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
10094     case -1: return Less;
10095     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
10096     case 1:
10097       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
10098       case -1: return InRange;
10099       case 0: return Max;
10100       case 1: return Greater;
10101       }
10102     }
10103 
10104     llvm_unreachable("impossible compare result");
10105   }
10106 
10107   static llvm::Optional<StringRef>
10108   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
10109     if (Op == BO_Cmp) {
10110       ComparisonResult LTFlag = LT, GTFlag = GT;
10111       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
10112 
10113       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
10114       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
10115       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
10116       return llvm::None;
10117     }
10118 
10119     ComparisonResult TrueFlag, FalseFlag;
10120     if (Op == BO_EQ) {
10121       TrueFlag = EQ;
10122       FalseFlag = NE;
10123     } else if (Op == BO_NE) {
10124       TrueFlag = NE;
10125       FalseFlag = EQ;
10126     } else {
10127       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
10128         TrueFlag = LT;
10129         FalseFlag = GE;
10130       } else {
10131         TrueFlag = GT;
10132         FalseFlag = LE;
10133       }
10134       if (Op == BO_GE || Op == BO_LE)
10135         std::swap(TrueFlag, FalseFlag);
10136     }
10137     if (R & TrueFlag)
10138       return StringRef("true");
10139     if (R & FalseFlag)
10140       return StringRef("false");
10141     return llvm::None;
10142   }
10143 };
10144 }
10145 
10146 static bool HasEnumType(Expr *E) {
10147   // Strip off implicit integral promotions.
10148   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
10149     if (ICE->getCastKind() != CK_IntegralCast &&
10150         ICE->getCastKind() != CK_NoOp)
10151       break;
10152     E = ICE->getSubExpr();
10153   }
10154 
10155   return E->getType()->isEnumeralType();
10156 }
10157 
10158 static int classifyConstantValue(Expr *Constant) {
10159   // The values of this enumeration are used in the diagnostics
10160   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
10161   enum ConstantValueKind {
10162     Miscellaneous = 0,
10163     LiteralTrue,
10164     LiteralFalse
10165   };
10166   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
10167     return BL->getValue() ? ConstantValueKind::LiteralTrue
10168                           : ConstantValueKind::LiteralFalse;
10169   return ConstantValueKind::Miscellaneous;
10170 }
10171 
10172 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
10173                                         Expr *Constant, Expr *Other,
10174                                         const llvm::APSInt &Value,
10175                                         bool RhsConstant) {
10176   if (S.inTemplateInstantiation())
10177     return false;
10178 
10179   Expr *OriginalOther = Other;
10180 
10181   Constant = Constant->IgnoreParenImpCasts();
10182   Other = Other->IgnoreParenImpCasts();
10183 
10184   // Suppress warnings on tautological comparisons between values of the same
10185   // enumeration type. There are only two ways we could warn on this:
10186   //  - If the constant is outside the range of representable values of
10187   //    the enumeration. In such a case, we should warn about the cast
10188   //    to enumeration type, not about the comparison.
10189   //  - If the constant is the maximum / minimum in-range value. For an
10190   //    enumeratin type, such comparisons can be meaningful and useful.
10191   if (Constant->getType()->isEnumeralType() &&
10192       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
10193     return false;
10194 
10195   // TODO: Investigate using GetExprRange() to get tighter bounds
10196   // on the bit ranges.
10197   QualType OtherT = Other->getType();
10198   if (const auto *AT = OtherT->getAs<AtomicType>())
10199     OtherT = AT->getValueType();
10200   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
10201 
10202   // Whether we're treating Other as being a bool because of the form of
10203   // expression despite it having another type (typically 'int' in C).
10204   bool OtherIsBooleanDespiteType =
10205       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
10206   if (OtherIsBooleanDespiteType)
10207     OtherRange = IntRange::forBoolType();
10208 
10209   // Determine the promoted range of the other type and see if a comparison of
10210   // the constant against that range is tautological.
10211   PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
10212                                    Value.isUnsigned());
10213   auto Cmp = OtherPromotedRange.compare(Value);
10214   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
10215   if (!Result)
10216     return false;
10217 
10218   // Suppress the diagnostic for an in-range comparison if the constant comes
10219   // from a macro or enumerator. We don't want to diagnose
10220   //
10221   //   some_long_value <= INT_MAX
10222   //
10223   // when sizeof(int) == sizeof(long).
10224   bool InRange = Cmp & PromotedRange::InRangeFlag;
10225   if (InRange && IsEnumConstOrFromMacro(S, Constant))
10226     return false;
10227 
10228   // If this is a comparison to an enum constant, include that
10229   // constant in the diagnostic.
10230   const EnumConstantDecl *ED = nullptr;
10231   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
10232     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
10233 
10234   // Should be enough for uint128 (39 decimal digits)
10235   SmallString<64> PrettySourceValue;
10236   llvm::raw_svector_ostream OS(PrettySourceValue);
10237   if (ED)
10238     OS << '\'' << *ED << "' (" << Value << ")";
10239   else
10240     OS << Value;
10241 
10242   // FIXME: We use a somewhat different formatting for the in-range cases and
10243   // cases involving boolean values for historical reasons. We should pick a
10244   // consistent way of presenting these diagnostics.
10245   if (!InRange || Other->isKnownToHaveBooleanValue()) {
10246     S.DiagRuntimeBehavior(
10247       E->getOperatorLoc(), E,
10248       S.PDiag(!InRange ? diag::warn_out_of_range_compare
10249                        : diag::warn_tautological_bool_compare)
10250           << OS.str() << classifyConstantValue(Constant)
10251           << OtherT << OtherIsBooleanDespiteType << *Result
10252           << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
10253   } else {
10254     unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
10255                         ? (HasEnumType(OriginalOther)
10256                                ? diag::warn_unsigned_enum_always_true_comparison
10257                                : diag::warn_unsigned_always_true_comparison)
10258                         : diag::warn_tautological_constant_compare;
10259 
10260     S.Diag(E->getOperatorLoc(), Diag)
10261         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
10262         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
10263   }
10264 
10265   return true;
10266 }
10267 
10268 /// Analyze the operands of the given comparison.  Implements the
10269 /// fallback case from AnalyzeComparison.
10270 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
10271   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10272   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10273 }
10274 
10275 /// Implements -Wsign-compare.
10276 ///
10277 /// \param E the binary operator to check for warnings
10278 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
10279   // The type the comparison is being performed in.
10280   QualType T = E->getLHS()->getType();
10281 
10282   // Only analyze comparison operators where both sides have been converted to
10283   // the same type.
10284   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
10285     return AnalyzeImpConvsInComparison(S, E);
10286 
10287   // Don't analyze value-dependent comparisons directly.
10288   if (E->isValueDependent())
10289     return AnalyzeImpConvsInComparison(S, E);
10290 
10291   Expr *LHS = E->getLHS();
10292   Expr *RHS = E->getRHS();
10293 
10294   if (T->isIntegralType(S.Context)) {
10295     llvm::APSInt RHSValue;
10296     llvm::APSInt LHSValue;
10297 
10298     bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
10299     bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
10300 
10301     // We don't care about expressions whose result is a constant.
10302     if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
10303       return AnalyzeImpConvsInComparison(S, E);
10304 
10305     // We only care about expressions where just one side is literal
10306     if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
10307       // Is the constant on the RHS or LHS?
10308       const bool RhsConstant = IsRHSIntegralLiteral;
10309       Expr *Const = RhsConstant ? RHS : LHS;
10310       Expr *Other = RhsConstant ? LHS : RHS;
10311       const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
10312 
10313       // Check whether an integer constant comparison results in a value
10314       // of 'true' or 'false'.
10315       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
10316         return AnalyzeImpConvsInComparison(S, E);
10317     }
10318   }
10319 
10320   if (!T->hasUnsignedIntegerRepresentation()) {
10321     // We don't do anything special if this isn't an unsigned integral
10322     // comparison:  we're only interested in integral comparisons, and
10323     // signed comparisons only happen in cases we don't care to warn about.
10324     return AnalyzeImpConvsInComparison(S, E);
10325   }
10326 
10327   LHS = LHS->IgnoreParenImpCasts();
10328   RHS = RHS->IgnoreParenImpCasts();
10329 
10330   if (!S.getLangOpts().CPlusPlus) {
10331     // Avoid warning about comparison of integers with different signs when
10332     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
10333     // the type of `E`.
10334     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
10335       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10336     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
10337       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10338   }
10339 
10340   // Check to see if one of the (unmodified) operands is of different
10341   // signedness.
10342   Expr *signedOperand, *unsignedOperand;
10343   if (LHS->getType()->hasSignedIntegerRepresentation()) {
10344     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
10345            "unsigned comparison between two signed integer expressions?");
10346     signedOperand = LHS;
10347     unsignedOperand = RHS;
10348   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
10349     signedOperand = RHS;
10350     unsignedOperand = LHS;
10351   } else {
10352     return AnalyzeImpConvsInComparison(S, E);
10353   }
10354 
10355   // Otherwise, calculate the effective range of the signed operand.
10356   IntRange signedRange = GetExprRange(S.Context, signedOperand);
10357 
10358   // Go ahead and analyze implicit conversions in the operands.  Note
10359   // that we skip the implicit conversions on both sides.
10360   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
10361   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
10362 
10363   // If the signed range is non-negative, -Wsign-compare won't fire.
10364   if (signedRange.NonNegative)
10365     return;
10366 
10367   // For (in)equality comparisons, if the unsigned operand is a
10368   // constant which cannot collide with a overflowed signed operand,
10369   // then reinterpreting the signed operand as unsigned will not
10370   // change the result of the comparison.
10371   if (E->isEqualityOp()) {
10372     unsigned comparisonWidth = S.Context.getIntWidth(T);
10373     IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
10374 
10375     // We should never be unable to prove that the unsigned operand is
10376     // non-negative.
10377     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
10378 
10379     if (unsignedRange.Width < comparisonWidth)
10380       return;
10381   }
10382 
10383   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10384     S.PDiag(diag::warn_mixed_sign_comparison)
10385       << LHS->getType() << RHS->getType()
10386       << LHS->getSourceRange() << RHS->getSourceRange());
10387 }
10388 
10389 /// Analyzes an attempt to assign the given value to a bitfield.
10390 ///
10391 /// Returns true if there was something fishy about the attempt.
10392 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
10393                                       SourceLocation InitLoc) {
10394   assert(Bitfield->isBitField());
10395   if (Bitfield->isInvalidDecl())
10396     return false;
10397 
10398   // White-list bool bitfields.
10399   QualType BitfieldType = Bitfield->getType();
10400   if (BitfieldType->isBooleanType())
10401      return false;
10402 
10403   if (BitfieldType->isEnumeralType()) {
10404     EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
10405     // If the underlying enum type was not explicitly specified as an unsigned
10406     // type and the enum contain only positive values, MSVC++ will cause an
10407     // inconsistency by storing this as a signed type.
10408     if (S.getLangOpts().CPlusPlus11 &&
10409         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
10410         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
10411         BitfieldEnumDecl->getNumNegativeBits() == 0) {
10412       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
10413         << BitfieldEnumDecl->getNameAsString();
10414     }
10415   }
10416 
10417   if (Bitfield->getType()->isBooleanType())
10418     return false;
10419 
10420   // Ignore value- or type-dependent expressions.
10421   if (Bitfield->getBitWidth()->isValueDependent() ||
10422       Bitfield->getBitWidth()->isTypeDependent() ||
10423       Init->isValueDependent() ||
10424       Init->isTypeDependent())
10425     return false;
10426 
10427   Expr *OriginalInit = Init->IgnoreParenImpCasts();
10428   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
10429 
10430   Expr::EvalResult Result;
10431   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
10432                                    Expr::SE_AllowSideEffects)) {
10433     // The RHS is not constant.  If the RHS has an enum type, make sure the
10434     // bitfield is wide enough to hold all the values of the enum without
10435     // truncation.
10436     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
10437       EnumDecl *ED = EnumTy->getDecl();
10438       bool SignedBitfield = BitfieldType->isSignedIntegerType();
10439 
10440       // Enum types are implicitly signed on Windows, so check if there are any
10441       // negative enumerators to see if the enum was intended to be signed or
10442       // not.
10443       bool SignedEnum = ED->getNumNegativeBits() > 0;
10444 
10445       // Check for surprising sign changes when assigning enum values to a
10446       // bitfield of different signedness.  If the bitfield is signed and we
10447       // have exactly the right number of bits to store this unsigned enum,
10448       // suggest changing the enum to an unsigned type. This typically happens
10449       // on Windows where unfixed enums always use an underlying type of 'int'.
10450       unsigned DiagID = 0;
10451       if (SignedEnum && !SignedBitfield) {
10452         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
10453       } else if (SignedBitfield && !SignedEnum &&
10454                  ED->getNumPositiveBits() == FieldWidth) {
10455         DiagID = diag::warn_signed_bitfield_enum_conversion;
10456       }
10457 
10458       if (DiagID) {
10459         S.Diag(InitLoc, DiagID) << Bitfield << ED;
10460         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
10461         SourceRange TypeRange =
10462             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
10463         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
10464             << SignedEnum << TypeRange;
10465       }
10466 
10467       // Compute the required bitwidth. If the enum has negative values, we need
10468       // one more bit than the normal number of positive bits to represent the
10469       // sign bit.
10470       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
10471                                                   ED->getNumNegativeBits())
10472                                        : ED->getNumPositiveBits();
10473 
10474       // Check the bitwidth.
10475       if (BitsNeeded > FieldWidth) {
10476         Expr *WidthExpr = Bitfield->getBitWidth();
10477         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
10478             << Bitfield << ED;
10479         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
10480             << BitsNeeded << ED << WidthExpr->getSourceRange();
10481       }
10482     }
10483 
10484     return false;
10485   }
10486 
10487   llvm::APSInt Value = Result.Val.getInt();
10488 
10489   unsigned OriginalWidth = Value.getBitWidth();
10490 
10491   if (!Value.isSigned() || Value.isNegative())
10492     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
10493       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
10494         OriginalWidth = Value.getMinSignedBits();
10495 
10496   if (OriginalWidth <= FieldWidth)
10497     return false;
10498 
10499   // Compute the value which the bitfield will contain.
10500   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
10501   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
10502 
10503   // Check whether the stored value is equal to the original value.
10504   TruncatedValue = TruncatedValue.extend(OriginalWidth);
10505   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
10506     return false;
10507 
10508   // Special-case bitfields of width 1: booleans are naturally 0/1, and
10509   // therefore don't strictly fit into a signed bitfield of width 1.
10510   if (FieldWidth == 1 && Value == 1)
10511     return false;
10512 
10513   std::string PrettyValue = Value.toString(10);
10514   std::string PrettyTrunc = TruncatedValue.toString(10);
10515 
10516   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
10517     << PrettyValue << PrettyTrunc << OriginalInit->getType()
10518     << Init->getSourceRange();
10519 
10520   return true;
10521 }
10522 
10523 /// Analyze the given simple or compound assignment for warning-worthy
10524 /// operations.
10525 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
10526   // Just recurse on the LHS.
10527   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10528 
10529   // We want to recurse on the RHS as normal unless we're assigning to
10530   // a bitfield.
10531   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
10532     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
10533                                   E->getOperatorLoc())) {
10534       // Recurse, ignoring any implicit conversions on the RHS.
10535       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
10536                                         E->getOperatorLoc());
10537     }
10538   }
10539 
10540   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10541 
10542   // Diagnose implicitly sequentially-consistent atomic assignment.
10543   if (E->getLHS()->getType()->isAtomicType())
10544     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
10545 }
10546 
10547 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
10548 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
10549                             SourceLocation CContext, unsigned diag,
10550                             bool pruneControlFlow = false) {
10551   if (pruneControlFlow) {
10552     S.DiagRuntimeBehavior(E->getExprLoc(), E,
10553                           S.PDiag(diag)
10554                             << SourceType << T << E->getSourceRange()
10555                             << SourceRange(CContext));
10556     return;
10557   }
10558   S.Diag(E->getExprLoc(), diag)
10559     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
10560 }
10561 
10562 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
10563 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
10564                             SourceLocation CContext,
10565                             unsigned diag, bool pruneControlFlow = false) {
10566   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
10567 }
10568 
10569 /// Diagnose an implicit cast from a floating point value to an integer value.
10570 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
10571                                     SourceLocation CContext) {
10572   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
10573   const bool PruneWarnings = S.inTemplateInstantiation();
10574 
10575   Expr *InnerE = E->IgnoreParenImpCasts();
10576   // We also want to warn on, e.g., "int i = -1.234"
10577   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
10578     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
10579       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
10580 
10581   const bool IsLiteral =
10582       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
10583 
10584   llvm::APFloat Value(0.0);
10585   bool IsConstant =
10586     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
10587   if (!IsConstant) {
10588     return DiagnoseImpCast(S, E, T, CContext,
10589                            diag::warn_impcast_float_integer, PruneWarnings);
10590   }
10591 
10592   bool isExact = false;
10593 
10594   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
10595                             T->hasUnsignedIntegerRepresentation());
10596   llvm::APFloat::opStatus Result = Value.convertToInteger(
10597       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
10598 
10599   if (Result == llvm::APFloat::opOK && isExact) {
10600     if (IsLiteral) return;
10601     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
10602                            PruneWarnings);
10603   }
10604 
10605   // Conversion of a floating-point value to a non-bool integer where the
10606   // integral part cannot be represented by the integer type is undefined.
10607   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
10608     return DiagnoseImpCast(
10609         S, E, T, CContext,
10610         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
10611                   : diag::warn_impcast_float_to_integer_out_of_range,
10612         PruneWarnings);
10613 
10614   unsigned DiagID = 0;
10615   if (IsLiteral) {
10616     // Warn on floating point literal to integer.
10617     DiagID = diag::warn_impcast_literal_float_to_integer;
10618   } else if (IntegerValue == 0) {
10619     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
10620       return DiagnoseImpCast(S, E, T, CContext,
10621                              diag::warn_impcast_float_integer, PruneWarnings);
10622     }
10623     // Warn on non-zero to zero conversion.
10624     DiagID = diag::warn_impcast_float_to_integer_zero;
10625   } else {
10626     if (IntegerValue.isUnsigned()) {
10627       if (!IntegerValue.isMaxValue()) {
10628         return DiagnoseImpCast(S, E, T, CContext,
10629                                diag::warn_impcast_float_integer, PruneWarnings);
10630       }
10631     } else {  // IntegerValue.isSigned()
10632       if (!IntegerValue.isMaxSignedValue() &&
10633           !IntegerValue.isMinSignedValue()) {
10634         return DiagnoseImpCast(S, E, T, CContext,
10635                                diag::warn_impcast_float_integer, PruneWarnings);
10636       }
10637     }
10638     // Warn on evaluatable floating point expression to integer conversion.
10639     DiagID = diag::warn_impcast_float_to_integer;
10640   }
10641 
10642   // FIXME: Force the precision of the source value down so we don't print
10643   // digits which are usually useless (we don't really care here if we
10644   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
10645   // would automatically print the shortest representation, but it's a bit
10646   // tricky to implement.
10647   SmallString<16> PrettySourceValue;
10648   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
10649   precision = (precision * 59 + 195) / 196;
10650   Value.toString(PrettySourceValue, precision);
10651 
10652   SmallString<16> PrettyTargetValue;
10653   if (IsBool)
10654     PrettyTargetValue = Value.isZero() ? "false" : "true";
10655   else
10656     IntegerValue.toString(PrettyTargetValue);
10657 
10658   if (PruneWarnings) {
10659     S.DiagRuntimeBehavior(E->getExprLoc(), E,
10660                           S.PDiag(DiagID)
10661                               << E->getType() << T.getUnqualifiedType()
10662                               << PrettySourceValue << PrettyTargetValue
10663                               << E->getSourceRange() << SourceRange(CContext));
10664   } else {
10665     S.Diag(E->getExprLoc(), DiagID)
10666         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
10667         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
10668   }
10669 }
10670 
10671 /// Analyze the given compound assignment for the possible losing of
10672 /// floating-point precision.
10673 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
10674   assert(isa<CompoundAssignOperator>(E) &&
10675          "Must be compound assignment operation");
10676   // Recurse on the LHS and RHS in here
10677   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10678   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10679 
10680   if (E->getLHS()->getType()->isAtomicType())
10681     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
10682 
10683   // Now check the outermost expression
10684   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
10685   const auto *RBT = cast<CompoundAssignOperator>(E)
10686                         ->getComputationResultType()
10687                         ->getAs<BuiltinType>();
10688 
10689   // The below checks assume source is floating point.
10690   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
10691 
10692   // If source is floating point but target is an integer.
10693   if (ResultBT->isInteger())
10694     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
10695                            E->getExprLoc(), diag::warn_impcast_float_integer);
10696 
10697   if (!ResultBT->isFloatingPoint())
10698     return;
10699 
10700   // If both source and target are floating points, warn about losing precision.
10701   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
10702       QualType(ResultBT, 0), QualType(RBT, 0));
10703   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
10704     // warn about dropping FP rank.
10705     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
10706                     diag::warn_impcast_float_result_precision);
10707 }
10708 
10709 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
10710                                       IntRange Range) {
10711   if (!Range.Width) return "0";
10712 
10713   llvm::APSInt ValueInRange = Value;
10714   ValueInRange.setIsSigned(!Range.NonNegative);
10715   ValueInRange = ValueInRange.trunc(Range.Width);
10716   return ValueInRange.toString(10);
10717 }
10718 
10719 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
10720   if (!isa<ImplicitCastExpr>(Ex))
10721     return false;
10722 
10723   Expr *InnerE = Ex->IgnoreParenImpCasts();
10724   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
10725   const Type *Source =
10726     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
10727   if (Target->isDependentType())
10728     return false;
10729 
10730   const BuiltinType *FloatCandidateBT =
10731     dyn_cast<BuiltinType>(ToBool ? Source : Target);
10732   const Type *BoolCandidateType = ToBool ? Target : Source;
10733 
10734   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
10735           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
10736 }
10737 
10738 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
10739                                              SourceLocation CC) {
10740   unsigned NumArgs = TheCall->getNumArgs();
10741   for (unsigned i = 0; i < NumArgs; ++i) {
10742     Expr *CurrA = TheCall->getArg(i);
10743     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
10744       continue;
10745 
10746     bool IsSwapped = ((i > 0) &&
10747         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
10748     IsSwapped |= ((i < (NumArgs - 1)) &&
10749         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
10750     if (IsSwapped) {
10751       // Warn on this floating-point to bool conversion.
10752       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
10753                       CurrA->getType(), CC,
10754                       diag::warn_impcast_floating_point_to_bool);
10755     }
10756   }
10757 }
10758 
10759 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
10760                                    SourceLocation CC) {
10761   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
10762                         E->getExprLoc()))
10763     return;
10764 
10765   // Don't warn on functions which have return type nullptr_t.
10766   if (isa<CallExpr>(E))
10767     return;
10768 
10769   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
10770   const Expr::NullPointerConstantKind NullKind =
10771       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
10772   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
10773     return;
10774 
10775   // Return if target type is a safe conversion.
10776   if (T->isAnyPointerType() || T->isBlockPointerType() ||
10777       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
10778     return;
10779 
10780   SourceLocation Loc = E->getSourceRange().getBegin();
10781 
10782   // Venture through the macro stacks to get to the source of macro arguments.
10783   // The new location is a better location than the complete location that was
10784   // passed in.
10785   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
10786   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
10787 
10788   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
10789   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
10790     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
10791         Loc, S.SourceMgr, S.getLangOpts());
10792     if (MacroName == "NULL")
10793       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
10794   }
10795 
10796   // Only warn if the null and context location are in the same macro expansion.
10797   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
10798     return;
10799 
10800   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
10801       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
10802       << FixItHint::CreateReplacement(Loc,
10803                                       S.getFixItZeroLiteralForType(T, Loc));
10804 }
10805 
10806 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
10807                                   ObjCArrayLiteral *ArrayLiteral);
10808 
10809 static void
10810 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
10811                            ObjCDictionaryLiteral *DictionaryLiteral);
10812 
10813 /// Check a single element within a collection literal against the
10814 /// target element type.
10815 static void checkObjCCollectionLiteralElement(Sema &S,
10816                                               QualType TargetElementType,
10817                                               Expr *Element,
10818                                               unsigned ElementKind) {
10819   // Skip a bitcast to 'id' or qualified 'id'.
10820   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
10821     if (ICE->getCastKind() == CK_BitCast &&
10822         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
10823       Element = ICE->getSubExpr();
10824   }
10825 
10826   QualType ElementType = Element->getType();
10827   ExprResult ElementResult(Element);
10828   if (ElementType->getAs<ObjCObjectPointerType>() &&
10829       S.CheckSingleAssignmentConstraints(TargetElementType,
10830                                          ElementResult,
10831                                          false, false)
10832         != Sema::Compatible) {
10833     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
10834         << ElementType << ElementKind << TargetElementType
10835         << Element->getSourceRange();
10836   }
10837 
10838   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
10839     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
10840   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
10841     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
10842 }
10843 
10844 /// Check an Objective-C array literal being converted to the given
10845 /// target type.
10846 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
10847                                   ObjCArrayLiteral *ArrayLiteral) {
10848   if (!S.NSArrayDecl)
10849     return;
10850 
10851   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
10852   if (!TargetObjCPtr)
10853     return;
10854 
10855   if (TargetObjCPtr->isUnspecialized() ||
10856       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
10857         != S.NSArrayDecl->getCanonicalDecl())
10858     return;
10859 
10860   auto TypeArgs = TargetObjCPtr->getTypeArgs();
10861   if (TypeArgs.size() != 1)
10862     return;
10863 
10864   QualType TargetElementType = TypeArgs[0];
10865   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
10866     checkObjCCollectionLiteralElement(S, TargetElementType,
10867                                       ArrayLiteral->getElement(I),
10868                                       0);
10869   }
10870 }
10871 
10872 /// Check an Objective-C dictionary literal being converted to the given
10873 /// target type.
10874 static void
10875 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
10876                            ObjCDictionaryLiteral *DictionaryLiteral) {
10877   if (!S.NSDictionaryDecl)
10878     return;
10879 
10880   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
10881   if (!TargetObjCPtr)
10882     return;
10883 
10884   if (TargetObjCPtr->isUnspecialized() ||
10885       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
10886         != S.NSDictionaryDecl->getCanonicalDecl())
10887     return;
10888 
10889   auto TypeArgs = TargetObjCPtr->getTypeArgs();
10890   if (TypeArgs.size() != 2)
10891     return;
10892 
10893   QualType TargetKeyType = TypeArgs[0];
10894   QualType TargetObjectType = TypeArgs[1];
10895   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
10896     auto Element = DictionaryLiteral->getKeyValueElement(I);
10897     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
10898     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
10899   }
10900 }
10901 
10902 // Helper function to filter out cases for constant width constant conversion.
10903 // Don't warn on char array initialization or for non-decimal values.
10904 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
10905                                           SourceLocation CC) {
10906   // If initializing from a constant, and the constant starts with '0',
10907   // then it is a binary, octal, or hexadecimal.  Allow these constants
10908   // to fill all the bits, even if there is a sign change.
10909   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
10910     const char FirstLiteralCharacter =
10911         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
10912     if (FirstLiteralCharacter == '0')
10913       return false;
10914   }
10915 
10916   // If the CC location points to a '{', and the type is char, then assume
10917   // assume it is an array initialization.
10918   if (CC.isValid() && T->isCharType()) {
10919     const char FirstContextCharacter =
10920         S.getSourceManager().getCharacterData(CC)[0];
10921     if (FirstContextCharacter == '{')
10922       return false;
10923   }
10924 
10925   return true;
10926 }
10927 
10928 static void
10929 CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC,
10930                         bool *ICContext = nullptr) {
10931   if (E->isTypeDependent() || E->isValueDependent()) return;
10932 
10933   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
10934   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
10935   if (Source == Target) return;
10936   if (Target->isDependentType()) return;
10937 
10938   // If the conversion context location is invalid don't complain. We also
10939   // don't want to emit a warning if the issue occurs from the expansion of
10940   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
10941   // delay this check as long as possible. Once we detect we are in that
10942   // scenario, we just return.
10943   if (CC.isInvalid())
10944     return;
10945 
10946   if (Source->isAtomicType())
10947     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
10948 
10949   // Diagnose implicit casts to bool.
10950   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
10951     if (isa<StringLiteral>(E))
10952       // Warn on string literal to bool.  Checks for string literals in logical
10953       // and expressions, for instance, assert(0 && "error here"), are
10954       // prevented by a check in AnalyzeImplicitConversions().
10955       return DiagnoseImpCast(S, E, T, CC,
10956                              diag::warn_impcast_string_literal_to_bool);
10957     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
10958         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
10959       // This covers the literal expressions that evaluate to Objective-C
10960       // objects.
10961       return DiagnoseImpCast(S, E, T, CC,
10962                              diag::warn_impcast_objective_c_literal_to_bool);
10963     }
10964     if (Source->isPointerType() || Source->canDecayToPointerType()) {
10965       // Warn on pointer to bool conversion that is always true.
10966       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
10967                                      SourceRange(CC));
10968     }
10969   }
10970 
10971   // Check implicit casts from Objective-C collection literals to specialized
10972   // collection types, e.g., NSArray<NSString *> *.
10973   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
10974     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
10975   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
10976     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
10977 
10978   // Strip vector types.
10979   if (isa<VectorType>(Source)) {
10980     if (!isa<VectorType>(Target)) {
10981       if (S.SourceMgr.isInSystemMacro(CC))
10982         return;
10983       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
10984     }
10985 
10986     // If the vector cast is cast between two vectors of the same size, it is
10987     // a bitcast, not a conversion.
10988     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
10989       return;
10990 
10991     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
10992     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
10993   }
10994   if (auto VecTy = dyn_cast<VectorType>(Target))
10995     Target = VecTy->getElementType().getTypePtr();
10996 
10997   // Strip complex types.
10998   if (isa<ComplexType>(Source)) {
10999     if (!isa<ComplexType>(Target)) {
11000       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
11001         return;
11002 
11003       return DiagnoseImpCast(S, E, T, CC,
11004                              S.getLangOpts().CPlusPlus
11005                                  ? diag::err_impcast_complex_scalar
11006                                  : diag::warn_impcast_complex_scalar);
11007     }
11008 
11009     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
11010     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
11011   }
11012 
11013   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
11014   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
11015 
11016   // If the source is floating point...
11017   if (SourceBT && SourceBT->isFloatingPoint()) {
11018     // ...and the target is floating point...
11019     if (TargetBT && TargetBT->isFloatingPoint()) {
11020       // ...then warn if we're dropping FP rank.
11021 
11022       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11023           QualType(SourceBT, 0), QualType(TargetBT, 0));
11024       if (Order > 0) {
11025         // Don't warn about float constants that are precisely
11026         // representable in the target type.
11027         Expr::EvalResult result;
11028         if (E->EvaluateAsRValue(result, S.Context)) {
11029           // Value might be a float, a float vector, or a float complex.
11030           if (IsSameFloatAfterCast(result.Val,
11031                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
11032                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
11033             return;
11034         }
11035 
11036         if (S.SourceMgr.isInSystemMacro(CC))
11037           return;
11038 
11039         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
11040       }
11041       // ... or possibly if we're increasing rank, too
11042       else if (Order < 0) {
11043         if (S.SourceMgr.isInSystemMacro(CC))
11044           return;
11045 
11046         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
11047       }
11048       return;
11049     }
11050 
11051     // If the target is integral, always warn.
11052     if (TargetBT && TargetBT->isInteger()) {
11053       if (S.SourceMgr.isInSystemMacro(CC))
11054         return;
11055 
11056       DiagnoseFloatingImpCast(S, E, T, CC);
11057     }
11058 
11059     // Detect the case where a call result is converted from floating-point to
11060     // to bool, and the final argument to the call is converted from bool, to
11061     // discover this typo:
11062     //
11063     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
11064     //
11065     // FIXME: This is an incredibly special case; is there some more general
11066     // way to detect this class of misplaced-parentheses bug?
11067     if (Target->isBooleanType() && isa<CallExpr>(E)) {
11068       // Check last argument of function call to see if it is an
11069       // implicit cast from a type matching the type the result
11070       // is being cast to.
11071       CallExpr *CEx = cast<CallExpr>(E);
11072       if (unsigned NumArgs = CEx->getNumArgs()) {
11073         Expr *LastA = CEx->getArg(NumArgs - 1);
11074         Expr *InnerE = LastA->IgnoreParenImpCasts();
11075         if (isa<ImplicitCastExpr>(LastA) &&
11076             InnerE->getType()->isBooleanType()) {
11077           // Warn on this floating-point to bool conversion
11078           DiagnoseImpCast(S, E, T, CC,
11079                           diag::warn_impcast_floating_point_to_bool);
11080         }
11081       }
11082     }
11083     return;
11084   }
11085 
11086   // Valid casts involving fixed point types should be accounted for here.
11087   if (Source->isFixedPointType()) {
11088     if (Target->isUnsaturatedFixedPointType()) {
11089       Expr::EvalResult Result;
11090       if (E->EvaluateAsFixedPoint(Result, S.Context,
11091                                   Expr::SE_AllowSideEffects)) {
11092         APFixedPoint Value = Result.Val.getFixedPoint();
11093         APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
11094         APFixedPoint MinVal = S.Context.getFixedPointMin(T);
11095         if (Value > MaxVal || Value < MinVal) {
11096           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11097                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11098                                     << Value.toString() << T
11099                                     << E->getSourceRange()
11100                                     << clang::SourceRange(CC));
11101           return;
11102         }
11103       }
11104     } else if (Target->isIntegerType()) {
11105       Expr::EvalResult Result;
11106       if (E->EvaluateAsFixedPoint(Result, S.Context,
11107                                   Expr::SE_AllowSideEffects)) {
11108         APFixedPoint FXResult = Result.Val.getFixedPoint();
11109 
11110         bool Overflowed;
11111         llvm::APSInt IntResult = FXResult.convertToInt(
11112             S.Context.getIntWidth(T),
11113             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
11114 
11115         if (Overflowed) {
11116           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11117                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11118                                     << FXResult.toString() << T
11119                                     << E->getSourceRange()
11120                                     << clang::SourceRange(CC));
11121           return;
11122         }
11123       }
11124     }
11125   } else if (Target->isUnsaturatedFixedPointType()) {
11126     if (Source->isIntegerType()) {
11127       Expr::EvalResult Result;
11128       if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
11129         llvm::APSInt Value = Result.Val.getInt();
11130 
11131         bool Overflowed;
11132         APFixedPoint IntResult = APFixedPoint::getFromIntValue(
11133             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
11134 
11135         if (Overflowed) {
11136           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11137                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11138                                     << Value.toString(/*radix=*/10) << T
11139                                     << E->getSourceRange()
11140                                     << clang::SourceRange(CC));
11141           return;
11142         }
11143       }
11144     }
11145   }
11146 
11147   DiagnoseNullConversion(S, E, T, CC);
11148 
11149   S.DiscardMisalignedMemberAddress(Target, E);
11150 
11151   if (!Source->isIntegerType() || !Target->isIntegerType())
11152     return;
11153 
11154   // TODO: remove this early return once the false positives for constant->bool
11155   // in templates, macros, etc, are reduced or removed.
11156   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
11157     return;
11158 
11159   IntRange SourceRange = GetExprRange(S.Context, E);
11160   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
11161 
11162   if (SourceRange.Width > TargetRange.Width) {
11163     // If the source is a constant, use a default-on diagnostic.
11164     // TODO: this should happen for bitfield stores, too.
11165     Expr::EvalResult Result;
11166     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
11167       llvm::APSInt Value(32);
11168       Value = Result.Val.getInt();
11169 
11170       if (S.SourceMgr.isInSystemMacro(CC))
11171         return;
11172 
11173       std::string PrettySourceValue = Value.toString(10);
11174       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11175 
11176       S.DiagRuntimeBehavior(E->getExprLoc(), E,
11177         S.PDiag(diag::warn_impcast_integer_precision_constant)
11178             << PrettySourceValue << PrettyTargetValue
11179             << E->getType() << T << E->getSourceRange()
11180             << clang::SourceRange(CC));
11181       return;
11182     }
11183 
11184     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
11185     if (S.SourceMgr.isInSystemMacro(CC))
11186       return;
11187 
11188     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
11189       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
11190                              /* pruneControlFlow */ true);
11191     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
11192   }
11193 
11194   if (TargetRange.Width > SourceRange.Width) {
11195     if (auto *UO = dyn_cast<UnaryOperator>(E))
11196       if (UO->getOpcode() == UO_Minus)
11197         if (Source->isUnsignedIntegerType()) {
11198           if (Target->isUnsignedIntegerType())
11199             return DiagnoseImpCast(S, E, T, CC,
11200                                    diag::warn_impcast_high_order_zero_bits);
11201           if (Target->isSignedIntegerType())
11202             return DiagnoseImpCast(S, E, T, CC,
11203                                    diag::warn_impcast_nonnegative_result);
11204         }
11205   }
11206 
11207   if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
11208       SourceRange.NonNegative && Source->isSignedIntegerType()) {
11209     // Warn when doing a signed to signed conversion, warn if the positive
11210     // source value is exactly the width of the target type, which will
11211     // cause a negative value to be stored.
11212 
11213     Expr::EvalResult Result;
11214     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
11215         !S.SourceMgr.isInSystemMacro(CC)) {
11216       llvm::APSInt Value = Result.Val.getInt();
11217       if (isSameWidthConstantConversion(S, E, T, CC)) {
11218         std::string PrettySourceValue = Value.toString(10);
11219         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11220 
11221         S.DiagRuntimeBehavior(
11222             E->getExprLoc(), E,
11223             S.PDiag(diag::warn_impcast_integer_precision_constant)
11224                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
11225                 << E->getSourceRange() << clang::SourceRange(CC));
11226         return;
11227       }
11228     }
11229 
11230     // Fall through for non-constants to give a sign conversion warning.
11231   }
11232 
11233   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
11234       (!TargetRange.NonNegative && SourceRange.NonNegative &&
11235        SourceRange.Width == TargetRange.Width)) {
11236     if (S.SourceMgr.isInSystemMacro(CC))
11237       return;
11238 
11239     unsigned DiagID = diag::warn_impcast_integer_sign;
11240 
11241     // Traditionally, gcc has warned about this under -Wsign-compare.
11242     // We also want to warn about it in -Wconversion.
11243     // So if -Wconversion is off, use a completely identical diagnostic
11244     // in the sign-compare group.
11245     // The conditional-checking code will
11246     if (ICContext) {
11247       DiagID = diag::warn_impcast_integer_sign_conditional;
11248       *ICContext = true;
11249     }
11250 
11251     return DiagnoseImpCast(S, E, T, CC, DiagID);
11252   }
11253 
11254   // Diagnose conversions between different enumeration types.
11255   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
11256   // type, to give us better diagnostics.
11257   QualType SourceType = E->getType();
11258   if (!S.getLangOpts().CPlusPlus) {
11259     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11260       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
11261         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
11262         SourceType = S.Context.getTypeDeclType(Enum);
11263         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
11264       }
11265   }
11266 
11267   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
11268     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
11269       if (SourceEnum->getDecl()->hasNameForLinkage() &&
11270           TargetEnum->getDecl()->hasNameForLinkage() &&
11271           SourceEnum != TargetEnum) {
11272         if (S.SourceMgr.isInSystemMacro(CC))
11273           return;
11274 
11275         return DiagnoseImpCast(S, E, SourceType, T, CC,
11276                                diag::warn_impcast_different_enum_types);
11277       }
11278 }
11279 
11280 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11281                                      SourceLocation CC, QualType T);
11282 
11283 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
11284                                     SourceLocation CC, bool &ICContext) {
11285   E = E->IgnoreParenImpCasts();
11286 
11287   if (isa<ConditionalOperator>(E))
11288     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
11289 
11290   AnalyzeImplicitConversions(S, E, CC);
11291   if (E->getType() != T)
11292     return CheckImplicitConversion(S, E, T, CC, &ICContext);
11293 }
11294 
11295 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11296                                      SourceLocation CC, QualType T) {
11297   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
11298 
11299   bool Suspicious = false;
11300   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
11301   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
11302 
11303   // If -Wconversion would have warned about either of the candidates
11304   // for a signedness conversion to the context type...
11305   if (!Suspicious) return;
11306 
11307   // ...but it's currently ignored...
11308   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
11309     return;
11310 
11311   // ...then check whether it would have warned about either of the
11312   // candidates for a signedness conversion to the condition type.
11313   if (E->getType() == T) return;
11314 
11315   Suspicious = false;
11316   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
11317                           E->getType(), CC, &Suspicious);
11318   if (!Suspicious)
11319     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
11320                             E->getType(), CC, &Suspicious);
11321 }
11322 
11323 /// Check conversion of given expression to boolean.
11324 /// Input argument E is a logical expression.
11325 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
11326   if (S.getLangOpts().Bool)
11327     return;
11328   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
11329     return;
11330   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
11331 }
11332 
11333 /// AnalyzeImplicitConversions - Find and report any interesting
11334 /// implicit conversions in the given expression.  There are a couple
11335 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
11336 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE,
11337                                        SourceLocation CC) {
11338   QualType T = OrigE->getType();
11339   Expr *E = OrigE->IgnoreParenImpCasts();
11340 
11341   if (E->isTypeDependent() || E->isValueDependent())
11342     return;
11343 
11344   // For conditional operators, we analyze the arguments as if they
11345   // were being fed directly into the output.
11346   if (isa<ConditionalOperator>(E)) {
11347     ConditionalOperator *CO = cast<ConditionalOperator>(E);
11348     CheckConditionalOperator(S, CO, CC, T);
11349     return;
11350   }
11351 
11352   // Check implicit argument conversions for function calls.
11353   if (CallExpr *Call = dyn_cast<CallExpr>(E))
11354     CheckImplicitArgumentConversions(S, Call, CC);
11355 
11356   // Go ahead and check any implicit conversions we might have skipped.
11357   // The non-canonical typecheck is just an optimization;
11358   // CheckImplicitConversion will filter out dead implicit conversions.
11359   if (E->getType() != T)
11360     CheckImplicitConversion(S, E, T, CC);
11361 
11362   // Now continue drilling into this expression.
11363 
11364   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
11365     // The bound subexpressions in a PseudoObjectExpr are not reachable
11366     // as transitive children.
11367     // FIXME: Use a more uniform representation for this.
11368     for (auto *SE : POE->semantics())
11369       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
11370         AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
11371   }
11372 
11373   // Skip past explicit casts.
11374   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
11375     E = CE->getSubExpr()->IgnoreParenImpCasts();
11376     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
11377       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
11378     return AnalyzeImplicitConversions(S, E, CC);
11379   }
11380 
11381   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11382     // Do a somewhat different check with comparison operators.
11383     if (BO->isComparisonOp())
11384       return AnalyzeComparison(S, BO);
11385 
11386     // And with simple assignments.
11387     if (BO->getOpcode() == BO_Assign)
11388       return AnalyzeAssignment(S, BO);
11389     // And with compound assignments.
11390     if (BO->isAssignmentOp())
11391       return AnalyzeCompoundAssignment(S, BO);
11392   }
11393 
11394   // These break the otherwise-useful invariant below.  Fortunately,
11395   // we don't really need to recurse into them, because any internal
11396   // expressions should have been analyzed already when they were
11397   // built into statements.
11398   if (isa<StmtExpr>(E)) return;
11399 
11400   // Don't descend into unevaluated contexts.
11401   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
11402 
11403   // Now just recurse over the expression's children.
11404   CC = E->getExprLoc();
11405   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
11406   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
11407   for (Stmt *SubStmt : E->children()) {
11408     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
11409     if (!ChildExpr)
11410       continue;
11411 
11412     if (IsLogicalAndOperator &&
11413         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
11414       // Ignore checking string literals that are in logical and operators.
11415       // This is a common pattern for asserts.
11416       continue;
11417     AnalyzeImplicitConversions(S, ChildExpr, CC);
11418   }
11419 
11420   if (BO && BO->isLogicalOp()) {
11421     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
11422     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
11423       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
11424 
11425     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
11426     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
11427       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
11428   }
11429 
11430   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
11431     if (U->getOpcode() == UO_LNot) {
11432       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
11433     } else if (U->getOpcode() != UO_AddrOf) {
11434       if (U->getSubExpr()->getType()->isAtomicType())
11435         S.Diag(U->getSubExpr()->getBeginLoc(),
11436                diag::warn_atomic_implicit_seq_cst);
11437     }
11438   }
11439 }
11440 
11441 /// Diagnose integer type and any valid implicit conversion to it.
11442 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
11443   // Taking into account implicit conversions,
11444   // allow any integer.
11445   if (!E->getType()->isIntegerType()) {
11446     S.Diag(E->getBeginLoc(),
11447            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
11448     return true;
11449   }
11450   // Potentially emit standard warnings for implicit conversions if enabled
11451   // using -Wconversion.
11452   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
11453   return false;
11454 }
11455 
11456 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
11457 // Returns true when emitting a warning about taking the address of a reference.
11458 static bool CheckForReference(Sema &SemaRef, const Expr *E,
11459                               const PartialDiagnostic &PD) {
11460   E = E->IgnoreParenImpCasts();
11461 
11462   const FunctionDecl *FD = nullptr;
11463 
11464   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11465     if (!DRE->getDecl()->getType()->isReferenceType())
11466       return false;
11467   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
11468     if (!M->getMemberDecl()->getType()->isReferenceType())
11469       return false;
11470   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
11471     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
11472       return false;
11473     FD = Call->getDirectCallee();
11474   } else {
11475     return false;
11476   }
11477 
11478   SemaRef.Diag(E->getExprLoc(), PD);
11479 
11480   // If possible, point to location of function.
11481   if (FD) {
11482     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
11483   }
11484 
11485   return true;
11486 }
11487 
11488 // Returns true if the SourceLocation is expanded from any macro body.
11489 // Returns false if the SourceLocation is invalid, is from not in a macro
11490 // expansion, or is from expanded from a top-level macro argument.
11491 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
11492   if (Loc.isInvalid())
11493     return false;
11494 
11495   while (Loc.isMacroID()) {
11496     if (SM.isMacroBodyExpansion(Loc))
11497       return true;
11498     Loc = SM.getImmediateMacroCallerLoc(Loc);
11499   }
11500 
11501   return false;
11502 }
11503 
11504 /// Diagnose pointers that are always non-null.
11505 /// \param E the expression containing the pointer
11506 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
11507 /// compared to a null pointer
11508 /// \param IsEqual True when the comparison is equal to a null pointer
11509 /// \param Range Extra SourceRange to highlight in the diagnostic
11510 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
11511                                         Expr::NullPointerConstantKind NullKind,
11512                                         bool IsEqual, SourceRange Range) {
11513   if (!E)
11514     return;
11515 
11516   // Don't warn inside macros.
11517   if (E->getExprLoc().isMacroID()) {
11518     const SourceManager &SM = getSourceManager();
11519     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
11520         IsInAnyMacroBody(SM, Range.getBegin()))
11521       return;
11522   }
11523   E = E->IgnoreImpCasts();
11524 
11525   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
11526 
11527   if (isa<CXXThisExpr>(E)) {
11528     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
11529                                 : diag::warn_this_bool_conversion;
11530     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
11531     return;
11532   }
11533 
11534   bool IsAddressOf = false;
11535 
11536   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
11537     if (UO->getOpcode() != UO_AddrOf)
11538       return;
11539     IsAddressOf = true;
11540     E = UO->getSubExpr();
11541   }
11542 
11543   if (IsAddressOf) {
11544     unsigned DiagID = IsCompare
11545                           ? diag::warn_address_of_reference_null_compare
11546                           : diag::warn_address_of_reference_bool_conversion;
11547     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
11548                                          << IsEqual;
11549     if (CheckForReference(*this, E, PD)) {
11550       return;
11551     }
11552   }
11553 
11554   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
11555     bool IsParam = isa<NonNullAttr>(NonnullAttr);
11556     std::string Str;
11557     llvm::raw_string_ostream S(Str);
11558     E->printPretty(S, nullptr, getPrintingPolicy());
11559     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
11560                                 : diag::warn_cast_nonnull_to_bool;
11561     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
11562       << E->getSourceRange() << Range << IsEqual;
11563     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
11564   };
11565 
11566   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
11567   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
11568     if (auto *Callee = Call->getDirectCallee()) {
11569       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
11570         ComplainAboutNonnullParamOrCall(A);
11571         return;
11572       }
11573     }
11574   }
11575 
11576   // Expect to find a single Decl.  Skip anything more complicated.
11577   ValueDecl *D = nullptr;
11578   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
11579     D = R->getDecl();
11580   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
11581     D = M->getMemberDecl();
11582   }
11583 
11584   // Weak Decls can be null.
11585   if (!D || D->isWeak())
11586     return;
11587 
11588   // Check for parameter decl with nonnull attribute
11589   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
11590     if (getCurFunction() &&
11591         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
11592       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
11593         ComplainAboutNonnullParamOrCall(A);
11594         return;
11595       }
11596 
11597       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
11598         // Skip function template not specialized yet.
11599         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
11600           return;
11601         auto ParamIter = llvm::find(FD->parameters(), PV);
11602         assert(ParamIter != FD->param_end());
11603         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
11604 
11605         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
11606           if (!NonNull->args_size()) {
11607               ComplainAboutNonnullParamOrCall(NonNull);
11608               return;
11609           }
11610 
11611           for (const ParamIdx &ArgNo : NonNull->args()) {
11612             if (ArgNo.getASTIndex() == ParamNo) {
11613               ComplainAboutNonnullParamOrCall(NonNull);
11614               return;
11615             }
11616           }
11617         }
11618       }
11619     }
11620   }
11621 
11622   QualType T = D->getType();
11623   const bool IsArray = T->isArrayType();
11624   const bool IsFunction = T->isFunctionType();
11625 
11626   // Address of function is used to silence the function warning.
11627   if (IsAddressOf && IsFunction) {
11628     return;
11629   }
11630 
11631   // Found nothing.
11632   if (!IsAddressOf && !IsFunction && !IsArray)
11633     return;
11634 
11635   // Pretty print the expression for the diagnostic.
11636   std::string Str;
11637   llvm::raw_string_ostream S(Str);
11638   E->printPretty(S, nullptr, getPrintingPolicy());
11639 
11640   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
11641                               : diag::warn_impcast_pointer_to_bool;
11642   enum {
11643     AddressOf,
11644     FunctionPointer,
11645     ArrayPointer
11646   } DiagType;
11647   if (IsAddressOf)
11648     DiagType = AddressOf;
11649   else if (IsFunction)
11650     DiagType = FunctionPointer;
11651   else if (IsArray)
11652     DiagType = ArrayPointer;
11653   else
11654     llvm_unreachable("Could not determine diagnostic.");
11655   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
11656                                 << Range << IsEqual;
11657 
11658   if (!IsFunction)
11659     return;
11660 
11661   // Suggest '&' to silence the function warning.
11662   Diag(E->getExprLoc(), diag::note_function_warning_silence)
11663       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
11664 
11665   // Check to see if '()' fixit should be emitted.
11666   QualType ReturnType;
11667   UnresolvedSet<4> NonTemplateOverloads;
11668   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
11669   if (ReturnType.isNull())
11670     return;
11671 
11672   if (IsCompare) {
11673     // There are two cases here.  If there is null constant, the only suggest
11674     // for a pointer return type.  If the null is 0, then suggest if the return
11675     // type is a pointer or an integer type.
11676     if (!ReturnType->isPointerType()) {
11677       if (NullKind == Expr::NPCK_ZeroExpression ||
11678           NullKind == Expr::NPCK_ZeroLiteral) {
11679         if (!ReturnType->isIntegerType())
11680           return;
11681       } else {
11682         return;
11683       }
11684     }
11685   } else { // !IsCompare
11686     // For function to bool, only suggest if the function pointer has bool
11687     // return type.
11688     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
11689       return;
11690   }
11691   Diag(E->getExprLoc(), diag::note_function_to_function_call)
11692       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
11693 }
11694 
11695 /// Diagnoses "dangerous" implicit conversions within the given
11696 /// expression (which is a full expression).  Implements -Wconversion
11697 /// and -Wsign-compare.
11698 ///
11699 /// \param CC the "context" location of the implicit conversion, i.e.
11700 ///   the most location of the syntactic entity requiring the implicit
11701 ///   conversion
11702 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
11703   // Don't diagnose in unevaluated contexts.
11704   if (isUnevaluatedContext())
11705     return;
11706 
11707   // Don't diagnose for value- or type-dependent expressions.
11708   if (E->isTypeDependent() || E->isValueDependent())
11709     return;
11710 
11711   // Check for array bounds violations in cases where the check isn't triggered
11712   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
11713   // ArraySubscriptExpr is on the RHS of a variable initialization.
11714   CheckArrayAccess(E);
11715 
11716   // This is not the right CC for (e.g.) a variable initialization.
11717   AnalyzeImplicitConversions(*this, E, CC);
11718 }
11719 
11720 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
11721 /// Input argument E is a logical expression.
11722 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
11723   ::CheckBoolLikeConversion(*this, E, CC);
11724 }
11725 
11726 /// Diagnose when expression is an integer constant expression and its evaluation
11727 /// results in integer overflow
11728 void Sema::CheckForIntOverflow (Expr *E) {
11729   // Use a work list to deal with nested struct initializers.
11730   SmallVector<Expr *, 2> Exprs(1, E);
11731 
11732   do {
11733     Expr *OriginalE = Exprs.pop_back_val();
11734     Expr *E = OriginalE->IgnoreParenCasts();
11735 
11736     if (isa<BinaryOperator>(E)) {
11737       E->EvaluateForOverflow(Context);
11738       continue;
11739     }
11740 
11741     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
11742       Exprs.append(InitList->inits().begin(), InitList->inits().end());
11743     else if (isa<ObjCBoxedExpr>(OriginalE))
11744       E->EvaluateForOverflow(Context);
11745     else if (auto Call = dyn_cast<CallExpr>(E))
11746       Exprs.append(Call->arg_begin(), Call->arg_end());
11747     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
11748       Exprs.append(Message->arg_begin(), Message->arg_end());
11749   } while (!Exprs.empty());
11750 }
11751 
11752 namespace {
11753 
11754 /// Visitor for expressions which looks for unsequenced operations on the
11755 /// same object.
11756 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
11757   using Base = EvaluatedExprVisitor<SequenceChecker>;
11758 
11759   /// A tree of sequenced regions within an expression. Two regions are
11760   /// unsequenced if one is an ancestor or a descendent of the other. When we
11761   /// finish processing an expression with sequencing, such as a comma
11762   /// expression, we fold its tree nodes into its parent, since they are
11763   /// unsequenced with respect to nodes we will visit later.
11764   class SequenceTree {
11765     struct Value {
11766       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
11767       unsigned Parent : 31;
11768       unsigned Merged : 1;
11769     };
11770     SmallVector<Value, 8> Values;
11771 
11772   public:
11773     /// A region within an expression which may be sequenced with respect
11774     /// to some other region.
11775     class Seq {
11776       friend class SequenceTree;
11777 
11778       unsigned Index;
11779 
11780       explicit Seq(unsigned N) : Index(N) {}
11781 
11782     public:
11783       Seq() : Index(0) {}
11784     };
11785 
11786     SequenceTree() { Values.push_back(Value(0)); }
11787     Seq root() const { return Seq(0); }
11788 
11789     /// Create a new sequence of operations, which is an unsequenced
11790     /// subset of \p Parent. This sequence of operations is sequenced with
11791     /// respect to other children of \p Parent.
11792     Seq allocate(Seq Parent) {
11793       Values.push_back(Value(Parent.Index));
11794       return Seq(Values.size() - 1);
11795     }
11796 
11797     /// Merge a sequence of operations into its parent.
11798     void merge(Seq S) {
11799       Values[S.Index].Merged = true;
11800     }
11801 
11802     /// Determine whether two operations are unsequenced. This operation
11803     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
11804     /// should have been merged into its parent as appropriate.
11805     bool isUnsequenced(Seq Cur, Seq Old) {
11806       unsigned C = representative(Cur.Index);
11807       unsigned Target = representative(Old.Index);
11808       while (C >= Target) {
11809         if (C == Target)
11810           return true;
11811         C = Values[C].Parent;
11812       }
11813       return false;
11814     }
11815 
11816   private:
11817     /// Pick a representative for a sequence.
11818     unsigned representative(unsigned K) {
11819       if (Values[K].Merged)
11820         // Perform path compression as we go.
11821         return Values[K].Parent = representative(Values[K].Parent);
11822       return K;
11823     }
11824   };
11825 
11826   /// An object for which we can track unsequenced uses.
11827   using Object = NamedDecl *;
11828 
11829   /// Different flavors of object usage which we track. We only track the
11830   /// least-sequenced usage of each kind.
11831   enum UsageKind {
11832     /// A read of an object. Multiple unsequenced reads are OK.
11833     UK_Use,
11834 
11835     /// A modification of an object which is sequenced before the value
11836     /// computation of the expression, such as ++n in C++.
11837     UK_ModAsValue,
11838 
11839     /// A modification of an object which is not sequenced before the value
11840     /// computation of the expression, such as n++.
11841     UK_ModAsSideEffect,
11842 
11843     UK_Count = UK_ModAsSideEffect + 1
11844   };
11845 
11846   struct Usage {
11847     Expr *Use;
11848     SequenceTree::Seq Seq;
11849 
11850     Usage() : Use(nullptr), Seq() {}
11851   };
11852 
11853   struct UsageInfo {
11854     Usage Uses[UK_Count];
11855 
11856     /// Have we issued a diagnostic for this variable already?
11857     bool Diagnosed;
11858 
11859     UsageInfo() : Uses(), Diagnosed(false) {}
11860   };
11861   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
11862 
11863   Sema &SemaRef;
11864 
11865   /// Sequenced regions within the expression.
11866   SequenceTree Tree;
11867 
11868   /// Declaration modifications and references which we have seen.
11869   UsageInfoMap UsageMap;
11870 
11871   /// The region we are currently within.
11872   SequenceTree::Seq Region;
11873 
11874   /// Filled in with declarations which were modified as a side-effect
11875   /// (that is, post-increment operations).
11876   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
11877 
11878   /// Expressions to check later. We defer checking these to reduce
11879   /// stack usage.
11880   SmallVectorImpl<Expr *> &WorkList;
11881 
11882   /// RAII object wrapping the visitation of a sequenced subexpression of an
11883   /// expression. At the end of this process, the side-effects of the evaluation
11884   /// become sequenced with respect to the value computation of the result, so
11885   /// we downgrade any UK_ModAsSideEffect within the evaluation to
11886   /// UK_ModAsValue.
11887   struct SequencedSubexpression {
11888     SequencedSubexpression(SequenceChecker &Self)
11889       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
11890       Self.ModAsSideEffect = &ModAsSideEffect;
11891     }
11892 
11893     ~SequencedSubexpression() {
11894       for (auto &M : llvm::reverse(ModAsSideEffect)) {
11895         UsageInfo &U = Self.UsageMap[M.first];
11896         auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
11897         Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
11898         SideEffectUsage = M.second;
11899       }
11900       Self.ModAsSideEffect = OldModAsSideEffect;
11901     }
11902 
11903     SequenceChecker &Self;
11904     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
11905     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
11906   };
11907 
11908   /// RAII object wrapping the visitation of a subexpression which we might
11909   /// choose to evaluate as a constant. If any subexpression is evaluated and
11910   /// found to be non-constant, this allows us to suppress the evaluation of
11911   /// the outer expression.
11912   class EvaluationTracker {
11913   public:
11914     EvaluationTracker(SequenceChecker &Self)
11915         : Self(Self), Prev(Self.EvalTracker) {
11916       Self.EvalTracker = this;
11917     }
11918 
11919     ~EvaluationTracker() {
11920       Self.EvalTracker = Prev;
11921       if (Prev)
11922         Prev->EvalOK &= EvalOK;
11923     }
11924 
11925     bool evaluate(const Expr *E, bool &Result) {
11926       if (!EvalOK || E->isValueDependent())
11927         return false;
11928       EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
11929       return EvalOK;
11930     }
11931 
11932   private:
11933     SequenceChecker &Self;
11934     EvaluationTracker *Prev;
11935     bool EvalOK = true;
11936   } *EvalTracker = nullptr;
11937 
11938   /// Find the object which is produced by the specified expression,
11939   /// if any.
11940   Object getObject(Expr *E, bool Mod) const {
11941     E = E->IgnoreParenCasts();
11942     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
11943       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
11944         return getObject(UO->getSubExpr(), Mod);
11945     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11946       if (BO->getOpcode() == BO_Comma)
11947         return getObject(BO->getRHS(), Mod);
11948       if (Mod && BO->isAssignmentOp())
11949         return getObject(BO->getLHS(), Mod);
11950     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
11951       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
11952       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
11953         return ME->getMemberDecl();
11954     } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11955       // FIXME: If this is a reference, map through to its value.
11956       return DRE->getDecl();
11957     return nullptr;
11958   }
11959 
11960   /// Note that an object was modified or used by an expression.
11961   void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
11962     Usage &U = UI.Uses[UK];
11963     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
11964       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
11965         ModAsSideEffect->push_back(std::make_pair(O, U));
11966       U.Use = Ref;
11967       U.Seq = Region;
11968     }
11969   }
11970 
11971   /// Check whether a modification or use conflicts with a prior usage.
11972   void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
11973                   bool IsModMod) {
11974     if (UI.Diagnosed)
11975       return;
11976 
11977     const Usage &U = UI.Uses[OtherKind];
11978     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
11979       return;
11980 
11981     Expr *Mod = U.Use;
11982     Expr *ModOrUse = Ref;
11983     if (OtherKind == UK_Use)
11984       std::swap(Mod, ModOrUse);
11985 
11986     SemaRef.Diag(Mod->getExprLoc(),
11987                  IsModMod ? diag::warn_unsequenced_mod_mod
11988                           : diag::warn_unsequenced_mod_use)
11989       << O << SourceRange(ModOrUse->getExprLoc());
11990     UI.Diagnosed = true;
11991   }
11992 
11993   void notePreUse(Object O, Expr *Use) {
11994     UsageInfo &U = UsageMap[O];
11995     // Uses conflict with other modifications.
11996     checkUsage(O, U, Use, UK_ModAsValue, false);
11997   }
11998 
11999   void notePostUse(Object O, Expr *Use) {
12000     UsageInfo &U = UsageMap[O];
12001     checkUsage(O, U, Use, UK_ModAsSideEffect, false);
12002     addUsage(U, O, Use, UK_Use);
12003   }
12004 
12005   void notePreMod(Object O, Expr *Mod) {
12006     UsageInfo &U = UsageMap[O];
12007     // Modifications conflict with other modifications and with uses.
12008     checkUsage(O, U, Mod, UK_ModAsValue, true);
12009     checkUsage(O, U, Mod, UK_Use, false);
12010   }
12011 
12012   void notePostMod(Object O, Expr *Use, UsageKind UK) {
12013     UsageInfo &U = UsageMap[O];
12014     checkUsage(O, U, Use, UK_ModAsSideEffect, true);
12015     addUsage(U, O, Use, UK);
12016   }
12017 
12018 public:
12019   SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
12020       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
12021     Visit(E);
12022   }
12023 
12024   void VisitStmt(Stmt *S) {
12025     // Skip all statements which aren't expressions for now.
12026   }
12027 
12028   void VisitExpr(Expr *E) {
12029     // By default, just recurse to evaluated subexpressions.
12030     Base::VisitStmt(E);
12031   }
12032 
12033   void VisitCastExpr(CastExpr *E) {
12034     Object O = Object();
12035     if (E->getCastKind() == CK_LValueToRValue)
12036       O = getObject(E->getSubExpr(), false);
12037 
12038     if (O)
12039       notePreUse(O, E);
12040     VisitExpr(E);
12041     if (O)
12042       notePostUse(O, E);
12043   }
12044 
12045   void VisitSequencedExpressions(Expr *SequencedBefore, Expr *SequencedAfter) {
12046     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
12047     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
12048     SequenceTree::Seq OldRegion = Region;
12049 
12050     {
12051       SequencedSubexpression SeqBefore(*this);
12052       Region = BeforeRegion;
12053       Visit(SequencedBefore);
12054     }
12055 
12056     Region = AfterRegion;
12057     Visit(SequencedAfter);
12058 
12059     Region = OldRegion;
12060 
12061     Tree.merge(BeforeRegion);
12062     Tree.merge(AfterRegion);
12063   }
12064 
12065   void VisitArraySubscriptExpr(ArraySubscriptExpr *ASE) {
12066     // C++17 [expr.sub]p1:
12067     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
12068     //   expression E1 is sequenced before the expression E2.
12069     if (SemaRef.getLangOpts().CPlusPlus17)
12070       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
12071     else
12072       Base::VisitStmt(ASE);
12073   }
12074 
12075   void VisitBinComma(BinaryOperator *BO) {
12076     // C++11 [expr.comma]p1:
12077     //   Every value computation and side effect associated with the left
12078     //   expression is sequenced before every value computation and side
12079     //   effect associated with the right expression.
12080     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12081   }
12082 
12083   void VisitBinAssign(BinaryOperator *BO) {
12084     // The modification is sequenced after the value computation of the LHS
12085     // and RHS, so check it before inspecting the operands and update the
12086     // map afterwards.
12087     Object O = getObject(BO->getLHS(), true);
12088     if (!O)
12089       return VisitExpr(BO);
12090 
12091     notePreMod(O, BO);
12092 
12093     // C++11 [expr.ass]p7:
12094     //   E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
12095     //   only once.
12096     //
12097     // Therefore, for a compound assignment operator, O is considered used
12098     // everywhere except within the evaluation of E1 itself.
12099     if (isa<CompoundAssignOperator>(BO))
12100       notePreUse(O, BO);
12101 
12102     Visit(BO->getLHS());
12103 
12104     if (isa<CompoundAssignOperator>(BO))
12105       notePostUse(O, BO);
12106 
12107     Visit(BO->getRHS());
12108 
12109     // C++11 [expr.ass]p1:
12110     //   the assignment is sequenced [...] before the value computation of the
12111     //   assignment expression.
12112     // C11 6.5.16/3 has no such rule.
12113     notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12114                                                        : UK_ModAsSideEffect);
12115   }
12116 
12117   void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
12118     VisitBinAssign(CAO);
12119   }
12120 
12121   void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12122   void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12123   void VisitUnaryPreIncDec(UnaryOperator *UO) {
12124     Object O = getObject(UO->getSubExpr(), true);
12125     if (!O)
12126       return VisitExpr(UO);
12127 
12128     notePreMod(O, UO);
12129     Visit(UO->getSubExpr());
12130     // C++11 [expr.pre.incr]p1:
12131     //   the expression ++x is equivalent to x+=1
12132     notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12133                                                        : UK_ModAsSideEffect);
12134   }
12135 
12136   void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12137   void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12138   void VisitUnaryPostIncDec(UnaryOperator *UO) {
12139     Object O = getObject(UO->getSubExpr(), true);
12140     if (!O)
12141       return VisitExpr(UO);
12142 
12143     notePreMod(O, UO);
12144     Visit(UO->getSubExpr());
12145     notePostMod(O, UO, UK_ModAsSideEffect);
12146   }
12147 
12148   /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
12149   void VisitBinLOr(BinaryOperator *BO) {
12150     // The side-effects of the LHS of an '&&' are sequenced before the
12151     // value computation of the RHS, and hence before the value computation
12152     // of the '&&' itself, unless the LHS evaluates to zero. We treat them
12153     // as if they were unconditionally sequenced.
12154     EvaluationTracker Eval(*this);
12155     {
12156       SequencedSubexpression Sequenced(*this);
12157       Visit(BO->getLHS());
12158     }
12159 
12160     bool Result;
12161     if (Eval.evaluate(BO->getLHS(), Result)) {
12162       if (!Result)
12163         Visit(BO->getRHS());
12164     } else {
12165       // Check for unsequenced operations in the RHS, treating it as an
12166       // entirely separate evaluation.
12167       //
12168       // FIXME: If there are operations in the RHS which are unsequenced
12169       // with respect to operations outside the RHS, and those operations
12170       // are unconditionally evaluated, diagnose them.
12171       WorkList.push_back(BO->getRHS());
12172     }
12173   }
12174   void VisitBinLAnd(BinaryOperator *BO) {
12175     EvaluationTracker Eval(*this);
12176     {
12177       SequencedSubexpression Sequenced(*this);
12178       Visit(BO->getLHS());
12179     }
12180 
12181     bool Result;
12182     if (Eval.evaluate(BO->getLHS(), Result)) {
12183       if (Result)
12184         Visit(BO->getRHS());
12185     } else {
12186       WorkList.push_back(BO->getRHS());
12187     }
12188   }
12189 
12190   // Only visit the condition, unless we can be sure which subexpression will
12191   // be chosen.
12192   void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
12193     EvaluationTracker Eval(*this);
12194     {
12195       SequencedSubexpression Sequenced(*this);
12196       Visit(CO->getCond());
12197     }
12198 
12199     bool Result;
12200     if (Eval.evaluate(CO->getCond(), Result))
12201       Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
12202     else {
12203       WorkList.push_back(CO->getTrueExpr());
12204       WorkList.push_back(CO->getFalseExpr());
12205     }
12206   }
12207 
12208   void VisitCallExpr(CallExpr *CE) {
12209     // C++11 [intro.execution]p15:
12210     //   When calling a function [...], every value computation and side effect
12211     //   associated with any argument expression, or with the postfix expression
12212     //   designating the called function, is sequenced before execution of every
12213     //   expression or statement in the body of the function [and thus before
12214     //   the value computation of its result].
12215     SequencedSubexpression Sequenced(*this);
12216     Base::VisitCallExpr(CE);
12217 
12218     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
12219   }
12220 
12221   void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
12222     // This is a call, so all subexpressions are sequenced before the result.
12223     SequencedSubexpression Sequenced(*this);
12224 
12225     if (!CCE->isListInitialization())
12226       return VisitExpr(CCE);
12227 
12228     // In C++11, list initializations are sequenced.
12229     SmallVector<SequenceTree::Seq, 32> Elts;
12230     SequenceTree::Seq Parent = Region;
12231     for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
12232                                         E = CCE->arg_end();
12233          I != E; ++I) {
12234       Region = Tree.allocate(Parent);
12235       Elts.push_back(Region);
12236       Visit(*I);
12237     }
12238 
12239     // Forget that the initializers are sequenced.
12240     Region = Parent;
12241     for (unsigned I = 0; I < Elts.size(); ++I)
12242       Tree.merge(Elts[I]);
12243   }
12244 
12245   void VisitInitListExpr(InitListExpr *ILE) {
12246     if (!SemaRef.getLangOpts().CPlusPlus11)
12247       return VisitExpr(ILE);
12248 
12249     // In C++11, list initializations are sequenced.
12250     SmallVector<SequenceTree::Seq, 32> Elts;
12251     SequenceTree::Seq Parent = Region;
12252     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
12253       Expr *E = ILE->getInit(I);
12254       if (!E) continue;
12255       Region = Tree.allocate(Parent);
12256       Elts.push_back(Region);
12257       Visit(E);
12258     }
12259 
12260     // Forget that the initializers are sequenced.
12261     Region = Parent;
12262     for (unsigned I = 0; I < Elts.size(); ++I)
12263       Tree.merge(Elts[I]);
12264   }
12265 };
12266 
12267 } // namespace
12268 
12269 void Sema::CheckUnsequencedOperations(Expr *E) {
12270   SmallVector<Expr *, 8> WorkList;
12271   WorkList.push_back(E);
12272   while (!WorkList.empty()) {
12273     Expr *Item = WorkList.pop_back_val();
12274     SequenceChecker(*this, Item, WorkList);
12275   }
12276 }
12277 
12278 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
12279                               bool IsConstexpr) {
12280   CheckImplicitConversions(E, CheckLoc);
12281   if (!E->isInstantiationDependent())
12282     CheckUnsequencedOperations(E);
12283   if (!IsConstexpr && !E->isValueDependent())
12284     CheckForIntOverflow(E);
12285   DiagnoseMisalignedMembers();
12286 }
12287 
12288 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
12289                                        FieldDecl *BitField,
12290                                        Expr *Init) {
12291   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
12292 }
12293 
12294 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
12295                                          SourceLocation Loc) {
12296   if (!PType->isVariablyModifiedType())
12297     return;
12298   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
12299     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
12300     return;
12301   }
12302   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
12303     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
12304     return;
12305   }
12306   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
12307     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
12308     return;
12309   }
12310 
12311   const ArrayType *AT = S.Context.getAsArrayType(PType);
12312   if (!AT)
12313     return;
12314 
12315   if (AT->getSizeModifier() != ArrayType::Star) {
12316     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
12317     return;
12318   }
12319 
12320   S.Diag(Loc, diag::err_array_star_in_function_definition);
12321 }
12322 
12323 /// CheckParmsForFunctionDef - Check that the parameters of the given
12324 /// function are appropriate for the definition of a function. This
12325 /// takes care of any checks that cannot be performed on the
12326 /// declaration itself, e.g., that the types of each of the function
12327 /// parameters are complete.
12328 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
12329                                     bool CheckParameterNames) {
12330   bool HasInvalidParm = false;
12331   for (ParmVarDecl *Param : Parameters) {
12332     // C99 6.7.5.3p4: the parameters in a parameter type list in a
12333     // function declarator that is part of a function definition of
12334     // that function shall not have incomplete type.
12335     //
12336     // This is also C++ [dcl.fct]p6.
12337     if (!Param->isInvalidDecl() &&
12338         RequireCompleteType(Param->getLocation(), Param->getType(),
12339                             diag::err_typecheck_decl_incomplete_type)) {
12340       Param->setInvalidDecl();
12341       HasInvalidParm = true;
12342     }
12343 
12344     // C99 6.9.1p5: If the declarator includes a parameter type list, the
12345     // declaration of each parameter shall include an identifier.
12346     if (CheckParameterNames &&
12347         Param->getIdentifier() == nullptr &&
12348         !Param->isImplicit() &&
12349         !getLangOpts().CPlusPlus)
12350       Diag(Param->getLocation(), diag::err_parameter_name_omitted);
12351 
12352     // C99 6.7.5.3p12:
12353     //   If the function declarator is not part of a definition of that
12354     //   function, parameters may have incomplete type and may use the [*]
12355     //   notation in their sequences of declarator specifiers to specify
12356     //   variable length array types.
12357     QualType PType = Param->getOriginalType();
12358     // FIXME: This diagnostic should point the '[*]' if source-location
12359     // information is added for it.
12360     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
12361 
12362     // If the parameter is a c++ class type and it has to be destructed in the
12363     // callee function, declare the destructor so that it can be called by the
12364     // callee function. Do not perform any direct access check on the dtor here.
12365     if (!Param->isInvalidDecl()) {
12366       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
12367         if (!ClassDecl->isInvalidDecl() &&
12368             !ClassDecl->hasIrrelevantDestructor() &&
12369             !ClassDecl->isDependentContext() &&
12370             ClassDecl->isParamDestroyedInCallee()) {
12371           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
12372           MarkFunctionReferenced(Param->getLocation(), Destructor);
12373           DiagnoseUseOfDecl(Destructor, Param->getLocation());
12374         }
12375       }
12376     }
12377 
12378     // Parameters with the pass_object_size attribute only need to be marked
12379     // constant at function definitions. Because we lack information about
12380     // whether we're on a declaration or definition when we're instantiating the
12381     // attribute, we need to check for constness here.
12382     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
12383       if (!Param->getType().isConstQualified())
12384         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
12385             << Attr->getSpelling() << 1;
12386 
12387     // Check for parameter names shadowing fields from the class.
12388     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
12389       // The owning context for the parameter should be the function, but we
12390       // want to see if this function's declaration context is a record.
12391       DeclContext *DC = Param->getDeclContext();
12392       if (DC && DC->isFunctionOrMethod()) {
12393         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
12394           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
12395                                      RD, /*DeclIsField*/ false);
12396       }
12397     }
12398   }
12399 
12400   return HasInvalidParm;
12401 }
12402 
12403 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
12404 /// or MemberExpr.
12405 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
12406                               ASTContext &Context) {
12407   if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
12408     return Context.getDeclAlign(DRE->getDecl());
12409 
12410   if (const auto *ME = dyn_cast<MemberExpr>(E))
12411     return Context.getDeclAlign(ME->getMemberDecl());
12412 
12413   return TypeAlign;
12414 }
12415 
12416 /// CheckCastAlign - Implements -Wcast-align, which warns when a
12417 /// pointer cast increases the alignment requirements.
12418 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
12419   // This is actually a lot of work to potentially be doing on every
12420   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
12421   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
12422     return;
12423 
12424   // Ignore dependent types.
12425   if (T->isDependentType() || Op->getType()->isDependentType())
12426     return;
12427 
12428   // Require that the destination be a pointer type.
12429   const PointerType *DestPtr = T->getAs<PointerType>();
12430   if (!DestPtr) return;
12431 
12432   // If the destination has alignment 1, we're done.
12433   QualType DestPointee = DestPtr->getPointeeType();
12434   if (DestPointee->isIncompleteType()) return;
12435   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
12436   if (DestAlign.isOne()) return;
12437 
12438   // Require that the source be a pointer type.
12439   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
12440   if (!SrcPtr) return;
12441   QualType SrcPointee = SrcPtr->getPointeeType();
12442 
12443   // Whitelist casts from cv void*.  We already implicitly
12444   // whitelisted casts to cv void*, since they have alignment 1.
12445   // Also whitelist casts involving incomplete types, which implicitly
12446   // includes 'void'.
12447   if (SrcPointee->isIncompleteType()) return;
12448 
12449   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
12450 
12451   if (auto *CE = dyn_cast<CastExpr>(Op)) {
12452     if (CE->getCastKind() == CK_ArrayToPointerDecay)
12453       SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
12454   } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
12455     if (UO->getOpcode() == UO_AddrOf)
12456       SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
12457   }
12458 
12459   if (SrcAlign >= DestAlign) return;
12460 
12461   Diag(TRange.getBegin(), diag::warn_cast_align)
12462     << Op->getType() << T
12463     << static_cast<unsigned>(SrcAlign.getQuantity())
12464     << static_cast<unsigned>(DestAlign.getQuantity())
12465     << TRange << Op->getSourceRange();
12466 }
12467 
12468 /// Check whether this array fits the idiom of a size-one tail padded
12469 /// array member of a struct.
12470 ///
12471 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
12472 /// commonly used to emulate flexible arrays in C89 code.
12473 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
12474                                     const NamedDecl *ND) {
12475   if (Size != 1 || !ND) return false;
12476 
12477   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
12478   if (!FD) return false;
12479 
12480   // Don't consider sizes resulting from macro expansions or template argument
12481   // substitution to form C89 tail-padded arrays.
12482 
12483   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
12484   while (TInfo) {
12485     TypeLoc TL = TInfo->getTypeLoc();
12486     // Look through typedefs.
12487     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
12488       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
12489       TInfo = TDL->getTypeSourceInfo();
12490       continue;
12491     }
12492     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
12493       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
12494       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
12495         return false;
12496     }
12497     break;
12498   }
12499 
12500   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
12501   if (!RD) return false;
12502   if (RD->isUnion()) return false;
12503   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
12504     if (!CRD->isStandardLayout()) return false;
12505   }
12506 
12507   // See if this is the last field decl in the record.
12508   const Decl *D = FD;
12509   while ((D = D->getNextDeclInContext()))
12510     if (isa<FieldDecl>(D))
12511       return false;
12512   return true;
12513 }
12514 
12515 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
12516                             const ArraySubscriptExpr *ASE,
12517                             bool AllowOnePastEnd, bool IndexNegated) {
12518   IndexExpr = IndexExpr->IgnoreParenImpCasts();
12519   if (IndexExpr->isValueDependent())
12520     return;
12521 
12522   const Type *EffectiveType =
12523       BaseExpr->getType()->getPointeeOrArrayElementType();
12524   BaseExpr = BaseExpr->IgnoreParenCasts();
12525   const ConstantArrayType *ArrayTy =
12526       Context.getAsConstantArrayType(BaseExpr->getType());
12527 
12528   if (!ArrayTy)
12529     return;
12530 
12531   const Type *BaseType = ArrayTy->getElementType().getTypePtr();
12532   if (EffectiveType->isDependentType() || BaseType->isDependentType())
12533     return;
12534 
12535   Expr::EvalResult Result;
12536   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
12537     return;
12538 
12539   llvm::APSInt index = Result.Val.getInt();
12540   if (IndexNegated)
12541     index = -index;
12542 
12543   const NamedDecl *ND = nullptr;
12544   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
12545     ND = DRE->getDecl();
12546   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
12547     ND = ME->getMemberDecl();
12548 
12549   if (index.isUnsigned() || !index.isNegative()) {
12550     // It is possible that the type of the base expression after
12551     // IgnoreParenCasts is incomplete, even though the type of the base
12552     // expression before IgnoreParenCasts is complete (see PR39746 for an
12553     // example). In this case we have no information about whether the array
12554     // access exceeds the array bounds. However we can still diagnose an array
12555     // access which precedes the array bounds.
12556     if (BaseType->isIncompleteType())
12557       return;
12558 
12559     llvm::APInt size = ArrayTy->getSize();
12560     if (!size.isStrictlyPositive())
12561       return;
12562 
12563     if (BaseType != EffectiveType) {
12564       // Make sure we're comparing apples to apples when comparing index to size
12565       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
12566       uint64_t array_typesize = Context.getTypeSize(BaseType);
12567       // Handle ptrarith_typesize being zero, such as when casting to void*
12568       if (!ptrarith_typesize) ptrarith_typesize = 1;
12569       if (ptrarith_typesize != array_typesize) {
12570         // There's a cast to a different size type involved
12571         uint64_t ratio = array_typesize / ptrarith_typesize;
12572         // TODO: Be smarter about handling cases where array_typesize is not a
12573         // multiple of ptrarith_typesize
12574         if (ptrarith_typesize * ratio == array_typesize)
12575           size *= llvm::APInt(size.getBitWidth(), ratio);
12576       }
12577     }
12578 
12579     if (size.getBitWidth() > index.getBitWidth())
12580       index = index.zext(size.getBitWidth());
12581     else if (size.getBitWidth() < index.getBitWidth())
12582       size = size.zext(index.getBitWidth());
12583 
12584     // For array subscripting the index must be less than size, but for pointer
12585     // arithmetic also allow the index (offset) to be equal to size since
12586     // computing the next address after the end of the array is legal and
12587     // commonly done e.g. in C++ iterators and range-based for loops.
12588     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
12589       return;
12590 
12591     // Also don't warn for arrays of size 1 which are members of some
12592     // structure. These are often used to approximate flexible arrays in C89
12593     // code.
12594     if (IsTailPaddedMemberArray(*this, size, ND))
12595       return;
12596 
12597     // Suppress the warning if the subscript expression (as identified by the
12598     // ']' location) and the index expression are both from macro expansions
12599     // within a system header.
12600     if (ASE) {
12601       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
12602           ASE->getRBracketLoc());
12603       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
12604         SourceLocation IndexLoc =
12605             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
12606         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
12607           return;
12608       }
12609     }
12610 
12611     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
12612     if (ASE)
12613       DiagID = diag::warn_array_index_exceeds_bounds;
12614 
12615     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
12616                         PDiag(DiagID) << index.toString(10, true)
12617                                       << size.toString(10, true)
12618                                       << (unsigned)size.getLimitedValue(~0U)
12619                                       << IndexExpr->getSourceRange());
12620   } else {
12621     unsigned DiagID = diag::warn_array_index_precedes_bounds;
12622     if (!ASE) {
12623       DiagID = diag::warn_ptr_arith_precedes_bounds;
12624       if (index.isNegative()) index = -index;
12625     }
12626 
12627     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
12628                         PDiag(DiagID) << index.toString(10, true)
12629                                       << IndexExpr->getSourceRange());
12630   }
12631 
12632   if (!ND) {
12633     // Try harder to find a NamedDecl to point at in the note.
12634     while (const ArraySubscriptExpr *ASE =
12635            dyn_cast<ArraySubscriptExpr>(BaseExpr))
12636       BaseExpr = ASE->getBase()->IgnoreParenCasts();
12637     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
12638       ND = DRE->getDecl();
12639     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
12640       ND = ME->getMemberDecl();
12641   }
12642 
12643   if (ND)
12644     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
12645                         PDiag(diag::note_array_index_out_of_bounds)
12646                             << ND->getDeclName());
12647 }
12648 
12649 void Sema::CheckArrayAccess(const Expr *expr) {
12650   int AllowOnePastEnd = 0;
12651   while (expr) {
12652     expr = expr->IgnoreParenImpCasts();
12653     switch (expr->getStmtClass()) {
12654       case Stmt::ArraySubscriptExprClass: {
12655         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
12656         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
12657                          AllowOnePastEnd > 0);
12658         expr = ASE->getBase();
12659         break;
12660       }
12661       case Stmt::MemberExprClass: {
12662         expr = cast<MemberExpr>(expr)->getBase();
12663         break;
12664       }
12665       case Stmt::OMPArraySectionExprClass: {
12666         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
12667         if (ASE->getLowerBound())
12668           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
12669                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
12670         return;
12671       }
12672       case Stmt::UnaryOperatorClass: {
12673         // Only unwrap the * and & unary operators
12674         const UnaryOperator *UO = cast<UnaryOperator>(expr);
12675         expr = UO->getSubExpr();
12676         switch (UO->getOpcode()) {
12677           case UO_AddrOf:
12678             AllowOnePastEnd++;
12679             break;
12680           case UO_Deref:
12681             AllowOnePastEnd--;
12682             break;
12683           default:
12684             return;
12685         }
12686         break;
12687       }
12688       case Stmt::ConditionalOperatorClass: {
12689         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
12690         if (const Expr *lhs = cond->getLHS())
12691           CheckArrayAccess(lhs);
12692         if (const Expr *rhs = cond->getRHS())
12693           CheckArrayAccess(rhs);
12694         return;
12695       }
12696       case Stmt::CXXOperatorCallExprClass: {
12697         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
12698         for (const auto *Arg : OCE->arguments())
12699           CheckArrayAccess(Arg);
12700         return;
12701       }
12702       default:
12703         return;
12704     }
12705   }
12706 }
12707 
12708 //===--- CHECK: Objective-C retain cycles ----------------------------------//
12709 
12710 namespace {
12711 
12712 struct RetainCycleOwner {
12713   VarDecl *Variable = nullptr;
12714   SourceRange Range;
12715   SourceLocation Loc;
12716   bool Indirect = false;
12717 
12718   RetainCycleOwner() = default;
12719 
12720   void setLocsFrom(Expr *e) {
12721     Loc = e->getExprLoc();
12722     Range = e->getSourceRange();
12723   }
12724 };
12725 
12726 } // namespace
12727 
12728 /// Consider whether capturing the given variable can possibly lead to
12729 /// a retain cycle.
12730 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
12731   // In ARC, it's captured strongly iff the variable has __strong
12732   // lifetime.  In MRR, it's captured strongly if the variable is
12733   // __block and has an appropriate type.
12734   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
12735     return false;
12736 
12737   owner.Variable = var;
12738   if (ref)
12739     owner.setLocsFrom(ref);
12740   return true;
12741 }
12742 
12743 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
12744   while (true) {
12745     e = e->IgnoreParens();
12746     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
12747       switch (cast->getCastKind()) {
12748       case CK_BitCast:
12749       case CK_LValueBitCast:
12750       case CK_LValueToRValue:
12751       case CK_ARCReclaimReturnedObject:
12752         e = cast->getSubExpr();
12753         continue;
12754 
12755       default:
12756         return false;
12757       }
12758     }
12759 
12760     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
12761       ObjCIvarDecl *ivar = ref->getDecl();
12762       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
12763         return false;
12764 
12765       // Try to find a retain cycle in the base.
12766       if (!findRetainCycleOwner(S, ref->getBase(), owner))
12767         return false;
12768 
12769       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
12770       owner.Indirect = true;
12771       return true;
12772     }
12773 
12774     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
12775       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
12776       if (!var) return false;
12777       return considerVariable(var, ref, owner);
12778     }
12779 
12780     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
12781       if (member->isArrow()) return false;
12782 
12783       // Don't count this as an indirect ownership.
12784       e = member->getBase();
12785       continue;
12786     }
12787 
12788     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
12789       // Only pay attention to pseudo-objects on property references.
12790       ObjCPropertyRefExpr *pre
12791         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
12792                                               ->IgnoreParens());
12793       if (!pre) return false;
12794       if (pre->isImplicitProperty()) return false;
12795       ObjCPropertyDecl *property = pre->getExplicitProperty();
12796       if (!property->isRetaining() &&
12797           !(property->getPropertyIvarDecl() &&
12798             property->getPropertyIvarDecl()->getType()
12799               .getObjCLifetime() == Qualifiers::OCL_Strong))
12800           return false;
12801 
12802       owner.Indirect = true;
12803       if (pre->isSuperReceiver()) {
12804         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
12805         if (!owner.Variable)
12806           return false;
12807         owner.Loc = pre->getLocation();
12808         owner.Range = pre->getSourceRange();
12809         return true;
12810       }
12811       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
12812                               ->getSourceExpr());
12813       continue;
12814     }
12815 
12816     // Array ivars?
12817 
12818     return false;
12819   }
12820 }
12821 
12822 namespace {
12823 
12824   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
12825     ASTContext &Context;
12826     VarDecl *Variable;
12827     Expr *Capturer = nullptr;
12828     bool VarWillBeReased = false;
12829 
12830     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
12831         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
12832           Context(Context), Variable(variable) {}
12833 
12834     void VisitDeclRefExpr(DeclRefExpr *ref) {
12835       if (ref->getDecl() == Variable && !Capturer)
12836         Capturer = ref;
12837     }
12838 
12839     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
12840       if (Capturer) return;
12841       Visit(ref->getBase());
12842       if (Capturer && ref->isFreeIvar())
12843         Capturer = ref;
12844     }
12845 
12846     void VisitBlockExpr(BlockExpr *block) {
12847       // Look inside nested blocks
12848       if (block->getBlockDecl()->capturesVariable(Variable))
12849         Visit(block->getBlockDecl()->getBody());
12850     }
12851 
12852     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
12853       if (Capturer) return;
12854       if (OVE->getSourceExpr())
12855         Visit(OVE->getSourceExpr());
12856     }
12857 
12858     void VisitBinaryOperator(BinaryOperator *BinOp) {
12859       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
12860         return;
12861       Expr *LHS = BinOp->getLHS();
12862       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
12863         if (DRE->getDecl() != Variable)
12864           return;
12865         if (Expr *RHS = BinOp->getRHS()) {
12866           RHS = RHS->IgnoreParenCasts();
12867           llvm::APSInt Value;
12868           VarWillBeReased =
12869             (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
12870         }
12871       }
12872     }
12873   };
12874 
12875 } // namespace
12876 
12877 /// Check whether the given argument is a block which captures a
12878 /// variable.
12879 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
12880   assert(owner.Variable && owner.Loc.isValid());
12881 
12882   e = e->IgnoreParenCasts();
12883 
12884   // Look through [^{...} copy] and Block_copy(^{...}).
12885   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
12886     Selector Cmd = ME->getSelector();
12887     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
12888       e = ME->getInstanceReceiver();
12889       if (!e)
12890         return nullptr;
12891       e = e->IgnoreParenCasts();
12892     }
12893   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
12894     if (CE->getNumArgs() == 1) {
12895       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
12896       if (Fn) {
12897         const IdentifierInfo *FnI = Fn->getIdentifier();
12898         if (FnI && FnI->isStr("_Block_copy")) {
12899           e = CE->getArg(0)->IgnoreParenCasts();
12900         }
12901       }
12902     }
12903   }
12904 
12905   BlockExpr *block = dyn_cast<BlockExpr>(e);
12906   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
12907     return nullptr;
12908 
12909   FindCaptureVisitor visitor(S.Context, owner.Variable);
12910   visitor.Visit(block->getBlockDecl()->getBody());
12911   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
12912 }
12913 
12914 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
12915                                 RetainCycleOwner &owner) {
12916   assert(capturer);
12917   assert(owner.Variable && owner.Loc.isValid());
12918 
12919   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
12920     << owner.Variable << capturer->getSourceRange();
12921   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
12922     << owner.Indirect << owner.Range;
12923 }
12924 
12925 /// Check for a keyword selector that starts with the word 'add' or
12926 /// 'set'.
12927 static bool isSetterLikeSelector(Selector sel) {
12928   if (sel.isUnarySelector()) return false;
12929 
12930   StringRef str = sel.getNameForSlot(0);
12931   while (!str.empty() && str.front() == '_') str = str.substr(1);
12932   if (str.startswith("set"))
12933     str = str.substr(3);
12934   else if (str.startswith("add")) {
12935     // Specially whitelist 'addOperationWithBlock:'.
12936     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
12937       return false;
12938     str = str.substr(3);
12939   }
12940   else
12941     return false;
12942 
12943   if (str.empty()) return true;
12944   return !isLowercase(str.front());
12945 }
12946 
12947 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
12948                                                     ObjCMessageExpr *Message) {
12949   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
12950                                                 Message->getReceiverInterface(),
12951                                                 NSAPI::ClassId_NSMutableArray);
12952   if (!IsMutableArray) {
12953     return None;
12954   }
12955 
12956   Selector Sel = Message->getSelector();
12957 
12958   Optional<NSAPI::NSArrayMethodKind> MKOpt =
12959     S.NSAPIObj->getNSArrayMethodKind(Sel);
12960   if (!MKOpt) {
12961     return None;
12962   }
12963 
12964   NSAPI::NSArrayMethodKind MK = *MKOpt;
12965 
12966   switch (MK) {
12967     case NSAPI::NSMutableArr_addObject:
12968     case NSAPI::NSMutableArr_insertObjectAtIndex:
12969     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
12970       return 0;
12971     case NSAPI::NSMutableArr_replaceObjectAtIndex:
12972       return 1;
12973 
12974     default:
12975       return None;
12976   }
12977 
12978   return None;
12979 }
12980 
12981 static
12982 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
12983                                                   ObjCMessageExpr *Message) {
12984   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
12985                                             Message->getReceiverInterface(),
12986                                             NSAPI::ClassId_NSMutableDictionary);
12987   if (!IsMutableDictionary) {
12988     return None;
12989   }
12990 
12991   Selector Sel = Message->getSelector();
12992 
12993   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
12994     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
12995   if (!MKOpt) {
12996     return None;
12997   }
12998 
12999   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
13000 
13001   switch (MK) {
13002     case NSAPI::NSMutableDict_setObjectForKey:
13003     case NSAPI::NSMutableDict_setValueForKey:
13004     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
13005       return 0;
13006 
13007     default:
13008       return None;
13009   }
13010 
13011   return None;
13012 }
13013 
13014 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
13015   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
13016                                                 Message->getReceiverInterface(),
13017                                                 NSAPI::ClassId_NSMutableSet);
13018 
13019   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
13020                                             Message->getReceiverInterface(),
13021                                             NSAPI::ClassId_NSMutableOrderedSet);
13022   if (!IsMutableSet && !IsMutableOrderedSet) {
13023     return None;
13024   }
13025 
13026   Selector Sel = Message->getSelector();
13027 
13028   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
13029   if (!MKOpt) {
13030     return None;
13031   }
13032 
13033   NSAPI::NSSetMethodKind MK = *MKOpt;
13034 
13035   switch (MK) {
13036     case NSAPI::NSMutableSet_addObject:
13037     case NSAPI::NSOrderedSet_setObjectAtIndex:
13038     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
13039     case NSAPI::NSOrderedSet_insertObjectAtIndex:
13040       return 0;
13041     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
13042       return 1;
13043   }
13044 
13045   return None;
13046 }
13047 
13048 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
13049   if (!Message->isInstanceMessage()) {
13050     return;
13051   }
13052 
13053   Optional<int> ArgOpt;
13054 
13055   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
13056       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
13057       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
13058     return;
13059   }
13060 
13061   int ArgIndex = *ArgOpt;
13062 
13063   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
13064   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
13065     Arg = OE->getSourceExpr()->IgnoreImpCasts();
13066   }
13067 
13068   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
13069     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
13070       if (ArgRE->isObjCSelfExpr()) {
13071         Diag(Message->getSourceRange().getBegin(),
13072              diag::warn_objc_circular_container)
13073           << ArgRE->getDecl() << StringRef("'super'");
13074       }
13075     }
13076   } else {
13077     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
13078 
13079     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
13080       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
13081     }
13082 
13083     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
13084       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
13085         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
13086           ValueDecl *Decl = ReceiverRE->getDecl();
13087           Diag(Message->getSourceRange().getBegin(),
13088                diag::warn_objc_circular_container)
13089             << Decl << Decl;
13090           if (!ArgRE->isObjCSelfExpr()) {
13091             Diag(Decl->getLocation(),
13092                  diag::note_objc_circular_container_declared_here)
13093               << Decl;
13094           }
13095         }
13096       }
13097     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
13098       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
13099         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
13100           ObjCIvarDecl *Decl = IvarRE->getDecl();
13101           Diag(Message->getSourceRange().getBegin(),
13102                diag::warn_objc_circular_container)
13103             << Decl << Decl;
13104           Diag(Decl->getLocation(),
13105                diag::note_objc_circular_container_declared_here)
13106             << Decl;
13107         }
13108       }
13109     }
13110   }
13111 }
13112 
13113 /// Check a message send to see if it's likely to cause a retain cycle.
13114 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
13115   // Only check instance methods whose selector looks like a setter.
13116   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
13117     return;
13118 
13119   // Try to find a variable that the receiver is strongly owned by.
13120   RetainCycleOwner owner;
13121   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
13122     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
13123       return;
13124   } else {
13125     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
13126     owner.Variable = getCurMethodDecl()->getSelfDecl();
13127     owner.Loc = msg->getSuperLoc();
13128     owner.Range = msg->getSuperLoc();
13129   }
13130 
13131   // Check whether the receiver is captured by any of the arguments.
13132   const ObjCMethodDecl *MD = msg->getMethodDecl();
13133   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
13134     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
13135       // noescape blocks should not be retained by the method.
13136       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
13137         continue;
13138       return diagnoseRetainCycle(*this, capturer, owner);
13139     }
13140   }
13141 }
13142 
13143 /// Check a property assign to see if it's likely to cause a retain cycle.
13144 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
13145   RetainCycleOwner owner;
13146   if (!findRetainCycleOwner(*this, receiver, owner))
13147     return;
13148 
13149   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
13150     diagnoseRetainCycle(*this, capturer, owner);
13151 }
13152 
13153 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
13154   RetainCycleOwner Owner;
13155   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
13156     return;
13157 
13158   // Because we don't have an expression for the variable, we have to set the
13159   // location explicitly here.
13160   Owner.Loc = Var->getLocation();
13161   Owner.Range = Var->getSourceRange();
13162 
13163   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
13164     diagnoseRetainCycle(*this, Capturer, Owner);
13165 }
13166 
13167 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
13168                                      Expr *RHS, bool isProperty) {
13169   // Check if RHS is an Objective-C object literal, which also can get
13170   // immediately zapped in a weak reference.  Note that we explicitly
13171   // allow ObjCStringLiterals, since those are designed to never really die.
13172   RHS = RHS->IgnoreParenImpCasts();
13173 
13174   // This enum needs to match with the 'select' in
13175   // warn_objc_arc_literal_assign (off-by-1).
13176   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
13177   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
13178     return false;
13179 
13180   S.Diag(Loc, diag::warn_arc_literal_assign)
13181     << (unsigned) Kind
13182     << (isProperty ? 0 : 1)
13183     << RHS->getSourceRange();
13184 
13185   return true;
13186 }
13187 
13188 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
13189                                     Qualifiers::ObjCLifetime LT,
13190                                     Expr *RHS, bool isProperty) {
13191   // Strip off any implicit cast added to get to the one ARC-specific.
13192   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
13193     if (cast->getCastKind() == CK_ARCConsumeObject) {
13194       S.Diag(Loc, diag::warn_arc_retained_assign)
13195         << (LT == Qualifiers::OCL_ExplicitNone)
13196         << (isProperty ? 0 : 1)
13197         << RHS->getSourceRange();
13198       return true;
13199     }
13200     RHS = cast->getSubExpr();
13201   }
13202 
13203   if (LT == Qualifiers::OCL_Weak &&
13204       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
13205     return true;
13206 
13207   return false;
13208 }
13209 
13210 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
13211                               QualType LHS, Expr *RHS) {
13212   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
13213 
13214   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
13215     return false;
13216 
13217   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
13218     return true;
13219 
13220   return false;
13221 }
13222 
13223 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
13224                               Expr *LHS, Expr *RHS) {
13225   QualType LHSType;
13226   // PropertyRef on LHS type need be directly obtained from
13227   // its declaration as it has a PseudoType.
13228   ObjCPropertyRefExpr *PRE
13229     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
13230   if (PRE && !PRE->isImplicitProperty()) {
13231     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
13232     if (PD)
13233       LHSType = PD->getType();
13234   }
13235 
13236   if (LHSType.isNull())
13237     LHSType = LHS->getType();
13238 
13239   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
13240 
13241   if (LT == Qualifiers::OCL_Weak) {
13242     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
13243       getCurFunction()->markSafeWeakUse(LHS);
13244   }
13245 
13246   if (checkUnsafeAssigns(Loc, LHSType, RHS))
13247     return;
13248 
13249   // FIXME. Check for other life times.
13250   if (LT != Qualifiers::OCL_None)
13251     return;
13252 
13253   if (PRE) {
13254     if (PRE->isImplicitProperty())
13255       return;
13256     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
13257     if (!PD)
13258       return;
13259 
13260     unsigned Attributes = PD->getPropertyAttributes();
13261     if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
13262       // when 'assign' attribute was not explicitly specified
13263       // by user, ignore it and rely on property type itself
13264       // for lifetime info.
13265       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
13266       if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
13267           LHSType->isObjCRetainableType())
13268         return;
13269 
13270       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
13271         if (cast->getCastKind() == CK_ARCConsumeObject) {
13272           Diag(Loc, diag::warn_arc_retained_property_assign)
13273           << RHS->getSourceRange();
13274           return;
13275         }
13276         RHS = cast->getSubExpr();
13277       }
13278     }
13279     else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
13280       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
13281         return;
13282     }
13283   }
13284 }
13285 
13286 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
13287 
13288 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
13289                                         SourceLocation StmtLoc,
13290                                         const NullStmt *Body) {
13291   // Do not warn if the body is a macro that expands to nothing, e.g:
13292   //
13293   // #define CALL(x)
13294   // if (condition)
13295   //   CALL(0);
13296   if (Body->hasLeadingEmptyMacro())
13297     return false;
13298 
13299   // Get line numbers of statement and body.
13300   bool StmtLineInvalid;
13301   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
13302                                                       &StmtLineInvalid);
13303   if (StmtLineInvalid)
13304     return false;
13305 
13306   bool BodyLineInvalid;
13307   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
13308                                                       &BodyLineInvalid);
13309   if (BodyLineInvalid)
13310     return false;
13311 
13312   // Warn if null statement and body are on the same line.
13313   if (StmtLine != BodyLine)
13314     return false;
13315 
13316   return true;
13317 }
13318 
13319 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
13320                                  const Stmt *Body,
13321                                  unsigned DiagID) {
13322   // Since this is a syntactic check, don't emit diagnostic for template
13323   // instantiations, this just adds noise.
13324   if (CurrentInstantiationScope)
13325     return;
13326 
13327   // The body should be a null statement.
13328   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
13329   if (!NBody)
13330     return;
13331 
13332   // Do the usual checks.
13333   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
13334     return;
13335 
13336   Diag(NBody->getSemiLoc(), DiagID);
13337   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
13338 }
13339 
13340 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
13341                                  const Stmt *PossibleBody) {
13342   assert(!CurrentInstantiationScope); // Ensured by caller
13343 
13344   SourceLocation StmtLoc;
13345   const Stmt *Body;
13346   unsigned DiagID;
13347   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
13348     StmtLoc = FS->getRParenLoc();
13349     Body = FS->getBody();
13350     DiagID = diag::warn_empty_for_body;
13351   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
13352     StmtLoc = WS->getCond()->getSourceRange().getEnd();
13353     Body = WS->getBody();
13354     DiagID = diag::warn_empty_while_body;
13355   } else
13356     return; // Neither `for' nor `while'.
13357 
13358   // The body should be a null statement.
13359   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
13360   if (!NBody)
13361     return;
13362 
13363   // Skip expensive checks if diagnostic is disabled.
13364   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
13365     return;
13366 
13367   // Do the usual checks.
13368   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
13369     return;
13370 
13371   // `for(...);' and `while(...);' are popular idioms, so in order to keep
13372   // noise level low, emit diagnostics only if for/while is followed by a
13373   // CompoundStmt, e.g.:
13374   //    for (int i = 0; i < n; i++);
13375   //    {
13376   //      a(i);
13377   //    }
13378   // or if for/while is followed by a statement with more indentation
13379   // than for/while itself:
13380   //    for (int i = 0; i < n; i++);
13381   //      a(i);
13382   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
13383   if (!ProbableTypo) {
13384     bool BodyColInvalid;
13385     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
13386         PossibleBody->getBeginLoc(), &BodyColInvalid);
13387     if (BodyColInvalid)
13388       return;
13389 
13390     bool StmtColInvalid;
13391     unsigned StmtCol =
13392         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
13393     if (StmtColInvalid)
13394       return;
13395 
13396     if (BodyCol > StmtCol)
13397       ProbableTypo = true;
13398   }
13399 
13400   if (ProbableTypo) {
13401     Diag(NBody->getSemiLoc(), DiagID);
13402     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
13403   }
13404 }
13405 
13406 //===--- CHECK: Warn on self move with std::move. -------------------------===//
13407 
13408 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
13409 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
13410                              SourceLocation OpLoc) {
13411   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
13412     return;
13413 
13414   if (inTemplateInstantiation())
13415     return;
13416 
13417   // Strip parens and casts away.
13418   LHSExpr = LHSExpr->IgnoreParenImpCasts();
13419   RHSExpr = RHSExpr->IgnoreParenImpCasts();
13420 
13421   // Check for a call expression
13422   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
13423   if (!CE || CE->getNumArgs() != 1)
13424     return;
13425 
13426   // Check for a call to std::move
13427   if (!CE->isCallToStdMove())
13428     return;
13429 
13430   // Get argument from std::move
13431   RHSExpr = CE->getArg(0);
13432 
13433   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
13434   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
13435 
13436   // Two DeclRefExpr's, check that the decls are the same.
13437   if (LHSDeclRef && RHSDeclRef) {
13438     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
13439       return;
13440     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
13441         RHSDeclRef->getDecl()->getCanonicalDecl())
13442       return;
13443 
13444     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
13445                                         << LHSExpr->getSourceRange()
13446                                         << RHSExpr->getSourceRange();
13447     return;
13448   }
13449 
13450   // Member variables require a different approach to check for self moves.
13451   // MemberExpr's are the same if every nested MemberExpr refers to the same
13452   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
13453   // the base Expr's are CXXThisExpr's.
13454   const Expr *LHSBase = LHSExpr;
13455   const Expr *RHSBase = RHSExpr;
13456   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
13457   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
13458   if (!LHSME || !RHSME)
13459     return;
13460 
13461   while (LHSME && RHSME) {
13462     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
13463         RHSME->getMemberDecl()->getCanonicalDecl())
13464       return;
13465 
13466     LHSBase = LHSME->getBase();
13467     RHSBase = RHSME->getBase();
13468     LHSME = dyn_cast<MemberExpr>(LHSBase);
13469     RHSME = dyn_cast<MemberExpr>(RHSBase);
13470   }
13471 
13472   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
13473   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
13474   if (LHSDeclRef && RHSDeclRef) {
13475     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
13476       return;
13477     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
13478         RHSDeclRef->getDecl()->getCanonicalDecl())
13479       return;
13480 
13481     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
13482                                         << LHSExpr->getSourceRange()
13483                                         << RHSExpr->getSourceRange();
13484     return;
13485   }
13486 
13487   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
13488     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
13489                                         << LHSExpr->getSourceRange()
13490                                         << RHSExpr->getSourceRange();
13491 }
13492 
13493 //===--- Layout compatibility ----------------------------------------------//
13494 
13495 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
13496 
13497 /// Check if two enumeration types are layout-compatible.
13498 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
13499   // C++11 [dcl.enum] p8:
13500   // Two enumeration types are layout-compatible if they have the same
13501   // underlying type.
13502   return ED1->isComplete() && ED2->isComplete() &&
13503          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
13504 }
13505 
13506 /// Check if two fields are layout-compatible.
13507 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
13508                                FieldDecl *Field2) {
13509   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
13510     return false;
13511 
13512   if (Field1->isBitField() != Field2->isBitField())
13513     return false;
13514 
13515   if (Field1->isBitField()) {
13516     // Make sure that the bit-fields are the same length.
13517     unsigned Bits1 = Field1->getBitWidthValue(C);
13518     unsigned Bits2 = Field2->getBitWidthValue(C);
13519 
13520     if (Bits1 != Bits2)
13521       return false;
13522   }
13523 
13524   return true;
13525 }
13526 
13527 /// Check if two standard-layout structs are layout-compatible.
13528 /// (C++11 [class.mem] p17)
13529 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
13530                                      RecordDecl *RD2) {
13531   // If both records are C++ classes, check that base classes match.
13532   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
13533     // If one of records is a CXXRecordDecl we are in C++ mode,
13534     // thus the other one is a CXXRecordDecl, too.
13535     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
13536     // Check number of base classes.
13537     if (D1CXX->getNumBases() != D2CXX->getNumBases())
13538       return false;
13539 
13540     // Check the base classes.
13541     for (CXXRecordDecl::base_class_const_iterator
13542                Base1 = D1CXX->bases_begin(),
13543            BaseEnd1 = D1CXX->bases_end(),
13544               Base2 = D2CXX->bases_begin();
13545          Base1 != BaseEnd1;
13546          ++Base1, ++Base2) {
13547       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
13548         return false;
13549     }
13550   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
13551     // If only RD2 is a C++ class, it should have zero base classes.
13552     if (D2CXX->getNumBases() > 0)
13553       return false;
13554   }
13555 
13556   // Check the fields.
13557   RecordDecl::field_iterator Field2 = RD2->field_begin(),
13558                              Field2End = RD2->field_end(),
13559                              Field1 = RD1->field_begin(),
13560                              Field1End = RD1->field_end();
13561   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
13562     if (!isLayoutCompatible(C, *Field1, *Field2))
13563       return false;
13564   }
13565   if (Field1 != Field1End || Field2 != Field2End)
13566     return false;
13567 
13568   return true;
13569 }
13570 
13571 /// Check if two standard-layout unions are layout-compatible.
13572 /// (C++11 [class.mem] p18)
13573 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
13574                                     RecordDecl *RD2) {
13575   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
13576   for (auto *Field2 : RD2->fields())
13577     UnmatchedFields.insert(Field2);
13578 
13579   for (auto *Field1 : RD1->fields()) {
13580     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
13581         I = UnmatchedFields.begin(),
13582         E = UnmatchedFields.end();
13583 
13584     for ( ; I != E; ++I) {
13585       if (isLayoutCompatible(C, Field1, *I)) {
13586         bool Result = UnmatchedFields.erase(*I);
13587         (void) Result;
13588         assert(Result);
13589         break;
13590       }
13591     }
13592     if (I == E)
13593       return false;
13594   }
13595 
13596   return UnmatchedFields.empty();
13597 }
13598 
13599 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
13600                                RecordDecl *RD2) {
13601   if (RD1->isUnion() != RD2->isUnion())
13602     return false;
13603 
13604   if (RD1->isUnion())
13605     return isLayoutCompatibleUnion(C, RD1, RD2);
13606   else
13607     return isLayoutCompatibleStruct(C, RD1, RD2);
13608 }
13609 
13610 /// Check if two types are layout-compatible in C++11 sense.
13611 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
13612   if (T1.isNull() || T2.isNull())
13613     return false;
13614 
13615   // C++11 [basic.types] p11:
13616   // If two types T1 and T2 are the same type, then T1 and T2 are
13617   // layout-compatible types.
13618   if (C.hasSameType(T1, T2))
13619     return true;
13620 
13621   T1 = T1.getCanonicalType().getUnqualifiedType();
13622   T2 = T2.getCanonicalType().getUnqualifiedType();
13623 
13624   const Type::TypeClass TC1 = T1->getTypeClass();
13625   const Type::TypeClass TC2 = T2->getTypeClass();
13626 
13627   if (TC1 != TC2)
13628     return false;
13629 
13630   if (TC1 == Type::Enum) {
13631     return isLayoutCompatible(C,
13632                               cast<EnumType>(T1)->getDecl(),
13633                               cast<EnumType>(T2)->getDecl());
13634   } else if (TC1 == Type::Record) {
13635     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
13636       return false;
13637 
13638     return isLayoutCompatible(C,
13639                               cast<RecordType>(T1)->getDecl(),
13640                               cast<RecordType>(T2)->getDecl());
13641   }
13642 
13643   return false;
13644 }
13645 
13646 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
13647 
13648 /// Given a type tag expression find the type tag itself.
13649 ///
13650 /// \param TypeExpr Type tag expression, as it appears in user's code.
13651 ///
13652 /// \param VD Declaration of an identifier that appears in a type tag.
13653 ///
13654 /// \param MagicValue Type tag magic value.
13655 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
13656                             const ValueDecl **VD, uint64_t *MagicValue) {
13657   while(true) {
13658     if (!TypeExpr)
13659       return false;
13660 
13661     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
13662 
13663     switch (TypeExpr->getStmtClass()) {
13664     case Stmt::UnaryOperatorClass: {
13665       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
13666       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
13667         TypeExpr = UO->getSubExpr();
13668         continue;
13669       }
13670       return false;
13671     }
13672 
13673     case Stmt::DeclRefExprClass: {
13674       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
13675       *VD = DRE->getDecl();
13676       return true;
13677     }
13678 
13679     case Stmt::IntegerLiteralClass: {
13680       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
13681       llvm::APInt MagicValueAPInt = IL->getValue();
13682       if (MagicValueAPInt.getActiveBits() <= 64) {
13683         *MagicValue = MagicValueAPInt.getZExtValue();
13684         return true;
13685       } else
13686         return false;
13687     }
13688 
13689     case Stmt::BinaryConditionalOperatorClass:
13690     case Stmt::ConditionalOperatorClass: {
13691       const AbstractConditionalOperator *ACO =
13692           cast<AbstractConditionalOperator>(TypeExpr);
13693       bool Result;
13694       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
13695         if (Result)
13696           TypeExpr = ACO->getTrueExpr();
13697         else
13698           TypeExpr = ACO->getFalseExpr();
13699         continue;
13700       }
13701       return false;
13702     }
13703 
13704     case Stmt::BinaryOperatorClass: {
13705       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
13706       if (BO->getOpcode() == BO_Comma) {
13707         TypeExpr = BO->getRHS();
13708         continue;
13709       }
13710       return false;
13711     }
13712 
13713     default:
13714       return false;
13715     }
13716   }
13717 }
13718 
13719 /// Retrieve the C type corresponding to type tag TypeExpr.
13720 ///
13721 /// \param TypeExpr Expression that specifies a type tag.
13722 ///
13723 /// \param MagicValues Registered magic values.
13724 ///
13725 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
13726 ///        kind.
13727 ///
13728 /// \param TypeInfo Information about the corresponding C type.
13729 ///
13730 /// \returns true if the corresponding C type was found.
13731 static bool GetMatchingCType(
13732         const IdentifierInfo *ArgumentKind,
13733         const Expr *TypeExpr, const ASTContext &Ctx,
13734         const llvm::DenseMap<Sema::TypeTagMagicValue,
13735                              Sema::TypeTagData> *MagicValues,
13736         bool &FoundWrongKind,
13737         Sema::TypeTagData &TypeInfo) {
13738   FoundWrongKind = false;
13739 
13740   // Variable declaration that has type_tag_for_datatype attribute.
13741   const ValueDecl *VD = nullptr;
13742 
13743   uint64_t MagicValue;
13744 
13745   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
13746     return false;
13747 
13748   if (VD) {
13749     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
13750       if (I->getArgumentKind() != ArgumentKind) {
13751         FoundWrongKind = true;
13752         return false;
13753       }
13754       TypeInfo.Type = I->getMatchingCType();
13755       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
13756       TypeInfo.MustBeNull = I->getMustBeNull();
13757       return true;
13758     }
13759     return false;
13760   }
13761 
13762   if (!MagicValues)
13763     return false;
13764 
13765   llvm::DenseMap<Sema::TypeTagMagicValue,
13766                  Sema::TypeTagData>::const_iterator I =
13767       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
13768   if (I == MagicValues->end())
13769     return false;
13770 
13771   TypeInfo = I->second;
13772   return true;
13773 }
13774 
13775 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
13776                                       uint64_t MagicValue, QualType Type,
13777                                       bool LayoutCompatible,
13778                                       bool MustBeNull) {
13779   if (!TypeTagForDatatypeMagicValues)
13780     TypeTagForDatatypeMagicValues.reset(
13781         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
13782 
13783   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
13784   (*TypeTagForDatatypeMagicValues)[Magic] =
13785       TypeTagData(Type, LayoutCompatible, MustBeNull);
13786 }
13787 
13788 static bool IsSameCharType(QualType T1, QualType T2) {
13789   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
13790   if (!BT1)
13791     return false;
13792 
13793   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
13794   if (!BT2)
13795     return false;
13796 
13797   BuiltinType::Kind T1Kind = BT1->getKind();
13798   BuiltinType::Kind T2Kind = BT2->getKind();
13799 
13800   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
13801          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
13802          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
13803          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
13804 }
13805 
13806 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
13807                                     const ArrayRef<const Expr *> ExprArgs,
13808                                     SourceLocation CallSiteLoc) {
13809   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
13810   bool IsPointerAttr = Attr->getIsPointer();
13811 
13812   // Retrieve the argument representing the 'type_tag'.
13813   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
13814   if (TypeTagIdxAST >= ExprArgs.size()) {
13815     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
13816         << 0 << Attr->getTypeTagIdx().getSourceIndex();
13817     return;
13818   }
13819   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
13820   bool FoundWrongKind;
13821   TypeTagData TypeInfo;
13822   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
13823                         TypeTagForDatatypeMagicValues.get(),
13824                         FoundWrongKind, TypeInfo)) {
13825     if (FoundWrongKind)
13826       Diag(TypeTagExpr->getExprLoc(),
13827            diag::warn_type_tag_for_datatype_wrong_kind)
13828         << TypeTagExpr->getSourceRange();
13829     return;
13830   }
13831 
13832   // Retrieve the argument representing the 'arg_idx'.
13833   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
13834   if (ArgumentIdxAST >= ExprArgs.size()) {
13835     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
13836         << 1 << Attr->getArgumentIdx().getSourceIndex();
13837     return;
13838   }
13839   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
13840   if (IsPointerAttr) {
13841     // Skip implicit cast of pointer to `void *' (as a function argument).
13842     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
13843       if (ICE->getType()->isVoidPointerType() &&
13844           ICE->getCastKind() == CK_BitCast)
13845         ArgumentExpr = ICE->getSubExpr();
13846   }
13847   QualType ArgumentType = ArgumentExpr->getType();
13848 
13849   // Passing a `void*' pointer shouldn't trigger a warning.
13850   if (IsPointerAttr && ArgumentType->isVoidPointerType())
13851     return;
13852 
13853   if (TypeInfo.MustBeNull) {
13854     // Type tag with matching void type requires a null pointer.
13855     if (!ArgumentExpr->isNullPointerConstant(Context,
13856                                              Expr::NPC_ValueDependentIsNotNull)) {
13857       Diag(ArgumentExpr->getExprLoc(),
13858            diag::warn_type_safety_null_pointer_required)
13859           << ArgumentKind->getName()
13860           << ArgumentExpr->getSourceRange()
13861           << TypeTagExpr->getSourceRange();
13862     }
13863     return;
13864   }
13865 
13866   QualType RequiredType = TypeInfo.Type;
13867   if (IsPointerAttr)
13868     RequiredType = Context.getPointerType(RequiredType);
13869 
13870   bool mismatch = false;
13871   if (!TypeInfo.LayoutCompatible) {
13872     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
13873 
13874     // C++11 [basic.fundamental] p1:
13875     // Plain char, signed char, and unsigned char are three distinct types.
13876     //
13877     // But we treat plain `char' as equivalent to `signed char' or `unsigned
13878     // char' depending on the current char signedness mode.
13879     if (mismatch)
13880       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
13881                                            RequiredType->getPointeeType())) ||
13882           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
13883         mismatch = false;
13884   } else
13885     if (IsPointerAttr)
13886       mismatch = !isLayoutCompatible(Context,
13887                                      ArgumentType->getPointeeType(),
13888                                      RequiredType->getPointeeType());
13889     else
13890       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
13891 
13892   if (mismatch)
13893     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
13894         << ArgumentType << ArgumentKind
13895         << TypeInfo.LayoutCompatible << RequiredType
13896         << ArgumentExpr->getSourceRange()
13897         << TypeTagExpr->getSourceRange();
13898 }
13899 
13900 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
13901                                          CharUnits Alignment) {
13902   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
13903 }
13904 
13905 void Sema::DiagnoseMisalignedMembers() {
13906   for (MisalignedMember &m : MisalignedMembers) {
13907     const NamedDecl *ND = m.RD;
13908     if (ND->getName().empty()) {
13909       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
13910         ND = TD;
13911     }
13912     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
13913         << m.MD << ND << m.E->getSourceRange();
13914   }
13915   MisalignedMembers.clear();
13916 }
13917 
13918 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
13919   E = E->IgnoreParens();
13920   if (!T->isPointerType() && !T->isIntegerType())
13921     return;
13922   if (isa<UnaryOperator>(E) &&
13923       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
13924     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
13925     if (isa<MemberExpr>(Op)) {
13926       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
13927       if (MA != MisalignedMembers.end() &&
13928           (T->isIntegerType() ||
13929            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
13930                                    Context.getTypeAlignInChars(
13931                                        T->getPointeeType()) <= MA->Alignment))))
13932         MisalignedMembers.erase(MA);
13933     }
13934   }
13935 }
13936 
13937 void Sema::RefersToMemberWithReducedAlignment(
13938     Expr *E,
13939     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
13940         Action) {
13941   const auto *ME = dyn_cast<MemberExpr>(E);
13942   if (!ME)
13943     return;
13944 
13945   // No need to check expressions with an __unaligned-qualified type.
13946   if (E->getType().getQualifiers().hasUnaligned())
13947     return;
13948 
13949   // For a chain of MemberExpr like "a.b.c.d" this list
13950   // will keep FieldDecl's like [d, c, b].
13951   SmallVector<FieldDecl *, 4> ReverseMemberChain;
13952   const MemberExpr *TopME = nullptr;
13953   bool AnyIsPacked = false;
13954   do {
13955     QualType BaseType = ME->getBase()->getType();
13956     if (ME->isArrow())
13957       BaseType = BaseType->getPointeeType();
13958     RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
13959     if (RD->isInvalidDecl())
13960       return;
13961 
13962     ValueDecl *MD = ME->getMemberDecl();
13963     auto *FD = dyn_cast<FieldDecl>(MD);
13964     // We do not care about non-data members.
13965     if (!FD || FD->isInvalidDecl())
13966       return;
13967 
13968     AnyIsPacked =
13969         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
13970     ReverseMemberChain.push_back(FD);
13971 
13972     TopME = ME;
13973     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
13974   } while (ME);
13975   assert(TopME && "We did not compute a topmost MemberExpr!");
13976 
13977   // Not the scope of this diagnostic.
13978   if (!AnyIsPacked)
13979     return;
13980 
13981   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
13982   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
13983   // TODO: The innermost base of the member expression may be too complicated.
13984   // For now, just disregard these cases. This is left for future
13985   // improvement.
13986   if (!DRE && !isa<CXXThisExpr>(TopBase))
13987       return;
13988 
13989   // Alignment expected by the whole expression.
13990   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
13991 
13992   // No need to do anything else with this case.
13993   if (ExpectedAlignment.isOne())
13994     return;
13995 
13996   // Synthesize offset of the whole access.
13997   CharUnits Offset;
13998   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
13999        I++) {
14000     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
14001   }
14002 
14003   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
14004   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
14005       ReverseMemberChain.back()->getParent()->getTypeForDecl());
14006 
14007   // The base expression of the innermost MemberExpr may give
14008   // stronger guarantees than the class containing the member.
14009   if (DRE && !TopME->isArrow()) {
14010     const ValueDecl *VD = DRE->getDecl();
14011     if (!VD->getType()->isReferenceType())
14012       CompleteObjectAlignment =
14013           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
14014   }
14015 
14016   // Check if the synthesized offset fulfills the alignment.
14017   if (Offset % ExpectedAlignment != 0 ||
14018       // It may fulfill the offset it but the effective alignment may still be
14019       // lower than the expected expression alignment.
14020       CompleteObjectAlignment < ExpectedAlignment) {
14021     // If this happens, we want to determine a sensible culprit of this.
14022     // Intuitively, watching the chain of member expressions from right to
14023     // left, we start with the required alignment (as required by the field
14024     // type) but some packed attribute in that chain has reduced the alignment.
14025     // It may happen that another packed structure increases it again. But if
14026     // we are here such increase has not been enough. So pointing the first
14027     // FieldDecl that either is packed or else its RecordDecl is,
14028     // seems reasonable.
14029     FieldDecl *FD = nullptr;
14030     CharUnits Alignment;
14031     for (FieldDecl *FDI : ReverseMemberChain) {
14032       if (FDI->hasAttr<PackedAttr>() ||
14033           FDI->getParent()->hasAttr<PackedAttr>()) {
14034         FD = FDI;
14035         Alignment = std::min(
14036             Context.getTypeAlignInChars(FD->getType()),
14037             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
14038         break;
14039       }
14040     }
14041     assert(FD && "We did not find a packed FieldDecl!");
14042     Action(E, FD->getParent(), FD, Alignment);
14043   }
14044 }
14045 
14046 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
14047   using namespace std::placeholders;
14048 
14049   RefersToMemberWithReducedAlignment(
14050       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
14051                      _2, _3, _4));
14052 }
14053